Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django rest auth store token securely
I'm trying to implement authentication with django-rest-auth library in the backend and I'm using react for the front-end. Django-rest-auth returns a token after authentication and I was guessing how to handle it. From a security perspective can that token be saved in an HTTPOnly cookie or it should be kept only in memory? Exists a tested approach to achieve local persistence with django-rest-auth and react without implementing vulnerabilities in the website? -
Table not displaying a data from model
this is my views.py def sms(request): obj = Sms.objects.all() return render(request, 'advisory.html', {'sms': obj}) and this is on my html. {% for i in sms %} <tr> <td>{{ i.description }}</td> <td>{{ i.timestamp }}</td> </tr> {% endfor %} this is the model class Sms(models.Model): description = models.CharField(max_length=100, blank=True) timestamp = models.DateTimeField(auto_now_add=True) And i don't really know why its not returning any data from my model. please help! thanks -
Get Data from all objects of a queryset in django
I have two models Order and OrderEntries class Order(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) order_entries = models.ManyToManyField(OrderEntries, blank=True) ... class OrderEntries(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.IntegerField() Now, I have to get history of purchased products. As I can get all previous orders placed by a user like this queryset = Order.objects.filter(user=self.request.user, client=self.request.client) But how I can get list of products from all those orders? -
Can't figure out how to craft my GraphQL query with graphene-django
I'm just starting out with graphene-django and GraphQL and can't figure out how to craft my mutation correctly. Here's my current mutation request: mutation createCustomer { createCustomer(input: { customerName: "John Smith", customerAddress: "1000 Airport Drive", customerCity: "1", customerState: "TX", customerZip: "75121", customerEmail: "me@me.com", customerCellPhone: "124567894", referredFrom: "g" }) { ok, customer{ id, customerName, customerZip, customerAddress } } } Here's my CustomerInput schema: input CustomerInput { id: ID customerName: String customerAddress: String customerCity: [LocationInput] customerState: String customerZip: String customerEmail: String customerCellPhone: String customerHomePhone: String referredFrom: String } LocationInput schema: input LocationInput { id: ID locationCity: String locationState: String locationSalesTaxRate: Float } And the error I'm receiving: { "errors": [ { "message": "Syntax Error GraphQL (6:28) Unexpected :\n\n5: customerAddress: \"1000 Airport Drive\",\n6: customerCity: [location:{id:1}],\n ^\n7: customerState: \"TX\",\n", "locations": [ { "line": 6, "column": 28 } ] } ] } And finally, here is my models: class Location(BaseModel, models.Model): location_city = models.CharField(max_length=100, blank=False, null=False, unique=True) location_state = models.CharField(max_length=2, blank=False, null=False, default="TX") location_sales_tax_rate = models.DecimalField(max_digits=4, decimal_places=2, verbose_name="Sales Tax Rate (%)", blank=True, null=True) class Customer(BaseModel, models.Model): """Customer model.""" REFERRAL_CHOICES = ( ('g', 'Google'), ('o', 'A friend'), ('f', 'Facebook'), ) # templates = "workorders/customers/customer.html" customer_name = models.CharField(max_length=100, blank=False, null=False, help_text="John Doe", verbose_name="Name") customer_address = models.CharField(max_length=100, blank=False, … -
Django: Is it appropriate to make queries from the template?
I have two models, Book and Chapter: class Book(models.Model): title = models.CharField(max_length = 200) class Chapter(models.Model): book = models.ForeignKey(Book, on_delete=models.CASCADE, related_name="chapter_set") index = models.IntegerField() In my template, I present each book and subsequent chapter indexes: {% for book in books %} <h2>{{ book.title }}</h2> <br> {% for chapter in book.chapter_set.all %} <p>{{ chapter.index }}</p> {% endfor %} {% endfor %} This code works fine. However, I hear repeatedly that it's a bad idea to place logic in the template that could be placed in the view or model. I'm hesitant to implement so many queries from my template if I'm hindering performance. I'm considering refactoring this code so that the template doesn't process queries through related_name. Is a refactor unnecessary, or am I violating best practices by making queries in the template? -
How to use Sphix's sphinx.ext.coverage's coverage_show_missing_items?
Sorry, I am a newbie trying to add Sphinx to auto-generate documentation for a Django project and also ensure sufficient documentation coverage of the project. I want to configure Sphinx to tell me which Objects are missing documentation by using the coverage_show_missing_items flag, specified here: https://www.sphinx-doc.org/ar/master/usage/extensions/coverage.html#confval-coverage_show_missing_items Unfortunately, I have not been able to figure out where/how to set this configuration. My Google-fu didn't come up with any examples on how to configure these settings. I'm guessing it should go inside conf.py somewhere, but haven't come across any examples on how to do it. Thank you for your time :) -
Enter a string sort in to alphabetic,numeric and alphanumeric? Using python django [closed]
Enter a string through an input text field. Sort it into 3 lists based on alphabet,numeric and alpha numeric. When user enter a string it is added to corresponding list. -
Installation of Django Framework on Mac [closed]
Yosephs-MacBook-Pro:Dev jose$ mkdir tenx Yosephs-MacBook-Pro:Dev jose$ cd tenx/ Yosephs-MacBook-Pro:tenx jose$ pipenv shell -bash: pipenv: command not found Yosephs-MacBook-Pro:tenx jose$ sudo pipenv shell sudo: pipenv: command not found -
registration form not getting saved in the database
this is my models.py for the registration session choice = ( ('2020-2021', '2020-2021'), ('2021-2022', '2021-2022'), ('2022-2023', '2022-2023'), ) registrationSession=models.CharField(max_length=15,choices=choice,blank=False) this is my views.py registrationSession=request.POST['RegistrationSession'] stu=Student(registrationSession=registrationSession) stu.save() this is my template <div class="component"> <label for="RegistrationSession">Registration Session <span style="color:red;">*</span> </label> <select class="col-form-label " style="width:760px;" name="RegistrationSession" id="RegistrationSession"> <option>2020-21</option> <option>2021-22</option> <option>2022-23</option> </select> </div> -
mttp comments problem in comment replying
everything works great but the problem is each time i try to reply to a comment it just creates a new individual comment instead, im trying to capture the id of the comment so that it posts it underneath it im not sure if im doing it the right way so feel free to change the code as much as you like im following a tutorial btw hmtl <div class="row justify-content-md-center pt-5"> <div class="col-8"><h1>{{posts.title}}</h1></div> <div class="col-8"><p>{{posts.content|linebreaks}}</p></div><br> <div class="col-md-8"> <hr> {% with comments.count as total_comments %} <legend class="border-bottom mb-4">{{total_comments}} comment{{total_comments|pluralize }}</legend> {% endwith %} <div class="col-8"> {% load mptt_tags %} <div> {% recursetree comments %} <div id="{{node.id}}"> <strong>{{ node.author }}: </strong>{{ node.content }} <div><sup class="text-muted">{{node.publish_date|date:"f, j.M/y"}}</sup> </div> </div> <button style="margin-bottom: 10px;" class="btn btn-outline-dark btn-sm" onclick="myFunction( {{ node.id }} )">Reply</button> {% if not node.is_leaf_node %} <div class="children" style="padding-left:30px; margin-bottom:20px;"> {{ children }} </div> {% endif %} {% endrecursetree %} </div> </div> <hr> <form action="{% url 'blog:comment-create' object.id %}" method="POST"> {% csrf_token %} <fieldset class="col-12 form-group"> <legend class="border-bottom mb-4">New Comment</legend> {{ form|crispy }} </fieldset> <div class="form-group mb-4"> <button class="btn btn-dark btn-lg mt-1" type="submit">Publish</button> </div> </form> </div> </div> </div> </div> </div> <script> function formExit(){ document.getElementById("newForm").remove(); } function myFunction(id){ if(document.contains(document.getElementById("newForm"))){ document.getElementById("newForm").remove(); } var a = … -
PANDAS: Excel to postgres append data without duplication
I am using Pandas, python, and postgresql. I want to avoid inserting data from excel file that is duplicated in the database The table is assembled with Django models: the crq_number column has the unique attribute class Crq(models.Model): id = models.IntegerField(primary_key=True) project = models.ForeignKey(Project, on_delete=models.CASCADE, null=True) crq_number = models.CharField(max_length=200, unique=True) crq_title = models.CharField(max_length=200) crq_impact = models.CharField(max_length=32) crq_type = models.CharField(max_length=32) pub_date = models.DateTimeField(auto_now_add=True) success = models.BooleanField(blank=True, null=True, default=True) CREATE TABLE public.srv_crq ( id bigint NOT NULL GENERATED ALWAYS AS IDENTITY ( INCREMENT 1 START 1 MINVALUE 1 MAXVALUE 9223372036854775807 CACHE 1 ), crq_number character varying(200) COLLATE pg_catalog."default" NOT NULL, crq_title character varying(200) COLLATE pg_catalog."default" NOT NULL, crq_impact character varying(32) COLLATE pg_catalog."default" NOT NULL, crq_type character varying(32) COLLATE pg_catalog."default", pub_date timestamp with time zone NOT NULL, success boolean, project_id integer, CONSTRAINT srv_crq_pkey PRIMARY KEY (id), CONSTRAINT srv_crq_crq_number_f3f26821_uniq UNIQUE (crq_number), CONSTRAINT srv_crq_project_id_745a788b_fk_srv_project_id FOREIGN KEY (project_id) REFERENCES public.srv_project (id) MATCH SIMPLE ON UPDATE NO ACTION ON DELETE NO ACTION DEFERRABLE INITIALLY DEFERRED ) and I have the following script to import data to the database: import pandas from sqlalchemy import create_engine, MetaData, Column, Table, exists, String df = pandas.read_excel('crq.xlsx') select_column = df[[ 'INFRASTRUCTURE_CHANGE_ID', 'DESCRIPTION', 'SCHEDULED_START_DATE', 'IMPACTO', 'ORIGEN', ]] df = select_column.rename(columns={ "INFRASTRUCTURE_CHANGE_ID": "crq_number", "DESCRIPTION": … -
Django 3: Badly formed URL in password_reset_email.html
I have a Django 3.0.7 app using the default template for sending password reset emails. For some of our users, the link to reset is badly formed, e.g.: https://foo.bar/accounts/reset/MzU4Mw/5no-9bd52590f0943503= fa3a/ /> While it should be: https://foo.bar/accounts/reset/MzU4Mw/5no-9bd52590f0943503fa3a/ This second one is whats actually being sent. But, as I said, some users are receiving the first one. I assume some of my users' email clients are wrecking the text, but what could I do? I've considered adding a plaintext url to the email, but it's already plaintext. Any ideas? -
Django order by highest number of likes in homepage
I'm trying to create a page where people can see the highest rated article in the homepage but I don't know how to use likes to do so. My post model class Post(models.Model): title = models.CharField(max_length=225) post_image = models.ImageField(null=True, blank=True, upload_to="images/") author = models.ForeignKey(User, on_delete=models.CASCADE) body = models.TextField() post_date = models.DateField(auto_now_add=True) likes = models.ManyToManyField(User, related_name='blog_posts') def total_likes(self): return self.likes.count() def __str__(self): return self.title + ' | ' + str(self.author) def get_absolute_url(self): return reverse('post-detail', args=(str(self.id)),) my views.py def LikeView(request, pk): post = get_object_or_404(Post, id=request.POST.get('post_id')) liked = False if post.likes.filter(id=request.user.id).exists(): post.likes.remove(request.user) liked = False else: post.likes.add(request.user) liked = True return HttpResponseRedirect(reverse('post-detail', args=[str(pk)])) class HomeView(ListView): model = Post template_name = 'home.html' class PostDetail(DetailView): model = Post template_name = 'post_detail.html' def get_context_data(self, *args, **kwargs): context = super(PostDetail, self).get_context_data() current_post = get_object_or_404(Post, id=self.kwargs['pk']) total_likes = current_post.total_likes() liked = False if current_post.likes.filter(id=self.request.user.id).exists(): liked = True context['total_likes'] = total_likes context['liked'] = liked return context Thanks in advance! ................................................................................................... -
Created custom user model, now creating new posts with requested user does not work?
I have a Post model for simple blog posts and a foreign key for the user who owns the post. Now using a custom user model I get a "Post.user" must be a "CustomUser" instance error. Here is the API view where the requested user is assigned to the post: class PostViewset(viewsets.ModelViewSet): queryset = Post.objects.all() serializer_class = PostSerializer permission_classes = [IsOwnerOrReadOnly] def perform_create(self, serializer): serializer.save(user=self.request.user) here is the Post model: class Post(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=100) body = models.CharField(max_length=100) def __str__(self): return self.title here is the post serializer: class PostSerializer(serializers.ModelSerializer): user_name = serializers.SerializerMethodField() class Meta: model = Post fields = ['id', 'title', 'body', 'user_name', 'user_id'] def get_user_name(self, obj): try: return obj.user.user_name except: pass here is my CustomUser model: class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) user_name = models.CharField(max_length=150, unique=True) first_name = models.CharField(max_length=150, blank=True) last_name = models.CharField(max_length=150, blank=True) date_joined = models.DateTimeField(auto_now_add=True) is_seller = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) #can be set to true after user confirms email address is_active = models.BooleanField(default=False) objects = CustomUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['user_name'] def __str__(self): return self.user_name ''' -
How to provide a queryset field for a subclass of a 1-to-many relation in Django?
How can I provide a queryset field for a subclass of a 1-to-many relation in Django? Example: Concept has a 1-to-many relationship with StudyResource. VideoStudyResource is a subclass of StudyResource. Django provides concept.studyresource_set.all() -- how can I also provide concept.videostudyresource_set.all() Appreciate any suggestions. -
How to make a detail view with fields that are toggled by the button?
So far my best guess is to make an UpdateView and toggle the editable attribute when user presses the button. Is it a good approach to this problem? -
Value Error. Cannot assign query set. It must be an instance
I want to create object in my comment model. It's my Reply model to a post. class Reply(MPTTModel): post = models.ForeignKey(Post, on_delete=models.CASCADE) detail = models.CharField(max_length=50, null=True, blank=True, unique=True) pub_date = models.DateTimeField(auto_now_add=True) last_edited = models.DateTimeField(auto_now=True) author = models.ForeignKey(User, on_delete=models.CASCADE) class MPTTMeta: order_insertion_by = ['name'] It's my view function for reply. def post_detail(request,id,**kwargs): post = Post.objects.all().filter(id=id) comment = CommentReply.objects.filter(post=id) context = {'post': post, 'comment': comment} if request.method == 'POST': comments = request.POST.get('comment') Reply.objects.create( post=post, detail=comments, author = request.user) else: return render(request, 'khalidblog_app/full_detail.html', context) return render(request,'khalidblog_app/full_detail.html',context) When I run this view function It shows a value error as follows. Cannot assign "<QuerySet [<Post: Author : zorainTiTleFirst PostDated :2021-01-17 16:27:47.043869+00:00>]>": "Reply.post" must be a "Post" instance. How I can set the forignkey(Post) in this reply model using this view function? -
Regroup data from model in Django views
I have a model with data like the following: Name Value Date pop1 15 2021-01-19 pup1 2 2021-01-18 pep1 25 2021-01-18 pop2 9 2021-01-17 pap1 1 2021-01-16 pep2 26 2021-01-16 pep3 4 2021-01-16 If i do data = myModel.objects.all() I obtain all the data in the normal structure, but what I want is obtain it grouped by date. Can this goal be achieved directly? I ask this because I know how to filter using myModel.objects.filter() or order the data using myModel.objects.order_by(). Then, exists something like myModel.objects.regroup('date')? Thank you very much. -
Get error "No module named 'ingredients'." during GraphQL Tutorial
The "import ingredients.schema" statement in the parent cookbook/schema.py seems to be the issue. Since im new to graphQl I thoroughly copied every thing but now it doesnt work. Any Ideas ? -
'collections.OrderedDict' object has no attribute 'uuid' - Django REST Framework
I'm using django-mptt to create a tree-like structure for my Section model. Unfortunately, when I go to serialize it with drf-writable-nested, I get an error. This error only occurs when the url field is added to the serializer. Code: # models.py class Section(MPTTModel, TimeStampedModel): uuid = models.UUIDField(default=uuid_lib.uuid4, editable=False) name = models.CharField(max_length=255, unique=True) objects = TreeManager() parent = TreeForeignKey('self', related_name='section_children', on_delete=models.CASCADE, null=True, blank=True) # serializers.py class SectionSerializer(UniqueFieldsMixin, WritableNestedModelSerializer): children = serializers.ListField(source='get_children', child=RecursiveField()) class Meta: model = Section fields = ['url', 'uuid', 'name', 'children'] extra_kwargs = { 'url': {'lookup_field': 'uuid'}, } # views.py class SectionDetail(generics.RetrieveUpdateDestroyAPIView, viewsets.GenericViewSet): queryset = Section.objects.all() serializer_class = SectionSerializer lookup_field = 'uuid' Traceback: Traceback (most recent call last): File "/usr/local/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/usr/local/lib/python3.9/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python3.9/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/usr/local/lib/python3.9/site-packages/rest_framework/viewsets.py", line 125, in view return self.dispatch(request, *args, **kwargs) File "/usr/local/lib/python3.9/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) File "/usr/local/lib/python3.9/site-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "/usr/local/lib/python3.9/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc File "/usr/local/lib/python3.9/site-packages/rest_framework/views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "/usr/local/lib/python3.9/site-packages/rest_framework/mixins.py", line 75, in update return Response(serializer.data) File "/usr/local/lib/python3.9/site-packages/rest_framework/serializers.py", line 548, in data ret = super().data … -
Django Channels-How to detect whether the connection was closed by server or client?
In my consumer,I need to detect whether the connection was closed by server or client. I tried using custom close_code so that I can detect who closed the connection. (close by server and close by client,both trigger disconnect() function) But disconnect function always prints 1006 as the code.Below is the code class ChatConsumer(WebsocketConsumer): def connect(self): if authorised: self.accept() else: # Accept and then reject to send custom close_code self.accept() self.close(code=3999) def disconnect(self,close_code): # But here the code is always 1006 print("Disconnected with ",close_code) Is there any other way to detect (in disconnect function) who (client/server) closed the connection? Any help or suggestion is appreciated. -
Django only show first POST element in loop
I have simple library page that user can register, add and edit\delete records from library. Template.html {% extends "book/base.html" %} {% block content %} <div class="row justify-content-center mt-5"> </div> {% if books %} {% for book in books %} <div class="table-users"> <div class="header"> {{ book.title }} </a> </div> <table cellspacing="0"> <tr><center> <th>Name</th> <th>Author</th> <th>Delete</th> </center> </tr> <td> {{ book.name }} </td> <td> {{ book.author }} </td> <td> <form class="delete" method="POST" action="{% url 'deletebook' book.id %}"> {% csrf_token %} <button class="delete" type="submit" class="btn btn-warning">Delete</button></td> views.py: def deletebook (request, book_pk): book = get_object_or_404(Book, pk=book_pk, user=request.user) if request.method == 'POST': book.delete() return redirect('currentbooks') With this loop only first element of POST method is active and working. Actually I'd debuggging html after rendered and i've seen that theres a only first element has a POST method. I searched on google and on stackoverflow and found something about the change id to class. But my template doesnt have any id. I also tried to move {% csrf_token %} outside of the loop but it doesnt work either. I think so, i missed something important here. I really appreciate if someone could help me out. Thank you in advance. -
Elasticsearch Default Settings in Django
In Django I can connect elastic_search = Elasticsearch(['http://elastic:elastic@localhost:9200/'], verify_certs=True) if elastic_search.ping(): # No problem! What I want is, I want to add this connection information to settings.py... ELASTICSEARCH_DSL = { 'default': { 'hosts': 'elastic:elastic@localhost:9200' }, } and call Elasticsearch this way: elastic_search = Elasticsearch() But this doesn't work. Ping only returns false. I also tried to add 'verify_certs': False to the settings but no chance. Is there a way to run Elasticsearch() function directly? -
Get all related objects with filter on through model
I have the next database structure: class Artwork(): id = models.IntegerField(_('id'), primary_key=True) artists = models.ManyToManyField('gql_service.Artist', through='gql_service.ArtistArtwork') class ArtistArtwork(models.Model): artist = models.ForeignKey('gql_service.Artist') artwork = models.ForeignKey('gql_service.Artwork') is_main_artist = models.BooleanField(default=False) class Artist(models.Model): id = models.IntegerField(_('id'), primary_key=True) is_main_artist feature flag used to define is this artist main for this artwork. In ArtworkNode I want to define main_artist field: class ArtworkNode(PrimaryKeyMixin, DjangoObjectType): main_artist = graphene.Field('escher.gql_service.schema.artist_node.ArtistNode') def resolve_main_artist(self, _): return ArtworkInfo(self).main_artist And then in the ArtworkService I can access artwork artists like: class ArtworkInfo(object): @property def main_artist(self): artist = self.artwork.artists.first() return artist Is there any way I can filter artists on ArtworkInfo and get only one main artist? -
Django Select2MultipleWidget leads to form continuously trying to load
I'm trying to incorporate Select2 into my django form -- specifically ModelSelect2MultipleWidget -- so that the user can associate multiple event objects to another model (like CheckboxSelectMultiple). The associated models are: from django.contrib.auth import get_user_model from django.db import models class F4Events(models.Model): name = models.CharField(max_length=300) handling_type = models.ManyToManyField(WaferHandlingType) def __str__(self): return self.name class ToolPm(models.Model): ceid = models.ForeignKey(CEID, on_delete=models.CASCADE) name = models.CharField(max_length=250) wafer_handling = models.BooleanField(default=True) wafer_based = models.BooleanField(default=False) frequency = models.FloatField(blank=True, null=True) handling_type = models.ManyToManyField(WaferHandlingType, blank=True) user_edited = models.BooleanField(default=False) pm_f4_events = models.ManyToManyField('F4Events', blank=True) def __str__(self): return str(self.name) if self.name else '' class Meta: ordering = ('ceid', 'name') My forms.py file is: from django import forms from .models import Entity, ToolPm, CEID, PDL, F4Events, WaferHandlingType from django_select2 import forms as s2forms class F4EventWidget(s2forms.ModelSelect2MultipleWidget): search_fields = [ 'name__icontains', ] attrs = {'data-placeholder': 'Please Choose F4 Events'} class PMForm(forms.ModelForm): class Meta: model = ToolPm fields = ['wafer_handling', 'wafer_based', 'handling_type', 'pm_f4_events'] widgets = {'handling_type': forms.CheckboxSelectMultiple, 'pm_f4_events': F4EventWidget } my view.py is: from datetime import datetime, timedelta from django.db.models import Sum from django.http import JsonResponse, HttpResponseRedirect from django.http.response import HttpResponse from django.shortcuts import render, get_object_or_404, redirect from django.views import View from django.views.generic import ListView from django_filters.views import FilterView from pages.filter import CeidFilter, PmRunDateFilter from tools.forms import EntityForm, …