Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Deploying Django-Channels app to Heroku with Daphne
I am trying to deploy a Django channels app to Heroku using daphne but cannot find a configuration that works with up-to-date dependencies. I did my initial config with the channels documentation (https://channels.readthedocs.io/en/latest/deploying.html) and have got the application running locally via daphne. I think the issue is probably with my ProcFile config and some missing component for serving the page in production. I have tried a number of configurations, but am limited to one web server and one worker via Heroku's free option. I am not sure if this application will work in deployment configured as ASGI ("daphne chatproject.asgi:application"), but it does work locally. My ProcFile is: web: daphne chatproject.asgi:application worker: python3 manage.py runworker channels I have also tried other things like binding to ports, but am limited in my knowledge. Things like 'daphne -b 0.0.0.0 -p 8001 myproject.asgi:application' (not sure if host ip actually required). In Heroku I have scaled to use both web and worker dynos and they appear in my heroku config. This is my redis config and my asgi.py is configured 100% to the documentation. WSGI_APPLICATION = 'chatproject.wsgi.application' # Channels ASGI_APPLICATION = 'chatproject.routing.application' CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": [os.environ.get('REDIS_URL', 'redis://localhost:6379')], }, … -
utf-8' codec can't decode byte 0xa9 in position 112483: invalid start byte in django?
I deployed my django website which is working fine till today.Now, out of nowhere it starts showing unicodedecodeerror Check error message here whilw the full traceback is :- Traceback (most recent call last): File "/home/gagan/saporawebapp/Sapora/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/gagan/saporawebapp/Sapora/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/gagan/saporawebapp/Sapora/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/gagan/saporawebapp/webapp/views.py", line 214, in explore return render(request,'explore/explore.html',{'query':query,'main':query2,'rank':query3,'sec':query4,'lis':query5,'result':result,'theme':request.user.profile.theme}) File "/home/gagan/saporawebapp/Sapora/lib/python3.6/site-packages/django/shortcuts.py", line 36, in render content = loader.render_to_string(template_name, context, request, using=using) File "/home/gagan/saporawebapp/Sapora/lib/python3.6/site-packages/django/template/loader.py", line 61, in render_to_string template = get_template(template_name, using=using) File "/home/gagan/saporawebapp/Sapora/lib/python3.6/site-packages/django/template/loader.py", line 15, in get_template return engine.get_template(template_name) File "/home/gagan/saporawebapp/Sapora/lib/python3.6/site-packages/django/template/backends/django.py", line 34, in get_template return Template(self.engine.get_template(template_name), self) File "/home/gagan/saporawebapp/Sapora/lib/python3.6/site-packages/django/template/engine.py", line 143, in get_template template, origin = self.find_template(template_name) File "/home/gagan/saporawebapp/Sapora/lib/python3.6/site-packages/django/template/engine.py", line 125, in find_template template = loader.get_template(name, skip=skip) File "/home/gagan/saporawebapp/Sapora/lib/python3.6/site-packages/django/template/loaders/base.py", line 24, in get_template contents = self.get_contents(origin) File "/home/gagan/saporawebapp/Sapora/lib/python3.6/site-packages/django/template/loaders/filesystem.py", line 24, in get_contents return fp.read() File "/home/gagan/saporawebapp/Sapora/lib/python3.6/codecs.py", line 321, in decode (result, consumed) = self._buffer_decode(data, self.errors, final) UnicodeDecodeError: 'utf-8' codec can't decode byte 0xa9 in position 112483: invalid start byte -
Not receiving same OTP in a time step/interval - Django-otp
I have set time step as 300sec and TOTP digit as 6. I'm not receiving same OTP in a time step/interval, means receiving different OTP in a given time step. ie, At 2019-11-03 19:15:00, i will get one code; 19:13:00 , i will get another new code. this is the code: import datetime import time from django_otp.oath import TOTP from django_otp.util import random_hex class TOTPVerification: def __init__(self): # secret key that will be used to generate a token, # User can provide a custom value to the key. self.key = random_hex(20) # counter with which last token was verified. # Next token must be generated at a higher counter value. self.last_verified_counter = -1 # this value will return True, if a token has been successfully # verified. self.verified = False # number of digits in a token. Default is 6 self.number_of_digits = 6 # validity period of a token. Default is 30 second. self.token_validity_period = 300 def totp_obj(self): # create a TOTP object totp = TOTP(key=self.key, step=self.token_validity_period, digits=self.number_of_digits) # the current time will be used to generate a counter totp.time = time.time() return totp def generate_token(self): # get the TOTP object and use that to create token totp = self.totp_obj() … -
How to configure AWS s3 to upload file AWS ec2 instance using Django
I'm currently running a Django project on an AWS EC2 server that has RHEL8 installed as the OS. My AWS environment is configured to store both static files and media files into a S3. My django app model leverages ImageField to upload an image and store in S3. When attempting to save an image to S3 via my django app, I'm currently getting a permission denied HTTP 500 connection error and the issue is not my django app, as I tested the exact same application with same configurations (setting.py) on my localhost and I can successfully upload both static files and media files to s3. Why would it work on my localhost and not in my EC2 instance? The issue is specific to connecting to S3 via the EC2 while uploading the image, as I had no issues uploading static files to S3 from my EC2 instance. In troubleshooting the above issue, I wanted to rule out that the issue was related to my django application, perhaps my settings.py file. I installed the exact same django project on my localhost (laptop) and was able to upload both static files and an image file to my S3 bucket via my django … -
how to add another 0000n_initial.py file from makemigrations command
i want to add another initial.py file from makemigrations file when i try to py manage.py makemigrations it show error you are trying to add a non-nullable field 'role' to user without a default; we can't do that (the database needs something to populate existing rows). Please select a fix : Provide a one-off default now(will be set on all existing rows with a null value for this column) Quit, and let me add a default in models.py i want to make another init to make a dependent dropdown this is what i write in models.py import datetime from django.db import models from django.utils import timezone class TableAll(models.Model): table_name = models.CharField(max_length=250) i want to add a foreign key to another model and want to makemigrations to add a new 00002_initial.py(for example) and i want to have something like this(here is the code i found from github source) new initial file (0002_add_initial_data.py) //this is just an example class Migration(migrations.Migration): Country = apps.get_model('hr', 'Country') City = apps.get_model('hr', 'City') india = Country.objects.create(name='India') City.objects.create(name='Bengaluru', country=india) City.objects.create(name='Mumbai', country=india) City.objects.create(name='Chennai', country=india) City.objects.create(name='Hyderabad', country=india) City.objects.create(name='New Delhi', country=india) usa = Country.objects.create(name='United States') City.objects.create(name='New York', country=usa) City.objects.create(name='San Francisco', country=usa) City.objects.create(name='Los Angeles', country=usa) City.objects.create(name='Chicago', country=usa) City.objects.create(name='Seattle', country=usa) russia = Country.objects.create(name='Russia') … -
Increment object's field on creation Django
I'm trying to either get or create an object. However, if I decide to create a new object, I want to keep count of what number in the list, the object is: cat = Cat.objects.get_or_create( profile='Juan' defaults={ counter=Cat.objects.filter(profile='Juan').count() + 1 } ) This looks kinda weird. I was thinking if I could use F() or something related. -
Ordering by m2m field
I have 2 model, and i need ordering to my query. First model: class Author(m.models): name = m.Charfield() Second model: class Book(m.models): title= m.CharField() authors = m.ManyToManyField('Author') I expected what this code return next result Book.objects.all().order_by('authors__name') Some[A] Some[A,B] Some[B,] ... Some[Z, B,D] But I get some like this: Some[A,B] Some[B,] Some[A,B] ... Some[Z, B,D] Why correct way to ordering by m2m field? -
Most efficient way to make continuous sequence of objects in Django
I have model like: city = CharField() order = PositiveIntegerField(default=0) and i'd like to fix sequence and make it uninterruptible. For example if I have: London 0 Paris 5 Boston 7 I need to delete gaps and transform it to: London 0 Paris 1 Boston 2 I can achieve it via something like: current_order = 0 cities = City.objects.all().order_by('order') for city in cities: if not current_order: current_order = city.order else: city.order = current_order city.save() current_order += 1 I found this solution completely inefficient as it hits DB multiple times so I'm thinking how to achieve similar behavior more efficiently, preferable via DB engine (PostgreSQL). -
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').