Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Writing Django signup form tests for checking new user creation
Implemented a custom user model in Django and allows user to signup using the url http://127.0.0.1:8000/users/signup/. A GET request on this url is displayed like this: I have written tests for this page. Tests for get is working as expected. I wrote test for post with the intention that the post would create a user in the test database. After which I could write tests to confirm if an user is created and whether the username matches and so on. But it seems the user is not getting created. Below are my tests class SignUpPageTests(TestCase): def setUp(self) -> None: self.username = 'testuser' self.email = 'testuser@email.com' self.age = 20 self.password = 'password' def test_signup_page_url(self): response = self.client.get("/users/signup/") self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, template_name='signup.html') def test_signup_page_view_name(self): response = self.client.get(reverse('signup')) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, template_name='signup.html') def test_signup_form(self): response = self.client.post(reverse('signup'), data={ 'username': self.username, 'email': self.email, 'age': self.age, 'password1': self.password, 'password2': self.password }) self.assertEqual(response.status_code, 200) users = get_user_model().objects.all() self.assertEqual(users.count(), 1) The users.count() turns out to be 0 and my test is failing. Where am I going wrong? -
Django: When is on_delete=DO_NOTHING useful?
When using a ForeignKey in a Django model, you can specify the on_delete argument, which defaults to CASCADE. There are multiple other options available and one of it is DO_NOTHING. The description for this option in the Django documentation is as follows: DO_NOTHING [source] Take no action. If your database backend enforces referential integrity, this will cause an IntegrityError unless you manually add an SQL ON DELETE constraint to the database field. Honestly, I do not fully understand what it actually does and when it's useful to choose DO_NOTHING. Can someone provide an example and explain the effect? -
Django's post_delete signal not being called
I've used signals a lot of times, however, I have a post_delete signal that is not being called: @receiver(post_delete, sender=Book) def book_deleted(sender, instance, **kwargs): .... The signal is being imported, so it should be called, however, when I do: book = Book.objects.get(id=book_id) book.delete() the signal is not being called, what may be going on? Thanks in advance -
submit form without refreshing the page
I created form contains title, content and image. I try to submit that form without refreshing the whole page using with django with ajax. When I submit the form POST method is okay but I get another GET method showing this error. GET http://127.0.0.1:8000/media/default.jpg [HTTP/1.1 404 Not Found 8ms] And I didn't declare default image in my model.py. Here is my views.py def posts(request): posts = Post.objects.filter(posted_date__lte=timezone.now()).order_by('-posted_date') if request.method == 'POST': form = PostForm(request.POST, request.FILES) if form.is_valid(): post = form.save(commit=False) post.author = request.user post.save() else: form = PostForm() args = { 'form': form, 'posts': posts, } if request.is_ajax(): html = render_to_string('posts/post-section.html', context=args, request=request) return JsonResponse({'pos':html}) return render(request, 'posts/posts.html', args) also here is my ajax $(document).on('submit', '.post-form', function(event){ event.preventDefault(); console.log($(this).serialize()); $.ajax({ type: 'POST', url: $(this).attr('action'), data: $(this).serialize(), dataType: 'json', success: function(response){ $('.post-section').html(response['pos']); }, error: function(rs, e){ console.log(rs.responseText); }, }); }); What should I do to submit that post without refreshing the page? -
Why isn't the method in my sub-classed form being called
I have a form which I am subclassing in order to change one method (get_json_filename). The form is something like class BackgroundForm(BetterModelForm): ... def get_json_filename(self): print("FRONT") return os.path.realpath(PROJECT_ROOT + '/form_data/background_info/' + self.curr_context['instrument'] + '_front.json') #Initiation of form. Set values, page format according to crispy forms, store variables delivered by views.py, and organize fields on the form. def __init__(self, *args, **kwargs): self.curr_context = kwargs.pop('context', None) super(BackgroundForm, self).__init__(*args, **kwargs) self.filename = self.get_json_filename() .... .... And my subclassed from is simply class BackpageBackgroundForm(BackgroundForm): def get_json_filename(self): print("BACK") return os.path.realpath(PROJECT_ROOT + '/form_data/background_info/' + self.curr_context['instrument'] + '_back.json') The get_json_filename called when using the subclassed form is the method from the original form. How do I fix this? -
Django cascade deletion not calling signal
I have a model: class Book(models.Model): ... And another model: class Chapter(models.Model): book = models.ForeignKey(Book, on_delete=models.CASCADE) Then I have a post_delete signal defined on Chapter. The signal is successfuly called when I delete a chapter, how ever, it is not being called when I delete a book. What should I have to do in order to get the signal called when deleting the chapters as result of deleting a book in cascade mode? Thanks in advance -
Activating and deactivating comments not working properly in panel admin
After activate a comment by checking the active box to showing that comment to the user on template, everything seems good but after deactivating that comment again, it makes a new instance or in another word copying that comment in panel admin as an active, it's like duplicating the comments after unchecking the active box. I am using Postgresql database, Is that possible this issue came from database? models.py class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') name = models.CharField(max_length=80) email = models.EmailField() body = models.TextField() created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) active = models.BooleanField(default=False) class Meta: ordering = ('created',) def __str__(self): return 'Comment by {} on {}'.format(self.name, self.post) forms.py class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ('name', 'email', 'body') views.py def post_detail(request, year, month, day, post): post = get_object_or_404(Post, slug=post, status='published', publish__year=year, publish__month=month, publish__day=day) # List of active comments for this post comments = post.comments.filter(active=True) new_comment = None if request.method == 'POST': # A comment was posted comment_form = CommentForm(data=request.POST) if comment_form.is_valid(): # Create Comment object but don't save to database yet new_comment = comment_form.save(commit=False) # Assign the current post to the comment new_comment.post = post # Save the comment to the database new_comment.save() else: comment_form = CommentForm() … -
Django - DoesNotExist
I am getting this error after I deployed my app to pythonanywhere. Everything worked fine in development. File "/home/AndrewsBRN/django_todo_app/memberships/models.py", line 47, in post_save_usermembership_create free_membership = Membership.objects.get(membership_type='Free') File "/usr/lib/python3.7/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/usr/lib/python3.7/site-packages/django/db/models/query.py", line 399, in get self.model._meta.object_name memberships.models.DoesNotExist: Membership matching query does not exist. I tried to remove 'django.contrib.sites' as per another solution to this error here on SO, but that does not work. memberships/models.py from django.conf import settings from django.db import models from django.db.models.signals import post_save from django.contrib.auth.models import User from datetime import datetime import stripe stripe.api_key = settings.STRIPE_SECRET_KEY MEMBERSHIP_CHOICES = ( ('Enterprise', 'ent'), ('Professional', 'pro'), ('Free', 'free') ) class Membership(models.Model): slug = models.SlugField() membership_type = models.CharField( choices=MEMBERSHIP_CHOICES, default='Free', max_length=30) price = models.IntegerField(default=15) stripe_plan_id = models.CharField(max_length=40) def __str__(self): return self.membership_type class UserMembership(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE) stripe_customer_id = models.CharField(max_length=40) membership = models.ForeignKey( Membership, on_delete=models.SET_NULL, null=True) website = models.URLField(default='', blank=True) member = models.DateTimeField(auto_now=True) def __str__(self): return self.user.username def post_save_usermembership_create(sender, instance, created, *args, **kwargs): user_membership, created = UserMembership.objects.get_or_create( user=instance) if user_membership.stripe_customer_id is None or user_membership.stripe_customer_id == '': new_customer_id = stripe.Customer.create(email=instance.email) free_membership = Membership.objects.get(membership_type='Free') user_membership.stripe_customer_id = new_customer_id['id'] user_membership.membership = free_membership user_membership.save() post_save.connect(post_save_usermembership_create, sender=settings.AUTH_USER_MODEL) settings.py import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = '***' LANGUAGE_CODE = 'en-us' … -
How to write a mptt custom manager to filter active fields on get_queryset method?
I have a model 'Category' based on mptt model. I want to filter my queryset on basis of a field 'active'. But I dont want to change it in admin level. i.e let i have a model 'all_objects' which will be TreeManager and 'objects' which will be 'modifiedTreeManager' returning only active queryset. I want to use objects in my views and all_objects in admin. I tried doing it but some methods like instance.get_descendants() working on the basis of 'all_objects' and not with 'objects'. class modifiedTreeManager(TreeManager): def get_queryset(self): return super(modifiedTreeManager, self).get_queryset().filter(active=True) class Category(MPTTModel): ... active=models.BooleanField(default=True) all_objects = TreeManager() objects = modifiedTreeManager() I also tried to change the _tree_manager value to objects but i dont know how to do it and if there will be any result of doing so. -
What Do you Return in Django if Ajax Request is successful?
I have made an Ajax request from a Javascript File to my Python views file in django which is successful but I am unsure what should be my return value. data_from_ajax = request.POST['data'] # do something with the data return ? I have tried returning HttpResponse("success") but the Ajax call in javascript still runs the error function. What is the correct return value for a successful ajax request? -
bootstrap datepicker not loading django
i have this jquery error while loading: base.html: {% load static%} <!doctype html> 3<html lang="en"> <head> <meta charset="utf-8"> <title>Celebizz</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="description" content="Site Description Here"> <link href= {% static 'main_site/css/bootstrap.css' %} rel="stylesheet" type="text/css" media="all" /> <link href={% static "main_site/css/stack-interface.css" %} rel="stylesheet" type="text/css" media="all" /> <link href={% static "main_site/css/socicon.css" %} rel="stylesheet" type="text/css" media="all" /> <link href={% static "main_site/css/lightbox.min.css" %} rel="stylesheet" type="text/css" media="all" /> <link href={% static "main_site/css/flickity.css" %} rel="stylesheet" type="text/css" media="all" /> <link href={% static "main_site/css/iconsmind.css" %} rel="stylesheet" type="text/css" media="all" /> <link href={% static "main_site/css/jquery.steps.css" %} rel="stylesheet" type="text/css" media="all" /> <link href={% static "main_site/css/theme.css" %} rel="stylesheet" type="text/css" media="all" /> <link href={% static "main_site/css/custom.css" %} rel="stylesheet" type="text/css" media="all" /> <link href="https://fonts.googleapis.com/css?family=Open+Sans:200,300,400,400i,500,600,700%7CMerriweather:300,300i" rel="stylesheet"> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <script src={% static "main_site/js/jquery-3.1.1.min.js" %}></script> <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <style> .my-nav{ background-color: rgb(28, 18, 157) !important } li.dropdown:hover > ul.dropdown-menu { display: block; } .nav-font{ color:white !important; } </style> </head> <!--end bar--> <!--end of notification--> <div class="nav-container "> <div class="bar bar--sm visible-xs"> <div class="container"> <div class="row"> <div class="col-3 col-md-2"> <a href={% url 'mainsite-index' %}> <img class="logo logo-dark" alt="logo" src={% static "main_site/img/logo.png" %} /> <img class="logo logo-light" alt="logo" src={% static "main_site/img/logo.png" %} /> </a> </div> <div class="col-9 col-md-10 text-right"> <a href="#" class="hamburger-toggle" data-toggle-class="#menu1;hidden-xs"> <i … -
Django "Reverse for 'question_update' with keyword arguments '{'pk': ''}' not found."error
NoReverseMatch at /answer_update/1/16 Reverse for 'question_update' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['question\/(?P[0-9]+)\/update\/$'] I am trying to make a comment update function. But it doesn't work. Someone please help me out. urls.py path('answer_update/<int:qpk>/<int:apk>',views.answer_update, name='answer_update'), views.py def answer_update(request, qpk, apk): answer = get_object_or_404(Answer, pk=apk) question = get_object_or_404(Question, pk=qpk) if request.method == "POST": form = AnswerForm(request.POST, instance=answer) if form.is_vaild(): form.save() return redirect('detail_question', pk=apk) else: form = AnswerForm(instance = answer) return render(request, 'detail_question.html',{'form':form}) detail_question.html <div> <h1>Answer_list</h1> <div> {% for answer in answers %} <div> {% if answer.image %} <img src="{{ answer.image.url}}" height=200> {% endif %} <p> {{ answer.content }} </p> <p> {{ answer.author }} </p> {% if user == answer.author %} <a href="{% url 'answer_update' question.pk answer.pk %}">update</a> {% endif %} {% if user == answer.author %} <a href="{% url 'answer_remove' question.pk answer.pk %}">delete</a> {% endif %} {% if user == question.author and question.selected == False %} <a href="{% url 'select_question' question.pk answer.pk %}">select</a> {% endif %} <hr> </div> {% endfor %} </div> -
How to solve the error of Unknown field(s) (Id_card_number) specified for User?
I am trying to add new input field in users page in django admin, but it is showing me just email, password, confirm password fields. I want it to show Id_card_number also. I have codes in different files but when I makemigrations, it is giving me django.core.exceptions.FieldError: Unknown field(s) (Id_number) specified for User. How to solve this problem? models.py from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): Id_card_number = models.CharField(max_length=15) settings.py AUTH_USER_MODEL = 'users.User' admin.py from django.contrib.auth.admin import UserAdmin from .models import * admin.site.register(User, UserAdmin) views.py from django.contrib.auth import get_user_model User = get_user_model() -
Updating data in Database from Django form
I want to create a form that edits data already stored on my DB. This is what the template looks like: {% for row in mydb %} <form method="post" novalidate> {% csrf_token %} {% include 'main/includes/bs4_form.html' with form=form3 %} {{row.firstfield}} {{row.secondfield}} <button name="button3" type="submit" class="btn btn-danger style="background-color: red;">CANCEL</button></td> </form> {% endfor %} The for statements is to display each row of the data in my table in a single line. Near each line, there is a submit button. When this button is clicked, the field secondfield is updated with the value New Value, as you can see in my form. Thi is the part of the view involved: def myview(request, tvticker): row = mydb.objects if request.method == 'POST': ... if 'button3' in request.POST: form3 = form = UpdateForm(request.POST) if form3.is_valid(): profile = form.save(commit=False) profile.save() messages.success(request, f"Success") ... render(request, "main/mytemplate.html", context={'row': row,}) And here is the form: class UpdateForm(forms.ModelForm): SomeField = forms.CharField() class Meta: model = MyModel fields = ("SomeField",) def save(self, commit=True): send = super(UpdateForm, self).save(commit=False) send.secondfield = 'New Value' if commit: send.save() return send My actual code it's not working, is seems to send a POST request but the secondfield value is not updated. For example, if i click … -
Unable to query through elasticsearch
I am using Elasticsearch in my Django application. When i try to query my result using curl i get found = false. Can someone help me here !]1 I am following this tutorial and my code when i execute https://www.freecodecamp.org/news/elasticsearch-with-django-the-easy-way-909375bc16cb/ and my code fails when i execute curl -XGET 'localhost:9200/blogpost-index/blog_post_index/1?pretty' -
Django Prefetch not fetching the related fields
I have four models that reference a CustomUser table. class Profile(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE) ... class Question(models.Model): question = models.CharField(max_length=140) class Answer(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name='answers') answer = models.CharField(max_length=70) class Response(models.Model): user = models.ForeignKey(CustomUser, on_delete=models.CASCADE, related_name='responses') question = models.ForeignKey(Question, on_delete=models.CASCADE) answer = models.ForeignKey(Answer, on_delete=models.CASCADE) Each question has multiple answers but each user can only pick one answer to each question. Each user can answer multiple questions. I have a ViewSet that authenticated users can access that is supposed to return a list of users with the same answers as them. serializer_class = serializers.ProfileSerializer def get_queryset(self): user_answers = qmodels.Answer.objects.filter(response__user=self.request.user) return models.Profile.objects.prefetch_related( Prefetch( 'user__responses', queryset=qmodels.Response.objects.filter(answer__in=user_answers), to_attr='common_answers' ) ) class ProfileSerializer(serializers.ModelSerializer): common_answers = ResponseSerializer(many=True) However, I'm getting the following error: Got AttributeError when attempting to get a value for field `common_answers` on serializer `ProfileSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `Profile` instance. Original exception text was: 'Profile' object has no attribute 'common_answers'. I've added a print after prefetch_related and it is showing the base records properly but there is no common_answers field -
Django: How to Auto-Populate field with a related-model's field
I have two basic models: class ModelA(models.model): ... #some fields score = models.IntegerField() class ModelB(models.model) ... #some fields related_model=models.OneToOneField(ModelA) score = models.IntegerField(default=related_model.score) What I want is that upon creation of ModelB, it's score field be filled with the value of score of ModelA to which it has a OneToOne relation. I have tried setting the score = models.IntegerField(default=related_model.score) but upon migration I get the error:AttributeError: 'OneToOneField' object has no attribute 'score' I also tried defining a method under ModelB as follows and passing it to the default: def get_score(self, *args, **kwargs): return self.threat.score This doesn't work either. when I set default=get_score() I get the error: missing one required positional argument: self How can I automatically set a model's field to be a field of it's related model's (by OneToOne Relation) field? -
how to run Laravel project and Dajngo project using same apache server
After i have done Django configuration in apache2.conf file my all laravel projects stop working I want to run laravel and Dajngo project deployed on different domain using same apache server -
How can i create a web page for upload big file in Django with process bar
i want to create a web page in Django for upload big file (any file) with process bar but i don't know how can i do it? i can't create process bar? i create a model for uploaded files and one form for render model and a html page for that form i created '''python class uploadfile(models.Model): filename=models.charfiled(max_length=10) file=models.filefiled(upload_to='myfile') class formuploadfile(forms.Form): filename = forms.ChoiceField() file = forms.FileField() ''''' -
How can i retrieve values in a table from forms.py in django
I'm trying to make a form where the user can view the rule created by that user Only. I have This Model class Rule(models.Model): name = models.CharField(max_length=30) color = models.CharField(max_length=7, default='#007bff') companyId=models.ForeignKey(User,unique=True, on_delete=models.CASCADE) def __str__(self): return self.name def get_html_badge(self): name = escape(self.name) color = escape(self.color) companyId = escape(self.companyId) html = '<span class="badge badge-primary" style="background-color: %s">%s</span>' % (color, name,companyId) return mark_safe(html) This Form class DepartmentSignUpForm(UserCreationForm): rules = forms.ModelMultipleChoiceField( queryset=Rule.objects.all(), # queryset=Rule.objects.filter(companyId=self.request.user), widget=forms.CheckboxSelectMultiple, required=False )`class Meta(UserCreationForm.Meta): model = User`enter code here` @transaction.atomic`def save(self): user = super().save(commit=False) user.user_type = 3 user.save() department = Department.objects.create(user=user) department.rules.add(*self.cleaned_data.get('rules')) return user ` And this view @method_decorator([login_required, company_required], name='dispatch') class DepartmentSignUpView(CreateView): model = User form_class = DepartmentSignUpForm template_name = 'registration/signup_form.html' def get_context_data(self, **kwargs): kwargs['user_type'] = 'department' return super().get_context_data(**kwargs) def form_valid(self, form): form.save() messages.success(self.request, 'The Department created successfully') return redirect('company:homePage') I want to retrieve the rules in the department sign up page created by the logged-in company only. What I am getting is the rules created by all the company -
how to get data from html page and save it to database in several steps?
i have a some model and i need get data from my html pages that users can complete it.one of them is here: class Doctor(models.Model): PersonalInfo=models.OneToOneField( Personalnfo, on_delete=models.CASCADE, ) ReceptionInfo=models.OneToOneField( ReceptionInfo, on_delete=models.PROTECT, null=True,blank=True ) MedicalComplex=models.ForeignKey(MedicalComplex,on_delete=models.CASCADE) MedicalNumber=models.IntegerField() Expertise=models.CharField(max_length=100) ExpertiseCode=models.CharField(max_length=5) UserName=models.CharField(max_length=32) PassWord=models.CharField(max_length=32) SelfPicture=models.ImageField() Bio=models.CharField(max_length=1000,null=True,blank=True) Website=models.CharField(max_length=50,null=True,blank=True) fields with name "PersonalInfo" and "ReceptionInfo" are from another class.problem is here.i want to create many html pages and use each one for one field. for example one page for PersonalInfo data , one page for ReceptionInfo data,and one page for other fields of my class.i mean step by step. now how can i get data from my pages and save them in my db? -
How to solve the problem of django.core.exceptions.FieldError?
I am trying to add new input field in users page in django admin, but it is showing me email, password, confirm password fields. I want it to show Id_card_number also. I have codes in different files but when I run the code, it is giving me django.core.exceptions.FieldError: Unknown field(s) (Id_number) specified for User. How to solve this problem? models.py from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): Id_card_number = forms.CharField(max_length=15, required=True) settings.py AUTH_USER_MODEL = 'users.User' admin.py from django.contrib.auth.admin import UserAdmin from .models import * admin.site.register(User, UserAdmin) views.py from django.contrib.auth import get_user_model User = get_user_model() -
How can i make like dislike button for anonymous user using django , how can i manage this session ? Please anyone could explain this?
Recently i'm developing my first blog website using django , no i want add like and dislike button but anyone can give multiple like , so i want to handle that . But how ? Please explain someone. -
Apache2 Configuration for Django Project
I have tried all apache configuration for running my Django project at itssmartworld.com which is my one the domain but all solution and configuration not working Can you tell me all the configuration for running it well i have made some configuration in my /etc/apache2/sites-available/000-default.conf file and my django project is uploaded at file path /var/www/vhosts/itssmartworld.com/MyAwesomeCart WSGIScriptAlias / /var/www/vhosts/itssmartworld.com/MyAwesomeCart/mac/wsgi.py WSGIPythonPath /var/www/vhosts/itssmartworld.com/MyAwesomeCart Order deny,allow Allow from all i want to run Django project at http://itssmartworld.com/ url only but right now this is coming on this url Server Error 403 Forbidden You do not have permission to access this document. -
How to write a model in Django with category and author or reporter (As ForeignKey)? Can i use two foreignkey in same Post class model?
category = models.ForeignKey(Category, related_name='article', on_delete=models.CASCADE) reporter = models.ManyToManyField(User, on_delete=models.CASCADE, related_name='article') Can I write a model class like this?