April 28, 2019, 1:36 p.m.

Django

Django, Model, Reset

In the process of developing a project on Django, we may encounter an unpleasant situation when some packages and modules were removed and, accordingly, models from these packages were no longer used. But at the same time, squash of application migrations does not allow removing these packages, since migrations have many circular dependencies. As a result, removing unnecessary packages becomes a rather difficult task. Since resolving such dependencies becomes a non-trivial task. For me, such an unpleasant package was Django CKEditor, which was present almost everywhere. As a result, this package due to migrations remained for quite a long time in the list of requirements.txt, although in fact it was not used on the site at all.

April 24, 2019, 7:42 a.m.

Django

Django, Application, Model

I would like to share one of the possible way for moving the data model from one application to another.

Immediately, I note that this version of the data model transfer is not 100% working and you may need additional manual editing of the tables to correctly set the Content Type. Since any such modifications are fraught with data loss for GenericForeignKey relationships.

In my case, GenericForeignKey was not used, so there was no such problem.

April 23, 2019, 8:10 a.m.

Django

Mac, Homebrew, Nginx, MacOS, Python, Apple, Django

I propose to consider the process of installing and configuring a Django project on Mac OS X based on an existing project.

Some steps will be similar to those already performed in the Django setup article for Ubuntu .

MU
March 10, 2019, 5:01 p.m.
Maciej Urmański

Hi, I try to show user object from category which they subscribe. But don't know exacly how.

I have four models: Board ( category ) Subject Embed and Subscribe (foreign to user and to board)

class Board(models.Model):
    title = models.CharField(max_length=255, verbose_name='Tytuł')
    slug = AutoSlugField(populate_from='title', unique=True)
    image = models.ImageField(upload_to='board-cover', verbose_name='Tło kategorii', null=True, blank=True)
    body = models.TextField(verbose_name='Opis kategorii')
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    created_at = models.DateTimeField(auto_now_add=True)

class Subscribe(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='subscribed_users')
    board = models.ForeignKey(Board, on_delete=models.CASCADE, related_name='subscribed_boards')
    created_at = models.DateTimeField(auto_now_add=True)
    subscribe = models.BooleanField(default=False)

class Subject(models.Model):
    title = models.CharField(max_length=255, verbose_name='Tytuł')
    slug = AutoSlugField(populate_from='title', unique=True)
    body = models.TextField(blank=True, verbose_name='Treść')
    image = models.ImageField(upload_to='subject', null=True, blank=True)
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    active = models.BooleanField(default=True)
    created_at = models.DateTimeField(auto_now_add=True)
    board = models.ForeignKey(Board, on_delete=models.CASCADE, related_name='subjects', verbose_name='Kategoria')
    votes = GenericRelation(LikeDislike, related_query_name='subjectsvotes')

class Embed(models.Model):
    url = models.URLField(max_length=255)
    title = models.CharField(max_length=255)
    description = models.TextField()
    thumbnail_url = models.URLField(max_length=255)
    html = models.TextField()
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    created_at = models.DateTimeField(auto_now_add=True)
    board = models.ForeignKey(Board, on_delete=models.CASCADE, blank=True, null=True, related_name='embeds')
    votes = GenericRelation(LikeDislike, related_query_name='embedvotes')

In my views I try something like this:

def feed(request):
    embeds = Embed.objects.filter(author=request.user)
    subscribed_ids = request.user.subscribed_users.values_list('id', flat=True)

    actions = embeds.filter(author_id__in=subscribed_ids)
    actions = actions[:10]

    return render(request, 'boards/feed.html',
                {'actions': actions})

but nothing show up.

MU
March 7, 2019, 10:01 a.m.
Maciej Urmański

Hi,

I try to save foreign key in django restframework serializer.

My goal is to save in database information from iframely.com and this part works good. But I need to also save it in specific category. After add field "Board(my category name field)" I have error: null value in column "board_id" violates not-null constraint

Maybe here someone help me.

My model:

class Embed(models.Model):
    url = models.URLField(max_length=255)
    title = models.CharField(max_length=255)
    description = models.TextField()
    thumbnail_url = models.URLField(max_length=255)
    html = models.TextField()
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    board = models.ForeignKey(Board, on_delete=models.CASCADE, verbose_name='Kategoria')

Form:

