Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
cookiecutter-django: Can't makemigrations after altering the username field in User model to PhoneNumberField
I'm working on a project that started from cookicutter-django, and I want to alter the username field to use PhoneNumberField form django-phonenumber-field instead of ordinary CharField username = PhoneNumberField( unique=True, help_text=_("Required. Phone number with country code."), error_messages={ "unique": _("A user with that phone number already exists.") }, ) but when I makemigrations I get this error: https://pastebin.com/2EYtySJP I tried adding PhoneNumberField to UserChangeForm and UserCreationForm but didn't solve the problem. I did a hacky thing, but not suitable as a permanent solution, which is: I added a region kwrg to the field class in the django source code, and the migrations worked, but this is not how I should solve it. I want to know the solution that would make the same effect without altering the django's source code. any suggestions, please? -
PrimaryKeyField on create and SerialzerField on get
I have two models. An employee and a manager. When creating an employee, you should supply the ID of the manager (you should never be able to create a new one) and the response should include the manager object. Here's the code class ManagerSerializer(serializers.ModelSerializer): class Meta: model = Manager fields = ('id', 'name') class EmployeeSerializer(serializers.ModelSerialzier): manager = ManagerSerializer(required=False) class Meta: model = Employee Right now, it expects to send a Manager object which creates a new manager but it's an ID only field. Upon creation the response should look like this: { "id": 90, "manager": { "id": 26, "name": "John" } ... } The following throws an exception: POST /employees/ { "manager": 10, ... } -
Can't disable required input for a Django TextField
Currently, one of the forms I'm working with is required to have input, I want to disable this behavior and make input optional. I'm using Wagtail, the relevant code is provided below. description = models.TextField(blank=True, null=True, verbose_name="Description") From what I understand the form should already be optional due to the line above, I don't understand why I can't see the change in my application. Any help is appreciated. -
Django - Autocompleting fields when re-rendering form
In my project, I have a Django form, which I then pass to my template. This form allows users to Signup for an account. If the user makes a mistake, I use Django messages to return an error to the user, and then redirect to the same page with the error. This error is successfully displayed. However all the previous data the user entered into the form is lost. What I want is too reload the page with the form filled in with all the previous data the user entered. This way they can correct the data easily without having to re-enter all the information again. Does Anybody know how to accomplish this? Thank you. views.py: if form.cleaned_data['password'] != form.cleaned_data['confirmPassword']: messages.error(request, 'Password fields do not match') return redirect('signup') else: try: user = User.objects.get(username=form.cleaned_data['username']) messages.error(request, 'Username has already been taken') return redirect('signup') Template: {% if messages %} {% for message in messages %} <span class="errorMessageSignup"> <img src="{% static 'wrongcross.png' %}" style="position:absolute;" height="17px" width="17px">&nbsp;&nbsp;&nbsp;&nbsp; <b>{{ message }}</b></span> {% endfor %} {% endif %} -
How can WSGI parse the URL that called it?
My problem seems to have been discussed in a previous question here, but had no working answer. I need to, in the WSGI python file, before actually starting Django, analyze the URL that was called and 'read' it, so I can know who called it and extract information from there that I can use to determine how my Django app will be started. I have an app running on a VM that is called from several different URLs, each pointing to a different WSGI file, all running the exact same code in Django, but using different 'DJANGO_SETTINGS_MODULE' files. A different settings file for each URL that calls my application. This is a legacy project which I cannot alter. Currently, this is how it operates: User1 accesses 'user1.example.com' > WSGI sets DJANGO_SETTINGS_MODULE to settings_user1 > WSGI starts Django User2 accesses 'user2.example.com' > WSGI sets DJANGO_SETTINGS_MODULE to settings_user2 > WSGI starts Django User3 accesses 'user3.example.com' > WSGI sets DJANGO_SETTINGS_MODULE to settings_user3 > WSGI starts Django Each URL calls for a different WSGI file, all running the same project, but setting the variable to the appropriate SETTINGS. We're moving away from Amazon, where our VM is currently located, and plan on using Google … -
Force newline in django form validation error string
How do I force a Django form to display a newline at a specific point in the validation error string? I've tried using \n\n as well as a <br> in the validate functions in forms.py and neither works. HTML doesn't care about the newlines and <br> gets escaped instead of rendered as a newline. The error strings are something similar to the following: raise ValidationError(f"'{value}' matched {match_count} objects.\n\n<br>Please be more specific. I want to force the newline between sentences. If there is some HTML+CSS trick to do so using the period as the delimiter, I am open to that. -
How to access the second most recent timestamped field entry in Django?
I have a form from a model that keeps track of enter/leave times. I am trying to add constraints to make the data more accurate. Currently, when someone "Enters", it creates a record, saves the time in timestamp and then redirects. If the person then tries to enter again, it creates a new record with a new timestamp. What I'm trying to add now is that, if the person has a previous entry without an exit timestamp then that record (which would be the second to last most recent entry), would be flagged by updating the time_exceptions field to 'N'. Currently, it changes all the fields to 'N', regardless of whether there's an exit or not, as shown below. class EnterExitArea(CreateView): model = EmployeeWorkAreaLog template_name = "operations/enter_exit_area.html" form_class = WarehouseForm def form_valid(self, form): emp_num = form.cleaned_data['employee_number'] area = form.cleaned_data['work_area'] station = form.cleaned_data['station_number'] if 'enter_area' in self.request.POST: form.save() EmployeeWorkAreaLog.objects.filter((Q(employee_number=emp_num) & Q(work_area=area) & Q(time_out__isnull=True) & Q(time_in__isnull=True)) & (Q(station_number=station) | Q(station_number__isnull=True))).update(time_in=datetime.now()) if EmployeeWorkAreaLog.objects.filter(Q(employee_number=emp_num)).count() > 1: EmployeeWorkAreaLog.objects.filter((Q(employee_number=emp_num) & Q(work_area=area) & Q(time_out__isnull=True)) & (Q(station_number=station) | Q(station_number__isnull=True))).update(time_exceptions='N') return HttpResponseRedirect(self.request.path_info) I tried the following, but I get a expected string or bytes-like object and while it still creates a new record before crashing, it does not update … -
How to use email instead of username in Simple JWT?
I need to use email instead of username for authenticating the user with django-rest-framework-simplejwt. I've tried to follow the code in this answer: https://stackoverflow.com/a/56318724/76535 However, the validate function in serializer is never called, and Simple JWT just returns error {"username":["This field is required."]} urls.py: urlpatterns = [ # ADMIN REST: path('admin/token/', TokenObtainPairView.as_view(serializer_class=CustomJWTSerializer)), ... serializers.py: from rest_framework_simplejwt.serializers import TokenObtainPairSerializer class CustomJWTSerializer(TokenObtainPairSerializer): def validate(self, attrs): # this never gets never called -
Specific Queryset for Input on Django ModelAdmin Change Form
I've got a 'Registration' object in place that users can create on the front end without issue. It looks like this: class Registration(models.Model): person = models.ForeignKey(Person, on_delete=models.PROTECT) course_detail = models.ForeignKey(CourseDetail, on_delete=models.PROTECT) camp_shirt = models.ForeignKey(CampShirt, on_delete=models.PROTECT) comments = models.CharField(max_length=200, blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return "%s" % (self.course_detail.course.camp) When I am in the admin and click on a given Registration - it takes a while to load because there are thousands and thousands of Person objects. For ease of use - there will never be a time when we would need to edit the 'person' associated with a given registration, so I would like to make the 'person' dropdown only show the selected user in the person queryset when editing from the django admin. So when I go to http://myapp.com/admin/registration/23/change I want the form to only display the currently selected person as the only option in the dropdown. My admin model looks like this: class RegistrationAdmin(admin.ModelAdmin): list_display = ("person", "course_detail") class Meta: # I think this is what I do in order to override the default admin form? Not sure. form = RegistrationAdminForm My RegistrationAdminForm looks like this: class RegistrationAdminForm(forms.ModelForm): # course_detail, person, camp_shirt, comments person … -
Django form field is displaying uuid of the record
I am using django 2.2 and python 3.6. I have a django modelform. I am using crispy forms to display the form in template. The form is not displaying the value of the records. It is displaying the uuid values of the records. I need to display the record name value instead of uuid value. models.py : @reversion.register() class Staff(BaseModel): user = models.OneToOneField( User, on_delete=models.PROTECT, db_index=True, verbose_name=_("Kullanıcı")) photo = models.ImageField( upload_to="staff/", null=True, blank=True, verbose_name=_("Fotoğraf")) staff_type = models.ManyToManyField( StaffType, verbose_name=_("Personel Tipi")) name = models.CharField( max_length=100, db_index=True, verbose_name=_("İsim")) surname = models.CharField( max_length=100, db_index=True, verbose_name=_("Soyad")) phone = models.CharField(max_length=100, verbose_name=_("Telefon Numarası")) email = models.EmailField(verbose_name=_("Email"), db_index=True) address = models.TextField(verbose_name=_("Adres")) subject = models.ForeignKey(Subject, on_delete=models.SET( get_unknown_subject), verbose_name=_("Branş")) gender = models.IntegerField( choices=GENDERS, default=None, verbose_name=_("Cinsiyet")) nationality = models.CharField( choices=NATIONALITIES, max_length=100, verbose_name=_("Uyruk")) blood_type = models.CharField( choices=BLOOD_TYPES, max_length=20, verbose_name=_("Kan Grubu")) id_no = models.CharField(max_length=100, unique=True, verbose_name=_("Kimlik No")) birthdate = models.DateField(verbose_name=_("Doğum Günü")) birthplace = models.CharField(max_length=200, verbose_name=_("Doğum Yeri")) education = models.IntegerField( choices=EDUCATION, default=None, verbose_name=_("Eğitim")) marital_status = models.BooleanField( default=True, verbose_name=_("Evlilik Durumu")) number_of_children = models.IntegerField( verbose_name=_("Çocuk Sayısı")) special_notes = models.TextField( null=True, blank=True, verbose_name=_("Özel Notlar")) registration_date = models.DateField(verbose_name=_("Kayıt Tarihi")) foreign_language = models.ForeignKey(Language, on_delete=models.SET( get_default_language), null=True, blank=True, verbose_name=_("Yabancı Dil")) class Meta: permissions = ( ("list_staff", _("List Staff")), ) ordering = ['name', 'surname'] def __unicode__(self): return "%s %s" % … -
My Django Middleware Isn't Working The Way It Should
How do I go about passing the reason to banned.html from the UserBanning model from the middleware file? Almost everything works but I can't seem to get the reason from the model to display in the template banned.html and im unsure way so any help will be amazing just got into learning about middleware. Should I be using process_request() instead? Thanks models.py: from django.db import models from django.contrib.auth.models import User from django.conf import settings class UserBanning(models.Model): user = models.ForeignKey(User, verbose_name="Username", help_text="Choose Username", on_delete=models.CASCADE) ban = models.BooleanField(default=True, verbose_name="Ban", help_text="Users Bans") reason = models.CharField(max_length=500, blank=True) class Meta: verbose_name_plural = "User Banning" ordering = ('user',) def __str__(self): return f"{self.user}" middleware.py: from .models import UserBanning from django.shortcuts import render class BanManagement(): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): banned = UserBanning.objects.all() context = { 'banned': banned, } if(banned.filter(ban=True, user_id=request.user.id)): return render(request, "account/banned.html", context) else: response = self.get_response(request) return response banned.html: {% extends "base.html" %} {% block content %} <p>Your account has been banned. Reason: {{ banned.reason }}</p> {% endblock content %} -
Python/Django 'utf-8' codec can't decode byte 0xb3 in position 0: invalid start byte
At the beginning I wanted to say hello and say that I have been using the portal for several years, but now I decided to create an account and describe my problem. I try to display the table, unfortunately there is still an error when I open view.html: UnicodeDecodeError at /add 'utf-8' codec can't decode byte 0xb3 in position 8: invalid start byte For a few hours I was looking for a solution and unfortunately I could not solve this problem. I use Polish characters, in the database characters are saved as utf-8, if I remove the Polish characters from the database it all works, but that's not what I want. models.py from django.db import models class komDane (models.Model): data = models.TextField() product = models.TextField() oldprice = models.TextField() newprice = models.TextField() dostepnosc = models.IntegerField() def __str__(self): return self.name views.py from django.shortcuts import render, render_to_response import mysql.connector from .models import komDane import sys def index(request): dupa = "nic" return render_to_response('index.html', {'name':'dupa'}) def add(request): zwraca = komDane.objects.all() return render_to_response('result.html', {'dane': zwraca}) views.html {% extends 'head1.html' %} {% block content %} <table><tbody> {% for a in dane %} <tr><td>{{ a.id }}</td><td>{{ a.product }}</td><td>{{ a.oldprice }}</td><td>{{ a.newprice }}</td><td>{{ a.newprice }}</td></tr> {% endfor %} </table></tbody> … -
Use the same form several times in the same template dynamically Django
Supposed I have an user update page for details. On this page you can add contact details (phone and email pair). I want to be able to dynamically add more and more contact information for people who have more then 1 pair of phone numbers and emails. Now, I have one contact details form, I want that when my user will press on + button on the page it will display another form of contact information (in the same page = now we will have 2 contact details forms in the page) and when the user click on - one form of contact information will disappear. Finely when the submit button get clicked I will get all the different contact details forms that filled in the page and I will be able from view to separate them (which data came from which form) and save the relevant data in the relevant place. Now the question: How do you do that? How do I "duplicate" the same form multiple times in the same page/template? How (from the view) can I separate the different forms even though they are the same (all contact details) -
Django ModelForm field queryset based on on other field
Consider my models.py, PowerPolicy: class PowerPolicy(models.Model): name = models.CharField(max_length=15) ... Group: class Group(models.Model): name = models.CharField(max_length=15) #But then, we also have: power_policies = models.ManytoManyField(PowerPolicy) Player: class Player(models.Model): name = models.CharField(max_length=15) group = models.ForeignKey(Group, on_delete=models.CASCADE) ... And then another model called, UsePower: class UserPower(models.Model): player = models.ForeignKey(Player, on_delete=models.CASCADE) power_policy = models.ForeignKey(PowerPolicy, on_delete=models.CASCADE) ... But! Here's the catch: I want to make it so that my superuser (Note that my superuser isn't a player, he's simply a superuser) can only create a UsePower object of the Powers specified in the Player's Group. Now, I do know that I have to create a custom form and override the queryset of the power_policy field that returns, my the custom queryset according to my needs through a function. - Here's what it would look something like: class UsePowerForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(UsePowerForm, self).__init__(*args, **kwargs) def MyCustomFunctionThatReturnsTheQuerySet(): This function returns the Power policies that are allowed to the player in their player Group. The only problem is, Our little function here doesn't know how to get the player chosen. could you help return TheQuerySet self.fields['power_policy'].queryset = MyCustomFunctionThatReturnsTheQuerySet() I really hope this makes sense, and you guys could help me out. Thank you for your time … -
Python Graphene working with many to many relations
if this is answered somewhere else then I am sorry but 2 days after work and still no cigar... I have a player model: class Player(models.Model): name = models.CharField(max_length=60) discord_id = models.CharField(max_length=60, null=True) known_npcs = models.ManyToManyField(NPC) The player can know many NPCs, and any NPC can be known by many players. NPC is nothing special: class NPC(models.Model): image = models.ImageField() name = models.CharField(max_length=50) description = models.TextField() last part of the puzzle is the Fact a fact is some piece of information attached to a NPC, however a person can know a NPC, but not necessarily all of the fact's related to the NPC are known by the Player hence the Fact looks like this: class Fact(models.Model): fact = models.TextField() known_by = models.ManyToManyField(Player) npc = models.ForeignKey(NPC, on_delete=models.DO_NOTHING, null=True) Now in graphene I want to create a Player and allPlayers query that would give me this: { allPlayers { name knownNPCs { image name description factsKnown { fact } } } } Where the factsKnown are only the ones based on the ManyToMany relation from the Fact object. What I have created so far returns the data but does not filter the Facts based on the player parent just shows all the … -
Django - Why is this random text rendering when I get errors upon form submission attempt?
I have a page with a form that takes in an employee # (using foreignkey), and when it is submitted it verifies that this employee # is in fact in another model (Salesman), and checks if 'WF' is in the team field for this employee. While the logic works and everything is being displayed, I keep getting this random bold text under the box Salesman object (406) (or whichever number I entered that would give me an error) after submitting the form, along with the proper error on top. I think this is related to the foreignkey field part, but I'm not sure how to prevent this from showing up when there are errors. models.py class EmployeeWorkAreaLog(TimeStampedModel, SoftDeleteModel, models.Model): employee_number = models.ForeignKey(Salesman, on_delete=models.SET_NULL, null=True, blank=False) ... def __str__(self): return self.employee_number forms.py class WarehouseForm(AppsModelForm): class Meta: model = EmployeeWorkAreaLog widgets = { 'employee_number': ForeignKeyRawIdWidget(EmployeeWorkAreaLog._meta.get_field('employee_number').remote_field, site, attrs={'id':'employee_number_field'}), } fields = ('employee_number', 'work_area', 'station_number') def clean_employee_number(self): employee_number = self.cleaned_data.get('employee_number') if 'WF' in employee_number.team: raise forms.ValidationError("Employee not valid, please contact manager") else: pass return self.cleaned_data views.py class EnterExitArea(CreateView): model = EmployeeWorkAreaLog template_name = "operations/enter_exit_area.html" form_class = WarehouseForm def form_valid(self, form): emp_num = form.cleaned_data['employee_number'] area = form.cleaned_data['work_area'] station = form.cleaned_data['station_number'] if 'enter_area' in self.request.POST: form.save() … -
Input contains NaN, infinity or a value too large for dtype('float64') on Django project
i tried https://github.com/samarth-p/Face_recognition this repo. I cant use identify feature Work on Ubuntu 18.04 with Jatson Nano. Use Python3 and i tried virtualenv Internal Server Error: /identify/ Traceback (most recent call last): File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/exception.py ", line 34, in inner response = get_response(request) File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/base.py", li ne 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/base.py", li ne 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/spoofer/kurulum/app/views.py", line 180, in identify identify_faces(video_capture) File "/home/spoofer/kurulum/app/views.py", line 94, in identify_faces predictions = predict(rgb_frame, model_path="app/facerec/models/trained_mode l.clf") File "/home/spoofer/kurulum/app/views.py", line 66, in predict closest_distances = knn_clf.kneighbors(faces_encodings, n_neighbors=1) File "/usr/local/lib/python3.6/dist-packages/sklearn/neighbors/base.py", line 402, in kneighbors X = check_array(X, accept_sparse='csr') File "/usr/local/lib/python3.6/dist-packages/sklearn/utils/validation.py", lin e 542, in check_array allow_nan=force_all_finite == 'allow-nan') File "/usr/local/lib/python3.6/dist-packages/sklearn/utils/validation.py", lin e 56, in _assert_all_finite raise ValueError(msg_err.format(type_err, X.dtype)) ValueError: Input contains NaN, infinity or a value too large for dtype('float64'). -
How to check_password() with salt?
I have a problem. I am creating a user by User.objects.create(..., password=make_password(data['password'], salt='some_salt'). Thats okay, but how can I check password with this salt? A cant add salt in check_password() method. -
No PUT method in DRF using ModelViewset
I am using Django 2.2 with Django Rest Framework 3.7. I have created a class like this ``` class UserViewSet(viewsets.ModelViewSet): permission_classes = [AllowAny] serializer_class = UserSerializer queryset = User.objects.all() def update(self, request, *args, **kwargs): import pdb;pdb.set_trace() I've created UserSerializer like this - class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'email', 'name', 'password') write_only_fields = ('password',) read_only_fields = ('id',) def create(self, validated_data): user = User.objects.create( email=validated_data['email'], name=validated_data['name'], ) user.set_password(validated_data['password']) user.save() return user def update(self, instance, validated_data): print('lalala from serialzier') import pdb;pdb.set_trace() instance.username = validated_data['username'] instance.save() return instance Only allowed methods being shown are - Allow: GET, POST, HEAD, OPTIONS I wonder why I am unable to perform actions like PUT, DELETE, RETRIEVE. These are by default supported by using ModelViewset as per documentation. In shown code neither serializer's update() nor views.py update() method getting called. Any hint would be appreciable. -
Python List to a Django Databse Table
I have some Django fields, and here is what i'm trying to do. I have a "Times" field, a "Price" Field and a "Start Date" field. So the User would input, for example: Times = 12 Price = 100,00 Start Date = 2019-11-01 with those, the following lists are created: Times = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] Price = [100,00, 100,00, 100,00, 100,00, 100,00, 100,00, 100,00, 100,00, 100,00, 100,00, 100,00, 100,00, ] Start Date = [2019-11-01, 2019-12-01, 2020-01-01, 2020-02-01, 2020-03-01, 2020-04-01, 2020-05-01, 2020-06-01, 2020-07-01, 2020-08-01, 2020-09-01, 2020-10-01, 2020-11-01] I already know how to create those lists, i'm struggling on how to insert them into Django's Database Table, one per line with the same ID or PK. Example - Times Price Dates 1 100,00 2019-11-01 2 100,00 2019-12-01..... -
go to login_url if user is not a staff member
Within my Django site, how would I go to the login_url if the user is not a staff? @user_passes_test(lambda u: u.is_staff, login_url='/denied/') The login_url argument worked with urls that had a permission_required decorator, but is there any way that I can send them to the url /denied/ f they are not a staff with the lambda notaion function shown above? Or is there another way to check if a user is staff, and then send them to the /denied/ url? Thanks for the help! -
How can i get Survey model data from django-survey-and-report with Graphene?
i'm making an API with Django + GraphQL using Graphene, and will like to add a survey feature, i added and install successfully the django-survey-and-report app, and can create and save surveys from the admin panel, but when i try to retrieved the data from the Survey model it gives me an error. # Type Definition class SurveyType(DjangoObjectType): class Meta: model = Survey # Query survey = graphene.List(SurveyType) # Resolver def resolve_survey(self, info, **kwargs): return Survey.objects.all() GraphQL query query{ survey{ id name } } Error "errors": [ { "message": "Received incompatible instance \"<QuerySet [<Survey: Test>]>\"." } ] -
What is default configuration used by gunicorn?
If for example, in the gunicorn startup, I do not set any config like worker_class or workers or even worker_connections, what configs will be used? -
Django database routing on startup
I'm not even sure if this is possible, but is there a way to have Django test the default database upon startup and, if it fails, to then select another database defined in the config? The closest I've seen is writing a DB Router, but that doesn't work if the default connection already fails upon startup. -
How to use .filter()/.get() to see whether a value is in an external model for validation in Django?
I made a form from a model (EmployeeWorkAreaLog) where the user can enter their Employee # and once they press Enter/Leave, it searches a separate model (Salesman) in the db to make sure this person is a valid employee, if not, a message would pop up from the html side saying it's not valid. Now, I'm trying to add another constraint, such that, if the employee is not in the 'WF' team then it would also give an error, and say to contact a manager. I tried doing it from the forms, but I keep getting this error: int() argument must be a string, a bytes-like object or a number, not 'Salesman' and according to the traceback, it comes from if Salesman.objects.get(id=employee_number).count(): Why is this error occurring? Is there a more efficient/better way to check the employee's team? models.py class EmployeeWorkAreaLog(TimeStampedModel, SoftDeleteModel, models.Model): employee_number = models.ForeignKey(Salesman, on_delete=models.SET_NULL, null=True, blank=False) ... def __str__(self): return self.employee_number The part where I filter it so only employee #'s from Salesman is under the widget attrs as shown below forms.py class WarehouseForm(AppsModelForm): class Meta: model = EmployeeWorkAreaLog widgets = { 'employee_number': ForeignKeyRawIdWidget(EmployeeWorkAreaLog._meta.get_field('employee_number').remote_field, site, attrs={'id':'employee_number_field'}), } fields = ('employee_number', 'work_area', 'station_number') def clean_employee_number(self): employee_number = self.cleaned_data.get('employee_number') …