Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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, … -
I want to make django chat application
I want to make a django chat app but I searched hours and I couldn't find how , youtube tutorials use react and I don't know react js Pls give me a way to study on how to make it and where to get it Done through official django docs but got errror with redis... It would be kind if you also can tell me about the steps involved in making.... -
How zero or many, one or many, zero or one are crated in django?
I have a Vacancy that can have zero or many Benefits and currently use a ManytToMany in Vacancy like this: class Vacancy(models.Model): benefits = models.ManyToManyField(Benefits) My question is how can I define that there is a possibility that a Vacancy has no Benefit? And how can I define that it must have at least one benefit? How does this apply to OneToOne and ForeignKey relationships in django? -
Can you make a view that redirects the user to another app based on a random variable?
as the title says, I want to create a functions that redirects the user to another app based on a random variable. I created a function and gave a random value to a variable that calls the corresponding view of another app, but only the first value of the random range works fine, while the other get an error at the form validation. -
Handling user choice with conditional logic in Jinja template (caesar cipher Django web app)
I’m writing a Django web app which basically presents the web visitor with the option to encrypt / decrypt a message using a very rudimentary caesar cipher. I got the encryption function to work but when I tried to implement conditional logic in my template to handle the user’s initial choice on the landing page (the option to encrypt or decrypt), Django is not serving the client the option. I’m not sure why. I’m expecting Django to give the web visitor this choice on the landing page: Would you like to encrypt a plaintext message? Or would you like to decrypt a scrambled message? (...where each question is a hyperlink that takes the visitor to a page to enter their message). When the web visitor lands on the page, neither option is showing. Django just serves a blank template. Here is a temporary mirror of my dev server: https://d0d342ea4934.ngrok.io Here is my views.py: from django.shortcuts import render import string def caesar(request): # Courtesy of Real Python: https://realpython.com/python-practice-problems/ if 'encrypt' in request.GET: plain_text = request.GET['original_entry'] shift_num = request.GET['shift_num'] shift_num = int(shift_num) letters = string.ascii_lowercase mask = letters[shift_num:] + letters[:shift_num] trantab = str.maketrans(letters, mask) output_text = plain_text.translate(trantab) context = {'select_option': False, 'output_text': … -
Using modelForm with CreateView
I have a problem with CreateView. My code is a bit of a frankenstein monster with code from various tutorials, docs, and stackoverflow. I feel like I have misunderstood some fundamental step in the workflow. Here is the models.py: class Customer(models.Model): name = models.CharField(max_length=200, null=False, blank=False) phone = models.CharField(max_length=50, null=False, blank=True) Here is the forms.py: class CustomerForm(forms.ModelForm): def clean(self): super().clean() name = form.cleaned_data['name'].upper() form.cleaned_data['name'] = name class Meta: model = Customer fields = ['name', 'phone'] widgets = { 'name': forms.TextInput(attrs={"class": "form-control"}), 'phone': forms.TextInput(attrs={"class": "form-control"}),} Here is the views.py: class CustomerCreateView(LoginRequiredMixin, CreateView): model = Customer form_class = CustomerForm context_object_name = 'customer_create' template_name = 'customers/customer-create.html' login_url = 'account_login' def form_valid(self, form): form.instance.created_by = self.request.user return super().form_valid(form) And lastly here is the template: <form method="post"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Save"> </form> The problem is that when I hit save the page just refreshes and the new object is not created. What am I doing wrong? -
How can I add column to the admin from other table, that isn't directly connected?
I am trying to add field to admin view, which goes through several tables. Using shell I have no issue getting the result I want, but I don't know how to add that field to the view. I have table meeting, which has foreign key of table person. Table person has many-to-many relationship with table ConditionDict. I wish to use one field from ConditionDict to Meeting view, without their direct link (as from database perspective it seems redundant), but I do not know how to do it. Here is shell I use to go through all these tables which works meeting.objects.filter(id=1).values('person_in_need__person_c__condition__issue') but I do not know how to add the 'issue' field to the meeting model. -
Why MyModel.objects.none() == MyModel.objects.none() returns False in django shell
I have a model named Program in my django project. I entered shell and tested this: Program.objects.none() == Program.objects.none() It is returning False!! Any idea why? -
ValidationError with Datatime field in Django
I am working with the date picker of Tempus Dominus Bootstrap 4 in my Django project. template's date-picker link: Doc in my models.py: class Industry(models.Model): name = models.CharField(max_length=200, blank=True) mycustomdate = models.DateTimeField(null=True, blank=True) in my views.py: if request.method == "POST": this_mycustomdate = request.POST['mycustomdate'] print(this_mycustomdate) Industry_obj = Industry.objects.create(name=this_name, mycustomdate = this_mycustomdate) Industry_obj.save() But it says error like: ValidationError at /industrySignup/ ['“03/04/2021 5:06 PM” value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format.'] with the line: Industry_obj = Industry.objects.create(name=this_name, mycustomdate = this_mycustomdate) How can I solve this problem?