Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to iterate iterate over a list a filter it according to a second list
I have a list of videos that belong to courses. I want to display those videos in a template grouped by courses: first all videos from a course, then a separator and all the videos of the next course. I already have a query_set grouped by course but I cannot find out how to display them separated in my html file. Any hints? Ideas? -
how to include template with context in navbar?
In base.html I have included navbar {% include 'partials/navbar.html' %}, now I need to do context for navbar.html. I trying to make context for navbar.html in this way: view.py def unread_conversation(request): if request.user.is_authenticated: conversations_all = Conversation.objects.filter(Q(starter=request.user) | Q(receiver=request.user)) for conversation in conversations_all: unread = Message.objects.filter(Q(conversation_id=conversation.pk) & Q(seen=False) & ~Q(user=request.user)) context = { 'unread': unread } return render(request, 'conversations/unread_message.html', context) else: messages.error(request, 'register please') return redirect('register') unread_message.html {% if unread %} <span>You have new message</span> {% endif %} navbar.html {% include 'conversations/unread_message.html' with unread=unread %} but it does not work for me, can you correct my way or offer me a better way of this? -
How to ensure idempotency in a Django REST API?
Say, I'm building a REST API based on Django/DRF and PostgreSQL. I want all GET, PUT, DELETE endpoints to follow the best practices and be idempotent. How can I ensure/verify that this is true? -
How to set Django model default value equal to result of a query
I'm quite new at Django, and trying to create a model where det default value for Foreign Keys user and department are set to the correct values for the logged in user. Normally I use the request object and queries the database, but in the model definition I don't know how to do this. I suppose a path forward is to make default value a function and make the query in the function, but I am stuck. Any help are greatly appreciated . Here is an example of my code: from django.contrib.auth import get_user_model from django.db import models from another_app.models import Department, DepartmentPermissions class Article(models.Model): header = models.CharField(max_length=200) text = models.CharField(max_length=800) owner = models(get_user_model(), related_name='owner_article', on_delete=models.PROTECT) department = models.ForeignKey(Department, on_delete=models.CASCADE) #here I want it defaulted to DepartmentPermissions.objets.get(user= <logged in user>)[0].department -
How to design a model and its child django
How to design a model in django for storing below JSON values in a single model class Bus(models.Model): source = models.CharField(max_length=200) destination = models.CharField(max_length=200) type= models.CharField(max_length=200) price=models.FloatField() I need to accept below json to accept and store in same table if i can use ListField , then how it will be for connections { "source": "delhi", "destination": "pune", "type": "Economy", "price":300.0, "Connections": [ { "source": "lon", "destination": "liverpool", "type": "luxury", }, { "source": "banglur", "destination": "cochin", "type": "luxury", } ], } -
How to have Django templates display slugs
Hi guys i am new to django...i been watching youtube videos and reading books on Django but am still struggling with templates. I am working on a ecommerce project and i would love a bit of help with templates. So i want my template to display a list of categories as links on a sidebar. I have defined a slug field in my category models and i have managed to map a url...but i am still not getting a list of categories on my index page sidebar. This is my url pattern and this is working perfect. When i click 127.0.0.1.000/food it's working (food is a category) path('<slug:category_slug>/', views.category, name='category'), the view function def category(request, category_slug): """Defines category views""" categories= get_object_or_404(Category, slug= category_slug) context = {'categories': categories} return render(request, "categories_list.html", context) This is the categories_list.html template that i need help with <h3> Shop by Category </h3> {% if category in categories %} <li> <a href ="{{category.slug}}"> {{category.name}}</a> </li> {% endif %} My wish is to have the categories displayed on the sidebar of my index page as links. I have used {% include 'category_list.html' %} on my index page template, and its only displaying the Shop by Category heading instead … -
Get List of Categories on the basis of foreign model in django
I've two models as below. class Category(models.Model): title = models.CharField(max_length=55) class Meta: verbose_name = 'Food Category' verbose_name_plural = 'Food Categories' def __str__(self): return self.title class FoodItem(TimeStampWithCreator): CATEGORY_CHOICES = ( ('takeway', 'Takeaway'), ('dine_in', 'Dine In'), ('function', 'Function'), ) type_menu_select = models.CharField(max_length=20, choices=CATEGORY_CHOICES, default='takeway') category = models.ForeignKey(FoodCategory, on_delete=models.CASCADE) i want to filter all the categories containing takeaway, I've no idea how to achieve this -
DJango user not logging out
I'm new to DJango and I'm trying to make a user auth. My login is working fine but my user isn't logging out. My Logout view is: from django.contrib.auth import logout from django.contrib.auth.models import User class LogoutView(generic.View): @staticmethod def get(request): if User.is_authenticated: # Debug statement print('if') logout(request) return redirect('login') else: print('ekse') return redirect('index') My url is working fine because when i go to /logout/, My debug statement executes but if User.is_authenticated: always returns an object(true). How can I resolve this issue. Thanks -
Same query set, different result in django
I get a different result when I filter another time with the same filters. This code is part of the get_queryset() of a class that inherits ListAPIView. validity_filters = Q( ( ( Q(display_publisher_group__publishers__id__exact=98) | Q(display_publisher_group__isnull=True) ) & ( ~Q(blacklist_publisher_group__publishers__id__exact=98) ) ) ) campaigns = Campaign.objects.filter(validity_filters) print(1, campaigns.distinct().count()) campaigns = campaigns.filter(validity_filters) print(2, campaigns.distinct().count()) The output is: 1 33276 2 33275 -
App 'category' doesn't provide model 'category'
Django==3.0.6 class Category(CommentMixin, TitleMixin, SlugMixin, models.Model): pass from category.models import Category class Post(TitleMixin, SlugMixin, DescriptionMixin, models.Model): ... category = models.ForeignKey(Category, on_delete=models.PROTECT, related_name='blog_posts') The database has been dropped and recreated. All migrations have been deleted. In settings.py 'post' and 'category' are added. When making migrations: ValueError: The field post.Post.category was declared with a lazy reference to 'category.category', but app 'category' doesn't provide model 'category'. Could you help me understand what is going on here? -
I am getting error ModuleNotFoundError: No module named 'rest_framework'
if I try to install rest fremwork by command pip3 install Django rest framework then it is showing Requirement already satisfied. -
How to handle AJAX POST request in Django
I have a sort of twitter like button function in my app such that, when the button is clicked, it triggers an AJAX call and performs the action specified in the views. However, when i click the button, it does not perform action in views. The code reaches the 'like view' but does not execute anything after 'if request.POST:'. Please help. Menu.html <form action="{% url 'like'%}" id="plt_{{menu.id}}" data-id="{{menu.id}}" method="post"> {%csrf_token%} <input name="menu_id" type="hidden" value="{{ menu.id }}"> <div class="like-button" id="btn_{{menu.id}}"></div> </form> <script> $('.like-button').on('click', function () { var id = $(this).attr('id'); id = id.replace('btn_',''); $(this).toggleClass('animate').promise().done(function () { var link = $("#plt_"+id).attr('action') $.ajax({ type: 'POST', url: link, headers: {'X-CSRFToken': '{{ csrf_token }}'}, }) }); }); </script> Views.py def like(request): print('reached') //this prints if request.POST: menu = Menu.objects.get(pk=request.POST.get('menu_id')) //execute code to like return HTTPResponse('') -
Django restframework, Authentication credentials were not provided
I took a tutorial in Redox and Django from youtube from Traversy Media. I follow along with the tutorial and now I don't know were it curshed. curl http://localhost:8000/api/auth/login/ -d \ '{"username": "Tom", "password": "PassWord@321"}' \ -H "Content-type: application/json" -X POST By doing so I need to get user and the corresponding token but instead I'm getting {"detail":"Authentication credentials were not provided."} What all I did => # settings.py INSTALLED_APPS = [ 'leads', 'rest_framework', 'frontend', 'accounts', 'knox', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] REST_FRAMEWORK = { "DEFAULT_AUTHENTICATION_CLASSES": ("knox.auth.TokenAuthentication", ), } # serializers.py class LoginSerializer(serializers.Serializer): username = serializers.CharField() password = serializers.CharField() def validate(self, data): user = authenticate(**data) if user and user.is_active: return user raise serializers.ValidationError("Incorrect Credentials") # api.py class LoginAPI(generics.GenericAPIView): serializer_class = LoginSerializer def post(self, request, *args, **kwargs): serializer = self.get_serializer(data = request.data) serializer.is_valid(raise_exception = True) user = serializer.validated_data _, token = AuthToken.objects.create(user) return Response({ "user": UserSerializer(user, context = self.get_serializer_context()).data, "token": token }) # leadmanager/urls.py urlpatterns = [ path("api/auth/", include("accounts.urls")), ] # accounts/urls.py urlpatterns = [ path("login/", LoginAPI.as_view()), ] I don't know were it crushed. -
Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response?
I am using react for my frontend and Django restframework for API. I am getting Access to XMLHttpRequest at 'xxxxxxxx' from origin 'xxxxxxxx' has been blocked by CORS policy: Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response. I have enabled "corsheaders" at my installed app, 'corsheaders.middleware.CorsMiddleware' at Middleware and CORS_ORIGIN_ALLOW_ALL = True and CORS_ALLOW_METHODS = [ 'DELETE', 'GET', 'OPTIONS', 'PATCH', 'POST', 'PUT', ] CORS_ALLOW_HEADERS = [ 'accept', 'accept-encoding', 'authorization', 'content-type', 'dnt', 'origin', 'user-agent', 'x-csrftoken', 'x-requested-with', ] in setting.py. Can anyone guide why i am getting this issue. Whether it is from client side or Server side. -
django.db.utils.OperationalError: no such table - after deleting all Django migrations
I had some issues with my database(design) and deleted all migrations, but not the db.sqlite3 file. I then rewrote my models.py, re-registered them inadmin.py and ran python3 manage.py makemigrations and python3 manage.py migrate. Both seemed to work fine and create the tables. In the Django admin interface, I can see my new tables, but when trying to access them or do something in my views.py with them i get this error (in this case for table orders_dish: django.db.utils.OperationalError: no such table: orders_dish Can anyone help me? Am really stuck here... Below the full traceback: Internal Server Error: /admin/orders/dish/ Traceback (most recent call last): File "/home/anna/py3_cs50W/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "/home/anna/py3_cs50W/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 303, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: no such table: orders_dish The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/anna/py3_cs50W/lib/python3.6/site-packages/django/core/handlers/exception.py", line 35, in inner response = get_response(request) File "/home/anna/py3_cs50W/lib/python3.6/site-packages/django/core/handlers/base.py", line 128, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/anna/py3_cs50W/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/anna/py3_cs50W/lib/python3.6/site-packages/django/contrib/admin/options.py", line 574, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "/home/anna/py3_cs50W/lib/python3.6/site-packages/django/utils/decorators.py", line 142, in _wrapped_view response = view_func(request, *args, **kwargs) File "/home/anna/py3_cs50W/lib/python3.6/site-packages/django/views/decorators/cache.py", line 44, in _wrapped_view_func response … -
Django access fields of model with many to many relationship
So I have the following models: class Image(models.Model): image=models.ImageField(upload_to='postimages') id=models.UUIDField(default=uuid.uuid4, editable=False, unique=True, primary_key=True) class Post(models.Model): title=models.CharField(max_length=500) created_date=models.DateField(auto_now=True) id=models.UUIDField(default=uuid.uuid4, editable=False, unique=True, primary_key=True) images=models.ManyToManyField(Image) user=models.ForeignKey(get_user_model(), on_delete=models.CASCADE, null=True, related_name='posts') In my views I have created a post object like this: post=Post(title=title) post.save() post.images.add(image) Now I need to diplay the image field of the Image model in my homepage. I am trying to do it like this: {%for post in posts%} <img src="{{post.images.image}}"> {%endfor%} But this returns image with src=(unknown). So my question is how do I access the image field of the Image model? -
'NoneType' object has no attribute 'nazev_zanru' although it should have
Good day community, I need your help as I cannot proceed with my project. Django model.py returns an AttributeError: 'NoneType' object has no attribute 'nazev_zanru' My models.py is as follows; from django.db import models class Zanr(models.Model): nazev_zanru = models.CharField(max_length=80, verbose_name="Žánr") def __str__(self): return "Nazev_zanru: {0}".format(self.nazev_zanru) class Meta: verbose_name = "Žánr" verbose_name_plural = "Žánry" class Film(models.Model): nazev = models.CharField(max_length=200, verbose_name="Název Filmu") rezie = models.CharField(max_length=180, verbose_name="Režie") zanr = models.ForeignKey(Zanr, on_delete=models.SET_NULL, null=True, verbose_name="Žánr") def __str__(self): return "Nazev: {0} | Rezie: {1} | Zanr: {2}".format(self.nazev, self.rezie, self.zanr.nazev_zanru) class Meta: verbose_name = "Film" verbose_name_plural = "Filmy" As far as I understand, the def __str__(self): return "Nazev: {0} | Rezie: {1} | Zanr: {2}".format(self.nazev, self.rezie, self.zanr.nazev_zanru) code refers through zanr = models.ForeignKey(Zanr, on_delete=models.SET_NULL, null=True, verbose_name="Žánr") to class Zanr(models.Model): nazev_zanru = models.CharField(max_length=80, verbose_name="Žánr") def __str__(self): return "Nazev_zanru: {0}".format(self.nazev_zanru) ` which is therefore defined. Where is the mistake? Migrations, URLs and admin done. Thank you in advance, David -
Django URL routing
I am learning Django and progressing well but i am stuck on how to configure the different urls to view functions. I created a project TenancyMGt and an app rentals. I have created several views in the module views.py Two are relevant here: def createTenant(request): form = TenantsForm context = {'form': form} html_form = render_to_string('rentals/partial_tenant_create.html', context, request=request, ) return JsonResponse({'html_form': html_form}) class TenantsListView(ListView): model = Tenants context_object_name = 'tenant_list' template_name = 'rentals/tenants_list.html' paginate_by = 5 def get_queryset(self): return Tenants.objects.all() Now i created a file urls.py under the app rentals: from . import views from django.urls import path app_name='rentals' urlpatterns = [ path("", views.TenantsListView.as_view(), name="index"), path("",views.TenantDetailView.as_view,name="detail"), path("",views.createTenant, name='createTenant'), path("<int:pk>/",views.TenantUpdateView.as_view, name='edit'), path("<int:pk>/",views.delete, name='delete'), ] under TenancyMgr/urls, i add the following: from django.contrib import admin from django.urls import path,include from rentals import views urlpatterns = [ path('admin/', admin.site.urls), path('', include('rentals.urls')), ] When i run the server, the index view opens successfully! From the index, i want to open the createTenant view as below. <button type="button" class="btn btn-primary js-create-tenant" data-url="{% url 'rentals:createTenant' %}> <span class="glyphicon glyphicon-plus"></span> New Tenant </button> When the button is clicked, i get the urls below: http://127.0.0.1:8000/rentals/createTenant/ Then i get the response is 404,page not found error. But this opens admin … -
how can I avoid hide lesson content from end user views-template?
I am trying to do this all vip user paid that contains type 2 allow to see the full information , but however it does as expect, but with a minor issue , it hide the lesson to the end-user if this doesnt belong to x user logged. I want to keep lesson displayed to the end-user, but however if the user tries to click to the lesson then display upgrade account instead of hidding content. how can I achieve this? model class Lesson(models.Model): content_title = models.CharField(max_length=120) content_text = models.CharField(max_length=200) thumbnail = models.ImageField(upload_to='xxx/xxx/xxx/xxx/xxx') link = models.CharField(max_length=200, null=True) allowed_memberships = models.ManyToManyField(Membership) def __str__(self): return self.content_title view def get_context_data(self, **kwargs): context = super(bootCamp, self).get_context_data(**kwargs) lesson = Lesson.objects.first() user_membership = UserMembership.objects.filter(user=self.request.user).first() user_membership_type = user_membership.membership.membership_type lesson_allowed_mem_types = lesson.allowed_memberships.all() context['lessons_allowed_mem_types'] = lesson_allowed_mem_types context['lessons'] = None if lesson_allowed_mem_types.filter(membership_type=user_membership_type).exists(): if Lesson.objects.filter(allowed_memberships=1): context['lessons'] = Lesson.objects.filter(allowed_memberships=1).values() elif Lesson.objects.filter(allowed_memberships=2): context['lessons'] = Lesson.objects.filter(allowed_memberships=2).values() else: pass return context template {% if lessons is not None %} {% for lessson in lessons %} <div class="col-md-3"> <a href="/{{ lessson.link }}"> <div class="item"> <div class="content-overlay"></div> <img src="/{{ lessson.thumbnail }}" /> <div class="content-details fadeIn-bottom"> <h3 class="content-title">{{ lessson.content_title }}</h3> <p class="content-text">{{ lessson.content_text }}</p> </div> </div> </a> </div> {% endfor %} {% else %} <p>upgrade</p> {% endif %} -
django not redirecting from CreateView
So I initially thought that the submit button was not working, but looking in the database, it is POSTing to the database, but it is not clearing the form and going to the success url, any ideas what I'm doing wrong here? <!DOCTYPE html> {% extends "project_portal/base.html" %} {% block detail %} <div class="project_setup"> <h1>Project Setup</h1> <form class="update" method="POST"> {% csrf_token %} <table> {{ form.as_table }} </table> <input type="submit" class="btn" value="Submit"> <a href="{% url 'project-list' 0 %}">Cancel</a> </form> </div> {% endblock %} and here is the view: class ProjectCreateView(CreateView): template_name = 'project_portal/project_create.html' form_class = ProjectModelForm queryset = Project.objects.all() success_url = '/si/home/0/' def form_valid(self, form): user = self.request.user form.instance.user = user return super().form_valid(form) -
Django - How do i calculate the sum of a field in a queryset
Using DJANGO I have a simple model that has fields Customer_ID, Date, Product, Total_price. I want to display them in groups by Date so all prices on that date are shown grouped eg 28 April 2020 Crisps £1.20 Cheese £1.40 29 April 2020 Crisps £1.80 Cheese £3.40 How do I then show total price under each date (eg £2.60, £5.20) Here's what I tried in my html, all good displaying in groups but last tag for calculating sum doesn't work: {% regroup results by Date as new_list %} {% for Date, results2 in new_list %} <div class="track-row"> <span class="track-item track1">{{ Date }}</span> {% for data in results2 %} <div> <span class="track-item track3">{{ data.Stock }}</span> <span class="track-item track5">£{{ data.Sell_price }}+vat</span> <span class="track-item track4">{{ data.Quantity }}</span> <span class="track-item track5">£{{ data.Total_price }}+vat</span> </div> {% endfor %} <h6 class="title4">£{{ data.Total_price__sum }} + vat</h6> </div> {% endfor %} In my views.py I created a queryset with all totals: total = Quotes.objects.values('Customer_ID', 'Date').filter(Customer_ID=customer_id).\ annotate(total_price=Sum('Total_price')).order_by('-Date') and this works fine and gives me the correct totals, but how do I show these results alongside my html. I tried: {% for data2 in total %} <h6 class="title4">£{{ data2.total_price }} + vat</h6> {% endfor %} which works great but just … -
Djnago: Failed to link nested child to parent
I have an issue when trying to create nested objects, more specifically creating a parent and its child at the same time. The child's model has the parent's id as foreign key as can be seen below. Here is my parent_model: from django.db import models from django.contrib.auth import get_user_model User = get_user_model() from PIL import Image class Work(models.Model): user = models.ForeignKey(User, null=True, on_delete=models.SET_NULL) name = models.CharField(max_length=200) length = models.IntegerField(null=True) width = models.IntegerField(null=True) def __str__(self): return "{}".format(self.id) My child_model: from django.db import models from .model_work import * from .model_taxes import * from djmoney.models.fields import MoneyField class Price(models.Model): work = models.OneToOneField(Work, on_delete=models.CASCADE, related_name='price') price = MoneyField(max_digits=19, decimal_places=4, default_currency='USD', null=True) total = models.IntegerField(null=True) def __str__(self): return "{}".format(self.price) Here is my ParentCreateSerializer: class WorkCreateSerializer(serializers.ModelSerializer): """ Serializer to create a new Work model in DB """ price = PriceCreateSerializer() class Meta: model = Work fields = [ 'user', 'price', 'name', 'length', 'width' ] def create(self, validated_data): price_data = validated_data.pop('price') work = Work.objects.create(**validated_data) price = Price.objects.create(**price_data) return work My ChildCreateSerializer: class PriceCreateSerializer(serializers.ModelSerializer): """ Serializer to create a new Price when new Work model is created in DB """ # work = WorkDetailsSerializer() class Meta: model = Price fields = [ 'work', 'price', 'price_currency', 'total' ] def … -
How to manually enter latitude and longitude for a PointField in Django admin with OSMGeoAdmin or GeoModelAdmin?
How can I enter the latitude and longitude of a PointField when creating/editing an entry using the OSMGeoAdmin or GeoModelAdmin? Currently, I have a map where I can place the point by clicking on the map. I'd like to keep this behavior but also be able to manually specify the exact values. Details I have a Location model with a PointField attribute. # models.py class Location(models.Model): name = models.CharField(max_length=255, db_index=True) point = PointField(blank=True, null=True) # admin.py from django.contrib.gis.admin import OSMGeoAdmin @admin.register(Location) class LocationAdmin(OSMGeoAdmin): list_display = ("id", "name") -
Реализация вложенные комментариев в django-rest-framework
Пытаюсь сделать вложенные комментарии к постам, но при выводе постов выдает ошибку: "столбец news_comment.parent_id не существует". Как решить эту проблему или, возможно, стоит сделать все иначе? serializers.py # сериализатор комментария class CommentSerializer(serializers.ModelSerializer): replys = serializers.SerializerMethodField() def get_replys(self, obj): queryset = Comment.objects.filter(parent_id=obj.id) serializer = CommentSerializer(queryset, many=True) return serializer.data class Meta: model = Comment fields = '__all__' # сериализатор вывода постов class PostListSerializer(serializers.ModelSerializer): comments = serializers.SerializerMethodField() def get_comments(self, obj): queryset = Comment.objects.filter(post_id=obj.id, parent_id=None) serializer = CommentSerializer(queryset, many=True) return serializer.data class Meta: model = Post fields = '__all__' models.py # модель комментария class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') parent = models.ForeignKey( 'self', default=None, blank=True, null=True, on_delete=models.CASCADE, verbose_name='parent', related_name='replys' ) text = models.TextField(max_length=1500) date = models.DateTimeField(auto_now=True) username = models.CharField(max_length=50) user = models.ForeignKey(User, on_delete=models.CASCADE) -
django : The view papers.views.member_agreement_vc didn't return an HttpResponse object. It returned None instead
I'd like to make user access to page depends on model exist. it works when there is models.objects, but if there is no objects, it doesn't work. How can I control user path create or just view? hope kindly help me. def member_agreement_vc(request, preassociation_pk): preassociation = preassociation_models.Preassociation.objects.get( pk=preassociation_pk ) try: member_agreement = models.MemberAgreement.objects.get(pk=1) return render( request, "papers/member_agreement/detail.html", {"member_agreement": member_agreement}, ) except models.MemberAgreement.DoesNotExist: form_class = forms.CreateMemberAgreementFormVC template_name = "papers/member_agreement/create.html" def form_valid(self, form): pk = self.kwargs.get("preassociation_pk") member_agreement = form.save() member_agreement.writer = self.request.user member_agreement.association = preassociation_models.Preassociation.objects.get( pk=pk ) member_agreement.category = "member_agreement" member_agreement.is_business = True member_agreement.is_general = False member_agreement.save() form.save() return redirect( reverse( "preassociations:paper", kwargs={"pk": member_agreement.association.pk}, ) )