class SubmitEmbed(forms.Form):
    url = forms.URLField()
    board = forms.ModelChoiceField(queryset=Board.objects.all())

Serializer:

class EmbedSerializer(serializers.ModelSerializer):
    author = serializers.HiddenField(default=serializers.CurrentUserDefault())
    board = serializers.RelatedField(read_only=True)

    class Meta:
        model = Embed
        fields = '__all__'

View:

def save_embed(request):

    if request.method == "POST":
        form = SubmitEmbed(request.POST)
        if form.is_valid():
            url = form.cleaned_data['url']
            r = requests.get('http://iframe.ly/api/oembed?url=' + url + '&key=' + settings.IFRAMELY_KEY)
            json = r.json()
            serializer = EmbedSerializer(data=json, context={'request': request})
            if serializer.is_valid():
                embed = serializer.save()
                return render(request, 'embed/embeds.html', {'embed': embed})
    else:
        form = SubmitEmbed()

    return render(request, 'embed/embedadd.html', {'form': form})
MU
Feb. 20, 2019, 2:11 p.m.
Maciej Urmański

Hi, i try to create list of users attendance in goal app.

But i don't know how to filter user.

I have Goal model:

class Goal(models.Model, Activity):
    title = models.CharField(max_length=255, verbose_name='Tytuł')
    image = ImageField(blank=True, verbose_name='Tło')
    body = HTMLField(verbose_name='Treść')
    tags = TaggableManager()
    created_at = models.DateTimeField(auto_now_add=True)
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    slug = AutoSlugField(populate_from='title')

and Joined model:

class Joined(models.Model, Activity):
    goal = models.ForeignKey(Goal, on_delete=models.CASCADE, related_name='joined')
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='joined_users')
    created_at = models.DateTimeField(auto_now_add=True)
    joined = models.BooleanField(default=False)

I try:

def goalusers(request, slug):
    goal = get_object_or_404(Goal, slug=slug)

    users = goal.joined_users.all()

    return render(request, 'goals/users.html',
                {'goal': goal,
                'users': users})

This makes error: 'Goal' object has no attribute 'joined_users'.

I try also:

users = User.objects.filter(joined_users__joined__in=goal)

but then error is: 'Goal' object is not iterable.

MU
Feb. 13, 2019, 11:30 p.m.
Maciej Urmański

Hi,

I search through internet and review many apps but still don't have answer maybe on this forum someone help me.

I try to create changing button after user join to Goal.

I have work buttons, but i don't know how to change this in template.

I try to do this with boolean field, when user click "Join", boolean field change to True, and then in templates:

{% if goal.joined %}
<Delete join>
{% else %}
<join to goal>
{% endif %}

For now user can click many times on button and create many "join" objects in one goal. Now i know that i need to create variable in view that checks if the current user has joined the goal and add it to the context. But I don't know how. Im still newby.

class Goal(models.Model, Activity):
    title = models.CharField(max_length=255, verbose_name='Tytuł')
    image = models.ImageField(upload_to='goals', verbose_name='Tło')
    body = HTMLField(verbose_name='Treść')
    tags = TaggableManager()
    created_at = models.DateTimeField(auto_now_add=True)
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    slug = AutoSlugField(populate_from='title')

    def __str__(self):
        return self.title

    class Meta:
        verbose_name = 'Cele'
        ordering = ['-created_at']

    def get_absolute_url(self):
        return reverse('goaldetail', args=[str(self.slug)])

    @property
    def activity_actor_attr(self):
        return self.author

    def add_user_to_list_of_attendees(self, user):
        registration = Joined.objects.create(user = user,
                                                    goal = self,
                                                    created_at = timezone.now())

    def remove_user_from_list_of_attendees(self, user):
        registration = Joined.objects.get(user = user, goal = self)
        registration.delete()

class Joined(models.Model, Activity):
    goal = models.ForeignKey(Goal, on_delete=models.CASCADE, related_name='joined')
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='joined_users')
    created_at = models.DateTimeField(auto_now_add=True)
    joined = models.BooleanField(default=False)

    def save(self, *args, **kwargs):
        if self.id is None and self.created_at is None:
            self.created_at = datetime.datetime.now()
        self.joined = True
        super(Joined, self).save(*args, **kwargs)

    @property
    def activity_actor_attr(self):
        return self.user

Views:

