Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to create an email registration form and email login system in django
i want to create a email registration system with password1 and password2(confirmation password) and also a email login system in django. i have seen couple of solutions but did not work for me. Any help will be appreciated. accounts/forms.py from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django import forms class UserCreateForm(UserCreationForm): class Meta: fields = ("email", "password1", "password2") model = User def clean_email(self): email = self.cleaned_data.get('email') if User.objects.filter(email__iexact=email).exists(): raise forms.ValidationError('A user has already registered using this email') return email accounts/backends.py class EmailBackend(ModelBackend): def authenticate(self, username=None, password=None, **kwargs): usermodel = get_user_model() try: user = usermodel.objects.get(email=username) except usermodel.DoesNotExist: return None else: if user.check_password(password): return user return None settings.py AUTHENTICATION_BACKENDS = ['accounts.backends.EmailBackend'] Whenever i try to register a second user i have the following error: UNIQUE constraint failed: auth_user.username -
django.core.exceptions.ImproperlyConfigured: WSGI application 'crmapp.wsgi.application' could not be loaded; Error importing module
I am a beginner and trying to learn django but i get the following error, django.core.exceptions.ImproperlyConfigured: WSGI application 'crmapp.wsgi.application' could not be loaded; Error importing module. This is the error i get when i try to run server. Any help appreciated Thanks ""My WSGI.PY file looks like this"" import os from django.core.wsgi import get_wsgi_application from dj_static import Cling os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'crmapp.settings') application = get_wsgi_application()` ""SETTINGS.PY FILE"" WSGI_APPLICATION = 'crmapp.wsgi.application' MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] -
How to have dynamically added fields to specific model fields and not all
i am building an application that has a model with three fields Company,Name, position. in the same model i want to have company name as one field while the user can add name and positions for multiple candidates. the reason am trying to do that is because i didnt find any proper way to set automatically select the foreign key based on the company name entered since foreign key is a drop down list and couldnt figure out the way to make foreign key field equal to company name entered. appreciate help and suggestions if any for the approach i have in mind. -
Send array of objects from a view to a template to use in javascript, django
As can be done so that from django through a view an array of objects (which is the result of a series of operations) can be sent to a template, but this arrangement will be used in a javascript code fragment which will handle make a graph -
How to render all permissions of a specific model in django templates?
Suppose I've a model called class UserProfile(models.Model): user = models.OneToOneField(User, verbose_name=_("User"), on_delete=models.CASCADE) first_name = models.CharField(_("First name"), max_length=50) middle_name = models.CharField(_("Middle name"), max_length=50, blank=True, null=True) last_name = models.CharField(_("Last name"), max_length=50) dob = models.DateField(_("D.O.B"), auto_now=False, auto_now_add=False, blank=False, null=False) profile_image = models.ImageField(_("Profile picture"), upload_to='user/profile/', blank=True) class Meta: verbose_name = _("User profile") verbose_name_plural = _("User profiles") def __str__(self): return self.first_name + " " + self.middle_name + " " + self.last_name def get_absolute_url(self): return reverse("userprofile_detail", kwargs={"pk": self.pk}) I want to render default permission available to this model in the tabular form like below. I try to render forms manually but it display all the permissions like below with checkboxes. account.add_emailaddress account.add_emailconfirmation account.change_emailaddress account.change_emailconfirmation account.delete_emailaddress account.delete_emailconfirmation auth.add_group auth.add_permission auth.change_group auth.change_permission auth.delete_group auth.delete_permission -
How to using Spring @RequestMapping annotation with attribute name in Spring MVC
As I know in the Django Framework offers a way to name URLs so it's easy to reference them in view methods and templates. For example: # Definition in coffeehouse/urls.py path('',TemplateView.as_view(template_name='homepage.html'),name="homepage") # Definition in view method from django.http import HttpResponsePermanentRedirect from django.urls import reverse def method(request): .... return HttpResponsePermanentRedirect(reverse('homepage')) # Definition in template <a href="{% url 'homepage' %}">Back to home page</a> what is the name attribute in Spring @RequestMapping annotation? Is it the same with the name URL in the Django Framework? how to using @RequestMapping annotation with attribute name in Spring MVC? -
How to test PasswordChangeView
I'm trying to create a test for the get_success_url method of PasswordChangeView to see whether the redirect work as intended. The expected behavior I'm looking for -- with a valid form -- is to have the password changed, and to get a 302 redirect response. But for some unknown reason, I can't seem to pass valid form data, so I get a 200 response, and the test keep failing. Does anyone know why the test below give me an invalid form? What am I missing? test.py def test_success_url(self): client = Client() user = User.objects.create(username="anon", password="pw") client.force_login(user) data = { 'old_password': 'pw', 'new_password1': 'newpw', 'new_password2': 'newpw', } response = client.post('/anon/change-password/', data) user.refresh_from_db() self.assertEqual(user.check_password('newpw)) self.assertEqual(response, 302) views.py class UserPasswordChangeView(LoginRequiredMixin, PermissionMixin, PasswordChangeView): def get_success_url(self): return reverse("user:detail", kwargs={ "username": self.request.user }) -
remove help_text from django UserCreationForm
i am making registration page but i dont like text under username like : Required 150 characters or fewer. Letters, digits and @/./+/-/_ only. or under password: Your password can't be too similar to your other personal information. you get the point pls help,thankyou i tried to find other questions but they all remove help_text from added field as email, but i need to remove from username,password... class UserRegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email' , 'password1', 'password2'] and then i render it in html as crispy form {% csrf_token %} <fieldset> <legend class="hello4"> <i>Join Today</i> </legend> <div > {{form|crispy}} </div> </fieldset> <div> <button type="submit" class="btn btn-light">Sign Up</button> </div> </form> -
Override update in Django Rest Framework without reimplementing the entire method?
So, I've been looking for a pattern or standard for this for a while, but I can't seem to find one. Suppose I have some serializer: WhateverSerializer(serializers.ModelSerializer): class Meta: model = Whatever fields = ( 'special', 'field_1', 'field_2' #a bunch more... ) And I want to have some special update behaviour just for the field special but no other fields. Is there a way to to override update without having to redo the entire update method like this? def update(self, instance, validated_data): special_behaviour(instance.special) instance.field_1 = validated_data.get('field_1', instance.field_1) instance.field_2 = validated_data.get('field_2', instance.field_2) #a bunch more... I've tried calling the ModelViewSet.update method, but it actually takes different parameters than the one you override in the viewset, and I'm not sure how exactly to pass the ones I have into that method. -
Getting the primary key of a ForeignKey field without querying the database again in Django
I have the following models: class Model1(models.Model): ... class Model2(models.Model): ... model1 = models.ForeignKey(Model1) Now, lets say I have an object of Model2 with pk=241 which is related to another object of Model1 with pk=102. I am querying them as follows: model2 = Model2.objects.get(pk=241) Now, if I want the pk of the referenced Model1 object. I do the following: model2.model1.pk This should not query the database again according to what I understand about tables, but if I run the following: from django.db import connection connection.queries I get a list of 2 queries. Why do I need to query my database again to only get the primary key of my related object? Is there a way to avoid doing this? I am aware of select_related(), however, what if I want to call the Model1 objects pk in the save() method of the Model2 class? Moreover, is select_related() required even if I want to just retrieve the pk of the related object and nothing more? -
scroll down or open link
with a hard work I've achieved to make A scrool down to a specefic div when clicking on a specific menu item, the issue that I have is in another menu item contact that opens another page contact.html. it does't work when using href="{% url 'contact' %}" <div class="main-menu mean-menu float-right"> <nav> <ul> <li class="active"><a href="#hero-area">home</a></li> <li><a href="#feature-area">about<i class="icofont"></i></a></li> <li><a href="#gallery-area">gallery<i class="icofont"></i></a></li> <li><a href="#instructor-area">services<i class="icofont"></i></a></li> <li><a href="{% url 'blog' %}">blog<i class="icofont"></i></a> <ul> <li><a href="{% url 'blog' %}">Blog</a></li> <li><a href="blog-details.html">Blog Details</a></li> </ul> </li> <li><a href="{% url 'contact' %}">contact</a></li> </ul> </nav> </div> .JS CODE $('.main-menu ul li a').on('click', function(e) { e.preventDefault() $('html, body').animate( { scrollTop: $($(this).attr('href')).offset().top, }, 500, 'linear' ) }) var menuLi = $('.main-menu ul li'); menuLi.on('click', function(){ var currLink = $(this); if( menuLi.hasClass('active') ){ menuLi.removeClass("active"); currLink.addClass('active'); } }); View def contact(request): return render(request, 'sc_drive/contact.html') URL path('contact', views.contact, name='contact'), -
ModelChoiceField lists tuples instead of simple values
I have a django form with a ModelChoiceField input and it lists the result as tuples instead of simple values. I have no clue on how to do it. DJANGO class PayThis(forms.Form): amount = forms.FloatField(required=False) cost2 = forms.FloatField(required=False) year = forms.ModelChoiceField(required=False,queryset=AnAgricol.objects.values_list('anul').all()) HTML <option value="(2019,)">(2019,)</option> I expect to get this: < option value="2019">2019< /option > -
Django forms with variable user entries
I want to create a django form that captures user entry such as name, address, age. For this type of information I can create a model such as class GeneralInfoPremium(models.Model): state = models.CharField(max_length = 2, choices = STATE_choices) class_code = models.CharField(max_length = 4) manual_premium = models.DecimalField(decimal_places = 2, max_digits = 10) class GeneralUserInfo(models.Model): firstname = models.CharField() lastname = models.CharField() address = models.CharField() # etc.... However, I also want to capture maybe some information like their class schedule or family information. class UserSchedule(models.Model): course_number = model.IntegerField() course_name = model.CharField() # etc.... class FamilyInfo(models.Model): family_member_type = models.CharField(choices = MEMBER_CHOICES) # mother, father, sibling family_member_name = models.CharField() # jon doe # etc.... where by each user, the number of courses and number of family members could vary. I would like the form to look something like below with a simple submit button to send things off to be saved. My question is, how should I structure the form template considering there are multiple models? -
Misunderstanding about Django collectstatic
I'm currently getting my Django website ready for production and have run into a small hitch. I've looked at the page https://docs.djangoproject.com/en/2.2/ref/contrib/staticfiles/, and it seems I need to run the collectstatic command to process all my static files and put them in one directory. The problem is that I have about 80GB worth of static files, and to copy them into a new STATIC_ROOT takes up a large amount of redundant hard drive space. Is there any way to keep this large set of datafiles in a file structure outside of the django website, and to serve them from there? -
I am trying to create a registration form to add data to 2 tables simultaneously. But I am not sure what to write after the POST method
I want to create a user into auth_user. And use its id(primary key) to fill in an entry into User_Profile to take it as a Foreign key. Models.py: class User_Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) contact_number = models.IntegerField() birth_date = models.DateField(null=False) address = models.CharField(max_length=200) role = models.ForeignKey(Role, on_delete=models.CASCADE) Forms.py: class UserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput) class Meta: model = User fields = ['username', 'email', 'password'] class UserProfileForm(forms.ModelForm): class Meta: model = User_Profile fields = [ 'contact_number', 'birth_date', 'address', 'role'] Views.py: def registration_view(request): form = UserForm(request.POST) form2 = UserProfileForm(request.POST) else: context = { 'form': form, 'form2': form2 } return render(request, 'Schoool/registration_form.html', context) -
How can I send a notification on creating a new post using django-webpush?
I need to add a web push notification on creating a post but it does not work. I have tried following this documentations, https://www.digitalocean.com/community/tutorials/how-to-send-web-push-notifications-from-django-applications#conclusion Added this to my CreatePost View at Views.py self.object.save() for user in User.objects.all(): user_id = self.object.user.pk user_site = get_object_or_404(User, pk=user_id) payload = {'head': self.object.group, 'body': str(self.object.user)+' Uploaded a post.'} try: send_user_notification( user=user_site, payload=payload, ttl=1000) print('Success!') except: print("Fail") return super().form_valid(form) I expect it to send a push notification to all users in my site. -
How to edit django form data before cleaning/validation?
How can I edit the value returned by a django form field before it is validated or saved? For example, If I have: from django import forms class ContactForm(forms.Form): # Everything as before. ... def clean(self): # the widget returns user.id's (django-select2 ModelSelect2MultipleWidget recipient_ids = self.data['recipients'] # need to convert IDs to usernames usernames = User.objects.filter(id=recipient_ids).values_list(username, flat=True) # now I have a list of usernames, I need to put those back into the data to finish cleaning etc: self.data['recipients'] = usernames # error, data isn't mutable... return super().clean() How can I modify the form data self.data['recipients'] = usernames before it gets sent for cleaning? Side note on why I need to do this: I am trying to use Django-select2 ModelSelect2MultipleWidget (which returns pks) for the Django-postman recipients field, but recipients in Django postman can't be ids, it has to be username or some other field (I tried setting POSTNAME_NAME_USER_AS='pk' but postman doesn't accept that, so I'm just using the default which is 'username') -
Raise exception in django authentication backend instead of return none
In my django project, i implement a custom authentication backend and i want to raise several exceptions in authenticate method and handle these exceptions in login view. below line is from Django doc: Either way, authenticate() should check the credentials it gets and return a user object that matches those credentials if the credentials are valid. If they’re not valid, it should return None. Is there any problem with raising exception in authentication backend? -
django channel cannot create new instance of an object using html input in otree
I am programming in otree for an online asset market with double auction, where each subject can both sell and buy, and all their orders are public to everyone in the market. I am using WebSocket to make orders visible in one page in the browser after subjects submit an order. My problem is that it seems that data from input submission can be received, but it cannot be used to create new instance of an object from the info shown in console, and I don't get any other error messages. Here is the code I tried. In consumer.py def receive(self, text=None, bytes=None, **kwargs): self.clean_kwargs() msg = text player = self.get_player() group = self.get_group() if msg['action'] == 'new_order': if msg['order_type'] == 'Buy': try: bid = player.bids.create(price_buy=msg['price_buy'], quantity_buy=msg['quantity_buy']) except NotEnoughFunds: logger.warning('not enough funds') elif msg['order_type'] == 'Sell': try: ask = player.asks.create(price_sell=msg['price_sell'], quantity_sell=msg['quantity_sell']) except NotEnoughSharesToSell: logger.warning('not enough shares to sell') player.save() for p in group.get_players(): self.group_send(p.get_personal_channel_name(), {'asks': p.get_asks_html(), 'bids': p.get_bids_html()}) In JS $form_container.on('click', 'button#submit_order', function () { ...some variable declared... if (order_type == 'Sell' && price_sell > 0) { var msg = { ...some message content... }; if (socket.readyState === WebSocket.OPEN) { socket.send(JSON.stringify(msg)); console.log(msg); }; } else if (order_type == 'Buy' && … -
Obtaining data from user
How do I obtain the field data from a User auth query within a class View. It's on the django framework. This code works just fine... from django.contrib.auth.models import User class PaymentsReportView(ListView): template_name = 'payments/Payment_list.html' userid = 'James' queryset = Payment.objects.filter(Landlord_FK__User_id=userid) but this doesn't... class PaymentsReportView(ListView): template_name = 'payments/Payment_list.html' userid = User.username # where the username is James queryset = Payment.objects.filter(Landlord_FK__User_id=userid) How can I check the output of User.username to see if it's valid? What am I missing to get the data? -
Bootstrap collapse expanding all cards when one is clicked
Hi I am trying to use bootstrap collapse for a part of my django application. This is my implementation so far: {% extends 'base.html' %} {% block content %} <div class="container"> <div class="row"> <div class="col-6"> <div class="card"> <h1 class="text-center">Recent reports</h1> <div class="accordion" id="accordionExample"> {% for report in reports %} <div class="card"> <div class="card-header" id="report_{{ loop.counter }}"> <h2 class="mb-0"> {% if loop.counter == 1 %} <button class="btn btn-link" type="button" data-toggle="collapse" data-target="#collapse{{ loop.counter }}" aria-expanded="true" aria-controls="collapse{{ loop.counter }}"> Report #{{ report.report_number }} </button> {% else %} <button class="btn btn-link collapsed" type="button" data-toggle="collapse" data-target="#collapse{{ loop.counter }}" aria-expanded="false" aria-controls="collapse{{ loop.counter }}"> Report #{{ report.report_number }} </button> {% endif %} </h2> </div> <div id="collapse{{ loop.counter }}" class="collapse" aria-labelledby="report_{{ loop.counter }}" data-parent="#accordionExample"> <div class="card-body"> <table class="table"> <tbody> <tr> <th scope="row">Date</th> <td>{{ report.datetime_submitted }}</td> </tr> <tr> <th scope="row">XYZ</th> <td>{{ report.xyz }}</td> </tr> ..... </tbody> </table> </div> </div> </div> {% endfor %} </div> </div> </div> </div> </div> {% endblock %} I am facing an issue where when I click on the card-header card, all the collapse card-body class elements expand opposed to just the related one(which is the desired behaviour). Any guidance on how to solve this will be appreciated. -
How can you show more than just the foreign key of an object when listing something in Django Rest Framework?
I'm working on a problem in one class called Tour, which includes an Artist foreign key. I need to show more than just its foreign key. How can I do that while keeping all of CRUD functional? I tried to add depth = 1 to the Meta class in the serializers. That works, but upon attempting to create a new object, I get the error NOT_NULL CONSTRAINT FAILED. Then I got rid of that and instead added artist = ArtistSerializer to the TourSerializer, but that still doesn't do it, even though I've seen it work in a tutorial. The issue with using artist=ArtistSerializer() is that when I try to create the object, I pass the foreign key, but it doesn't seem to recognize it as a valid field. It's like I didn't type anything at all into the field. Every time I get it to properly list it, the creation doesn't work as intended. Here's how my code looks right now: class TourSerializer(ModelSerializer): artist = ArtistSerializer() class Meta: model = Tour fields = ['artist', 'start', 'end', 'country', 'id', 'created_at', 'updated_at'] read_only_fields = ['id', 'created_at', 'updated_at'] The models for Tour and Artist are as follows: class Tour(models.Model): artist = models.ForeignKey('core.Artist', on_delete=models.PROTECT) … -
How can I display some specific column?
I have this problem : I have this following form using Django : class Test(forms.Form): name = forms.CharField( label=_('Name'), ) price = forms.IntegerField( label=_('Price'), required=False, ) year = forms.IntegerField( label=_('year'), required=False, ) And then to display the labels with the entries I did this : {% if form %} {{ form.as_p }} But I just want to display the label 'name' with entry and the label 'price' with entry and to give a default value to year. Could you help me please ? Thank you very much ! PS : I tried to use this editable:False but I got an unexepected keyword argument 'editable' -
Django : how to use modified queryset in templates without saving modification
In my views.py, I do: context_data = {} all_answers = Answer.objects.all() for i in range(0, len(all_answers)) : all_answers[i].text = modify_text(all_answers[i].text, request) context_data ["all_answers"] = all_answers print(context_data ["all_answers"][0].text) #Check that it was modified return render(request, 'template.html', context_data) And in my templates I have like : {% for answer in all_answers.all %} {{ answer.text}} {% endfor %} The check shows that the modification is made, yet it my template the answer.text is the unmodified data from the database. I saw that the type of the context_data ["all_answers"] is a queryset, that I guess is triggered during the template rendering, making any unsaved changes useless, how to make my changes show in the template ? I have tried : context_data ["all_answers"] = list(all_answers) To load the queryset. The check works but then nothing show in the template (1) An error arise during the template render when I used this function to load the queryset into a list of dict. I also saw a [linked question without answer].3 I don't want to save the changes as they are customized for each request (for each user basically). TLDR : How to see my modifications in the templates without saving the changes into the database ? … -
NOT NULL constraint failed for Django Forms when extending Custom Model mid-project
I'm trying to mimic this project with the Profile one-to-one model: https://ruddra.com/posts/django-custom-user-migration-mid-phase-project/ Django version 2.2.3. The difficulty is that it's allowing only one user model any user model after the first one created. I create a super user and then cannot register any other users. I've been working on extending the base model for a week. I'm getting the Null Constraint error: views.py def payments(request): if request.user.is_authenticated: return redirect('login') else: if request.method == "POST": form = CustomUserCreationForm(request.POST) if form.is_valid(): profile = form.save(commit=False) profile.user = request.user profile.key = "".join(random.choice(string.digits) for i in range(20)) profile.save() Profile = Profile.get_or_create( user = request.user, key=profile.key, first_name=form.cleaned_data['first_name'] ) Profile.save() auth_login(request, form.get_user()) messages.success(request, f'Your account has been created! Please proceed to agreements and payment.') return redirect('agreements_page') else: raise ValidationError("Form is not valid. Try Again.") else: form = CustomUserCreationForm() return render(request, 'premium/payments.html', {'form': form}) models.py I'm relying on both the default base model, which is what this saves to. I then create the profile model via the Django form. Once one is created, it does not allow me to create another user. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) key = models.CharField(max_length=25, null=True, blank=True) first_name = models.CharField(max_length=25) last_name = models.CharField(max_length=25) address1 = models.CharField(null=True, max_length=100, blank=True) address2 = models.CharField(null=True, max_length=100, …