def joined_add(request, pk):
    this_goal = Goal.objects.get(pk=pk)
    this_goal.add_user_to_list_of_attendees(user=request.user)
    return redirect('goaldetail', slug=this_goal.slug)

def joined_delete(request, pk):
    this_goal = Goal.objects.get(pk=pk)
    this_goal.remove_user_from_list_of_attendees(request.user)
    return redirect('goaldetail', slug=this_goal.slug)

def goaldetail(request, slug):
    goal = get_object_or_404(Goal, slug=slug)
    return render(request, 'goals/detail.html',
                {'goal': goal})

Path:

path('joined/<int:pk>', views.joined_add, name='joined_add'),
path('joined-delete/<int:pk>', views.joined_delete, name='joined_delete'),
Feb. 8, 2019, 11:51 a.m.
Arrow

Добрый день!

Пытаюсь на django реализовать удаление записи, а диалог подтверждение удаления хочу вынести в модальное окно.

Файл views.py:

class DeleteObject(LoginRequiredMixin, DeleteView):
    model = Object
    template_name = 'todoList/home.html'

    def get(self, request, *args, **kwargs):
        obj = get_object_or_404(Object, id=self.kwargs.get('id'))
        # Check for uncompleted tasks
        uncompleted = Data.objects.filter(objects=obj).filter(state=False).count()

        if uncompleted == 0:
            obj.delete()
        return redirect('home')

То есть реализовал удаление сразу при клике на ссылку удаления записи.

Пытаюсь в шаблоне (*.html) сделать так:

<div class="dropdown">
    <div class="circle dropdown-toggle ml-2" data-toggle="dropdown"></div>
    <div class="dropdown-menu">
        <a class="dropdown-item" href="{% url 'obj_update' object.id %}">Edit</a>
        <a class="dropdown-item" data-toggle="modal" data-target="#taskModal" OnClick="getId('{{ object.id }}')">Delete</a>

        <script language="javascript">
            function getId(objID) {
                link = "{% url 'del_obj' " + objID + " %}"; // Error
                objdel.setAttribute('href', link);
            };
        </script>
    </div>   
</div>

<div id="taskModal" class="modal fade">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title">Confirm deletion</h4>
            </div>
            <div class="modal-body">Are your sure you want to delete?</div>
            <div class="modal-footer">
                <a id="objdel" class="btn btn-danger" type="button" data-dismiss="modal" href="">Delete</a>
                <a class="btn btn-secondary" type="button" data-dismiss="modal">Cancel</a>
            </div>
        </div>
    </div>
</div>

Пытаюсь в атрибут href="" объекта id="objdel" впихнуть "{% url 'del_obj' " + objID + " %}", чтобы при клике в диалоге на "Delete" удалялась запись.

В строке "link = "{% url 'del_obj' " + objID + " %}";" ругается на то что objID не подходит в качестве параметра для "del_obj".

Возможно есть способ реализовать это по другому или я не правильно передаю ссылку?

MU
Feb. 4, 2019, 5:46 p.m.
Maciej Urmański

Hi, maybe this community help me.

I try integrate Getstream.io on my project. Following this code: https://github.com/GetStream/django_twitter I create most things like activity feed and notification but i don't know how to create a form to follow other people on profile page. (userdetailpage)

Code say how to create follow button on user list page but no on detail page.

Code to follow other people on list user page:

# Views

class DiscoverView(TemplateView):
    template_name = 'stream_twitter/follow_form.html'

    def get_context_data(self):
        context = super(DiscoverView, self).get_context_data()

        users = User.objects.order_by('date_joined')[:50]
        following = []
        for i in users:
            if len(i.followers.filter(user=self.request.user.id)) == 0:
                following.append((i, False))
            else:
                following.append((i, True))

        context['users'] = users,
        context['form'] = FollowForm()
        context['login_user'] = self.request.user
        context['following'] = following

return context

class FollowView(CreateView):
    form_class = FollowForm
    model = Follow
    success_url = reverse_lazy('timeline_feed')

    def form_valid(self, form):
        form.instance.user = self.request.user
        return super(FollowView, self).form_valid(form)


class UnfollowView(DeleteView):
    model = Follow
    success_url = reverse_lazy('timeline_feed')

    def get_object(self):
        target_id = self.kwargs['target_id']
return self.get_queryset().get(target__id=target_id)

#Forms
class FollowForm(forms.ModelForm):

    class Meta:
        exclude = set()
        model = Follow

#Urls

    path('follow/', login_required(views.FollowView.as_view()), name='follow'),
    re_path(r'^unfollow/(?P<target_id>\d+)/', login_required(views.UnfollowView.as_view()),
    name='unfollow'),

#Template

    {% for one, followed in following %}
    <div class="col-md-3 col-sm-6 col-xs-12">
      <div class="user">
      {% include "stream_twitter/_user.html" with user=one %}
      <div class="follow-button">
       <form action="{% if followed %}{% url 'unfollow' one.id %}{% else %}{% url 'follow' %}{% endif %}" method="post">
        {% csrf_token %}
        <input type="hidden" id="id_target" name="target" value="{{one.id}}">
        <input type="hidden" id="id_user" name="user" value="{{user.id}}">
        <button type="submit" class="btn btn-primary" value="Create" />
        {% if followed %}
          Unfollow
        {% else %}
          Follow
        {% endif %}
        </button> 
      </form>
      </div>
      </div>
    </div>
    {% if forloop.counter|divisibleby:'4' %}
    <div class="clearfix visible-sm-block visible-md-block visible-lg-block"></div>
    {% elif forloop.counter|divisibleby:'2' %}
    <div class="clearfix visible-sm-block"></div>
    {% endif %}
{% endfor %}
Jan. 29, 2019, 7:53 a.m.

Django

Django, Python

Когда вы разрабатываете большой проект, случайно можно забыть некоторые части кода, которые нужно протестировать. Coverage.py - это инструмент на python, который поможет вам в этом.

m
May 19, 2019, 1:49 a.m.
mahhaki

Qt - Test 001. Signals and slots

  • Result:78points,
  • Rating points2
S
May 17, 2019, 1:14 p.m.
SunBro

Qt - Test 001. Signals and slots

  • Result:42points,
  • Rating points-8
b
May 17, 2019, 4:18 a.m.
banana

C++ - Тест 003. Условия и циклы

  • Result:57points,
  • Rating points-2
Last comments
May 21, 2019, 8:10 p.m.
Дмитрий

Приветствую! Я думаю дойдёт и до этого, но пока изучать его у меня нет желания.
May 20, 2019, 7:20 p.m.
Евгений Легоцкой

Добрый день! Вы не думали разместить репозиторий проекта на GitHub?
P.
May 18, 2019, 2:03 p.m.
PELMYACH .

Спасибо большое! Вскоре буду разбираться!
May 18, 2019, 9:13 a.m.
Евгений Легоцкой

Добрый день! Отнимать значение общего счётчика можно в деструкторе класса кнопки QDynamicButton::~QDynamicButton(){ ResID--;} При этом я бы ещё переустанавливал значения вс...
P.
May 14, 2019, 10:33 p.m.
PELMYACH .

Здравствуйте!А не подскажите, как можно при удалении какой либо кнопки, у щётчика отнять значение?Дабы например четвёртой кнопке соответствовал ID 4, а не 5 скажем
Now discuss on the forum
ДТ
May 22, 2019, 1:40 p.m.
Даниил Тетерин

Есть задание - сделать программу-расписание, где главное окно - календарь, в котором можно нажать на любой день, тогда откроется окно, в котором будут видны уже существующие на этот день зад...
В
May 22, 2019, 10:05 a.m.
Владислав

Данный код компилируется только для 32 битной системы, а на 64 битной выдаёт ошибку линковки LNK2019. Возможно ли как-то, используя функцию RegisterHotKey, использовать глобальные горячие клав...
I
May 22, 2019, 5:08 a.m.
Intruder

Евгений, доброго времени суток и спасибо! Все получилось.
May 20, 2019, 8:43 a.m.
Михаиллл

Кинул библиотеки в папку с проектом и в папку к компилируемым файлам.В файле проекта прописал так, но все равно выдает ту же ошибку QT += core gui networkgreaterThan(QT_MAJOR_VERSI...
May 20, 2019, 1:47 a.m.
linq

Что вы понимаете под статической сборкой приложений? В какой среде?

For registered users on the site there is a minimum amount of advertising

EVILEG
About
Services
Join us
© EVILEG 2015-2019
Recommend hosting TIMEWEB