Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Mixed content error in using SSL with Gunicorn/Django/Nginx application
I'm trying to configure HTTPS for an instance of Superdesk, which is using Gunicorn and Nginx for routing. I have a certificate installed and (I think) working on the server. Pointing a browser to the application however gives "Blocked loading mixed active content “http://localhost/api" on Firefox and "WebSocket connection to 'ws://localhost/ws' failed: Error in connection establishment: net::ERR_CONNECTION_REFUSED" on Chrome. The documentation for this application is close to non-existent and I've spent countless hours now trying to get this to work. I filed an issue with the developer on GitHub, but I didn't have much luck with the answer. Here's my Nginx configuration: server { listen 80; listen 443 ssl; server_name my_server_name; ssl on; ssl_certificate /path/to/my/cert.pem; ssl_certificate_key /path/to/my/key/key.pem; location /ws { proxy_pass http://localhost:5100; proxy_http_version 1.1; proxy_buffering off; proxy_read_timeout 3600; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "Upgrade"; } location /api { proxy_pass http://localhost:5000; proxy_set_header Host localhost; expires epoch; sub_filter_once off; sub_filter_types application/json; sub_filter 'http://localhost' 'http://$host'; } location /contentapi { proxy_pass http://localhost:5400; proxy_set_header Host localhost; expires epoch; } location /.well-known { root /var/tmp; } location / { root /opt/superdesk/client/dist; # TODO: use "config.js:server" for user installations sub_filter_once off; sub_filter_types application/javascript; sub_filter 'http://localhost' 'http://$host'; sub_filter 'ws://localhost/ws' 'ws://$host/ws'; } location /mail { alias /var/log/superdesk/mail/; default_type text/plain; … -
Form conflict with naive datetimes
I have a form that creates a lesson with the inputs lesson_datetime_start and lesson_datetime_end. The form worked well until I added in a datetime validator that ensures, dates before the current date cannot be entered. I now receive the error, can't compare offset-naive and offset-aware datetimes. I was wondering if a solution existed to this problem, and would greatly appreciate any help. HTML <form action="{% url 'teacher:new_lesson' %}" method="POST" autocomplete="off"> {% csrf_token %} <!-- Instrument --> <div class="form-group"> <label>Instrument</label> {{ form.lesson_instrument }} </div> <!-- Date Time --> <div class="form-group"> <label>Lesson time availability on one date</label> {{ form.lesson_datetime_start }} {{ form.lesson_datetime_end }} </div> <!-- Check Boxes --> <div class="checkbox"> {{ form.lesson_weekly }} <label>Create lesson weekly</label> </div> <div class="bottom"> <button type="submit" name="submit" class="btn blue_button">Save</button> </div> </form> forms.py def validate_date1(value): value = datetime.utcnow().replace(tzinfo=pytz.UTC) if value < datetime.now(): raise ValidationError('Date cannot be in the past') def validate_date2(value): value = datetime.utcnow().replace(tzinfo=pytz.UTC) if value < datetime.now(): raise ValidationError('Date cannot be in the past') class LessonForm(forms.ModelForm): lesson_instrument = forms.ChoiceField(choices=instrument_list, widget=forms.Select(attrs={'class' : 'form-control', 'required' : 'True'})) lesson_datetime_start = forms.DateTimeField(input_formats=['%Y-%m-%d %I:%M %p'], widget=forms.DateTimeInput(attrs={'class': 'form-control', 'placeholder':'YYYY-MM-DD Hour:Minute am/pm'}), validators=[validate_date1]) lesson_datetime_end = forms.DateTimeField(input_formats=['%Y-%m-%d %I:%M %p'], required=False, widget=forms.DateTimeInput(attrs={'class': 'form-control', 'placeholder':'YYYY-MM-DD Hour:Minute am/pm'}), validators=[validate_date2]) lesson_weekly = forms.BooleanField(required=False) class Meta: model = Lesson fields … -
pbkdf2_hmac takes a long time in django
I'm doing some profiling of a django rest framework API, and using a profiling middleware based on cProfile, I've got the following output: Sat Mar 2 23:55:13 2019 /var/folders/jr/something 41224 function calls (40529 primitive calls) in 0.182 seconds Ordered by: internal time ncalls tottime percall cumtime percall filename:lineno(function) 1 0.124 0.124 0.124 0.124 {built-in method _hashlib.pbkdf2_hmac} 11 0.006 0.001 0.007 0.001 {method 'execute' of 'psycopg2.extensions.cursor' objects} 252 0.003 0.000 0.003 0.000 {built-in method posix.stat} 11 0.002 0.000 0.009 0.001 /Users/my-local-user/.pyenv/versions/3.7.0/lib/python3.7/traceback.py:312(extract) Based on this, calling _hashlib.pbkdf2_hmac once takes almost 70% of my total execution time for a single request! I haven't found a ton of information on this, except that it's used in openSSL - but I'm running locally without ssl. Why is so much of my time being spent in a cryptographic function for a simple API request? -
Setting a random value into a url in django template
On my page i want to create a button which when clicked will randomly take you to a model being viewed on my site in my urls.py i have this defined > path('<int:id>/workout/', views.workout, name='workout') so in the template placing something like <a href="{% url 'workout' 1 %}">Get a random workout</a> works fine, however i want to replace that "1" with a random int Ive tried playing with different ways to define the variable but have not been successful I have tried passing an array of id's from the view and using something like {{ pks|random }} but the url method doesnt want to accept this -
name 'include' is not defined
I am using the most current version of Django (2.1.7). I am trying to import include using the following statement from django.conf.urls import include (which another post said was the correct thing to do) and for some reason I get the following error: path('', inlcude('todo_list.urls')), NameError: name 'inlcude' is not defined Thanks for the help. -
How to add model objects "to cart" in django
I'm trying to work out how to use a very simple bit of "shopping cart" functionality, but I'm no good at this. Let's say I have a simple queryset, "objectos" that comes from: # models.py: class ObjectModel(models.Model): title = models.CharField(max_length=30) ... content = models.TextField() # views.py def product_list(request): objectos = ObjectModel.objects.all() return render(request, 'frontpage/object_list.html', {'objectos':objectos}) ..And let's say I need to insert a simple button in the template that grabs an object from the queryset and puts the object in another queryset. This is what I can't figure out; how to do that secondary queryset.. Anyway, here's a simplified look at what I'm trying to do in the template: <!-- template --> {% for obj in objectos %} {{ obj.title }} {{ obj.content }} <a href="#"> <button type="button">add to other qs!</button> </a> {% endfor %} How could this be done in a simple fashion? I'm considering building a shopping cart, only a lot simpler, but I'm not sure that's the right way to approach it. If you coulddirect me to a good shopping cart tutorial or similar that I could look at, I'd be most grateful :) -
algolia-django issues with the many-to-many models being updated in the algolia index
hi I'm having issues using the algolia django package. I created a model called ProviderInfo with a ManyToMany field that references another model called Practice. A provider should be able to have multiple practices. However, when I make changes on the Admin Panel in django the many-to-many reference fields aren't be reindexed. I looked into github and found a post https://github.com/algolia/algoliasearch-django/issues/202 but it doesn't seem to work. I'm on django 2+ and python3.5+. Models.py class Practice(models.Model): CHOICES = [ ('AK', 'AK'), ('AL', 'AL'), ('AR', 'AR'), ('AZ', 'AZ'), ('CA', 'CA'), ('CO', 'CO'), ('CT', 'CT'), ('DE', 'DE'), ('FL', 'FL'), ('GA', 'GA'), ('HI', 'HI'), ('IA', 'IA'), ('ID', 'ID'), ('IL', 'IL'), ('IN', 'IN'), ('KS', 'KS'), ('KY', 'KY'), ('LA', 'LA'), ('MA', 'MA'), ('MD', 'MD'), ('ME', 'ME'), ('MI', 'MI'), ('MN', 'MN'), ('MO', 'MO'), ('MS', 'MS'), ('MT', 'MT'), ('NC', 'NC'), ('ND', 'ND'), ('NE', 'NE'), ('NH', 'NH'), ('NJ', 'NJ'), ('NM', 'NM'), ('NV', 'NV'), ('NY', 'NY'), ('OH', 'OH'), ('OK', 'OK'), ('OR', 'OR'), ('PA', 'PA'), ('RI', 'RI'), ('SC', 'SC'), ('SD', 'SD'), ('TN', 'TN'), ('TX', 'TX'), ('UT', 'UT'), ('VA', 'VA'), ('VT', 'VT'), ('WA', 'WA'), ('WI', 'WI'), ('WV', 'WV'), ('WY', 'WY') ] user = models.ManyToManyField(User) name = models.CharField(blank=False, max_length=255, unique=True) address_line_1 = models.CharField(blank=False, max_length=255) address_line_2 = models.CharField(blank=False, max_length=255) city = models.CharField(blank=False, max_length=255) … -
How can I make WHERE clause with field from another table in SQL and Django?
Here is table in class from django first app called proizvodi: class Meblovi(models.Model): class Meta: verbose_name_plural = "Meblovi" #OSNOVNI_PODACI ime_proizvoda = models.CharField(max_length=120) proizvodjac = models.CharField(max_length=120, default="proizvodjac") sastav = models.CharField(max_length=120, default="sastav") sirina = models.CharField(max_length=120, default="sirina") zemlja_porekla = models.CharField(max_length=120, default="zemlja porekla") stara_cena = models.DecimalField(decimal_places=2,max_digits=10,default=795.00) nova_cena = models.DecimalField(decimal_places=2,max_digits=10,default=795.00) na_lageru = models.BooleanField() rok_isporuke = models.CharField(max_length=120, default="3 dana") jedinica_mere = models.CharField(max_length=120, default="po dužnom metru") #SLIKE glavna_slika = models.ImageField(upload_to='proizvodi/', null=True, blank=True) #KARAKTERISTIKE vodootporan = models.BooleanField(default=False) vodoodbojan = models.BooleanField(default=False) nezapaljiv = models. BooleanField(default=False) #OSTALO izdvojeno = models.BooleanField() def __str__(self): return self.ime_proizvoda Now, here is table from another app: class Podmeblovi(models.Model): class Meta: verbose_name_plural = "Meblovi - podvrste" #OSNOVNI_PODACI model_mebla = models.CharField(max_length=120) mebl = models.ForeignKey(Meblovi, on_delete=models.CASCADE) slika = models.ImageField(upload_to='proizvodi/', null=True, blank=True) #BOJE bela = models.BooleanField(default=False) svetlo_siva = models.BooleanField(default=False) tamno_siva = models.BooleanField(default=False) crna = models.BooleanField(default=False) bez = models.BooleanField(default=False) braon = models.BooleanField(default=False) zuta = models.BooleanField(default=False) narandzasta = models.BooleanField(default=False) crvena = models.BooleanField(default=False) bordo = models.BooleanField(default=False) svetlo_zelena = models.BooleanField(default=False) tamno_zelena = models.BooleanField(default=False) svetlo_plava = models.BooleanField(default=False) tamno_plava = models.BooleanField(default=False) pink = models.BooleanField(default=False) ljubicasta = models.BooleanField(default=False) #DIZAJN jednobojno = models.BooleanField(default=False) sareno = models.BooleanField(default=False) def __str__(self): return self.mebl.ime_proizvoda + " " + self.model_mebla So what I want is to make a sql query which returns content from table Podmeblovi(second app) but only if field from … -
Form not verifying data on submit
In my view, I included code that should check if the form input for lesson_instrument is equal to a user's instrument1, instrument2, instrument3, instrument4, or instrument5 values. If so the form should pass, and if not, it should fail. However, the form seems to be passing even when the lesson_instrument is not equaling the user's instrument. I would appreciate any insight into why this is occuring. HTML <form action="{% url 'teacher:new_lesson' %}" method="POST" autocomplete="off"> {% csrf_token %} <!-- Instrument --> <div class="form-group"> <label>Instrument</label> {{ form.lesson_instrument }} </div> <!-- Date Time --> <div class="form-group"> <label>Lesson time availability on one date</label> {{ form.lesson_datetime_start }} {{ form.lesson_datetime_end }} </div> <!-- Check Boxes --> <div class="checkbox"> {{ form.lesson_weekly }} <label>Create lesson weekly</label> </div> <div class="bottom"> <button type="submit" name="submit" class="btn blue_button">Save</button> </div> </form> forms.py class LessonForm(forms.ModelForm): lesson_instrument = forms.ChoiceField(choices=instrument_list, widget=forms.Select(attrs={'class' : 'form-control', 'required' : 'True'})) #lesson_level = forms.ChoiceField(choices=level_list, widget=forms.Select(attrs={'class' : 'form-control', 'required' : 'True'})) lesson_datetime_start = forms.DateTimeField(input_formats=['%Y-%m-%d %I:%M %p'], widget=forms.DateTimeInput(attrs={'class': 'form-control', 'placeholder':'YYYY-MM-DD Hour:Minute am/pm'})) lesson_datetime_end = forms.DateTimeField(input_formats=['%Y-%m-%d %I:%M %p'], required=False, widget=forms.DateTimeInput(attrs={'class': 'form-control', 'placeholder':'YYYY-MM-DD Hour:Minute am/pm'})) lesson_weekly = forms.BooleanField(required=False) class Meta: model = Lesson fields = ('lesson_instrument', 'lesson_datetime_start', 'lesson_datetime_end', 'lesson_weekly') views.py def new_lesson(request): if request.user.is_authenticated and request.user.time_zone: activate(request.user.time_zone) else: deactivate() user = request.user if request.method == … -
Django passing a value through a ListView
I have the listview working, and I tested a def in the shell, so now I'm tring to pass the returned result from the def through the listview so I can display the value in the html. So the problem is, how to do this? Here is the def, it is passing some raw sql which compares two tables in two different schemas to show the user how many records need updating. def count_new_rows(): with connection.cursor() as cursor: cursor.execute(""" SELECT count(*) FROM samples.samples a FULL OUTER JOIN kap.sample b ON a.area_easting = b.area_easting AND a.area_northing = b.area_northing AND a.sample_number = b.sample_number AND a.context_number = b.context_number WHERE (a.area_easting IS NULL AND a.area_northing IS NULL AND a.sample_number IS NULL AND a.context_number IS NULL) OR (b.area_easting IS NULL AND b.area_northing IS NULL AND b.sample_number IS NULL AND b.context_number IS NULL) """) count = cursor.fetchall() return count And here is the functioning listview class SampleListView(generic.ListView): template_name = 'sample/sample_list.html' model = Sample paginate_by = 50 queryset = Sample.objects.filter(sample_type='Organic') Do I add the following? If so how do I access the data on the html side? data = count_new_rows() -
How can I recover a profile picture from an author in other app?
I'm creating a blog post right now and I'm new at Django. I have an avatar picture in another app(registration) and I'm trying to import and associate correctly to another app (pages). In other words, I need to recover, in the HTML, the exact avatar picture from the user who creates a post. Thanks! models.py (registration) from django.db import models from django.contrib.auth.models import User from django.dispatch import receiver from django.db.models.signals import post_save def custom_upload_to(instance, filename): old_instance = Profile.objects.get(pk=instance.pk) old_instance.avatar.delete() return 'profiles/' + filename class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) avatar = models.ImageField(upload_to=custom_upload_to, null=True, blank=True) bio = models.TextField(null=True, blank=True) link = models.URLField(max_length=200, null=True, blank=True) class Meta: ordering = ['user__username'] @receiver(post_save, sender=User) def ensure_profile_exists(sender, instance, **kwargs): if kwargs.get('created', False): Profile.objects.get_or_create(user=instance) models.py (pages) from django.db import models from ckeditor.fields import RichTextField from django.contrib.auth.models import User from registration.models import Profile class Page(models.Model): title = models.CharField(verbose_name="Título", max_length=200) # Titulo author = models.ForeignKey('auth.User', verbose_name="autor", on_delete=models.CASCADE, null = True) content = RichTextField(verbose_name="Contenido") # Contenido order = models.SmallIntegerField(verbose_name="Orden", default=0) # Orden de publicacion created = models.DateTimeField(auto_now_add=True, verbose_name="Fecha de creación") # Fecha de creacion updated = models.DateTimeField(auto_now=True, verbose_name="Fecha de edición") # Fecha de actualizacion class Meta: verbose_name = "página" verbose_name_plural = "páginas" ordering = ['order', 'title'] def __str__(self): return … -
Filter templates by ChoiceField - Django
consider this model on Django: class My_model(models.Model): my_choices = { '1:first' 2:second'} myfield1=CharField() myfield2=CharField(choices=my_choices) Then on my form: class My_form(forms.ModelForm): class Meta: model = My_model fields = ['myfield1', 'myfield2'] My views: def get_name(request): if request.method == 'POST': form = My_form(request.POST) if form.is_valid(): return HttpResponseRedirect('/') else: form = My_form() return render(request, 'form/myform.html', {'form': form}) On my template: {% extends "base.html" %} {% block content %} <form action="/tlevels/" method="POST"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Submit"> </form> {% endblock %} On my base.html, I will load this template like this: {% extends "base.html" %} {% block content %} {% load crispy_forms_tags %} <div class="p-3 mb-2 bg-info text-white" style="margin-left:20px; margin-bottom:20px;">Status</div> <div class="form-row" style="margin-left:20px; margin-bottom:20px; margin-top:20px;"> <div class="form-group col-md-6 mb-0"> {{ form.myfield1|as_crispy_field }} </div> <div class="form-group col-md-6 mb-0"> {{ form.myfield2|as_crispy_field }} </div> </div> <input type="submit" class="btn btn-primary" value="Submit" style="margin-left:20px;"> </form> {% endblock %} What I want, is to have 2 other different templates, with whatever difference on them, and load them depending on the choice made on the ChoiceField, I guess that one way could be on the view, by adding some kind of conditional, and load a different template (html file). Any ideas? -
Django pytest access database
I am wanting to use pytest with django to only test functions that query the database. I don't want to create a new database for running these tests. Currently in my pytest files, I have to have the following: import os os.environ.setdefault("DJANGO_SETTINGS_MODULE","myProject.settings") import django django.setup() I have added the pytest-django package to my project, but it doesn't have this pytest.mark.django_db function. Is there an easy way to work around this? -
How to delete hundreds of documents to a Django Web App?
I developed a Django application and i have to process 500 documents (I have to upload them using a .zip/.rar and to process them one by one using NLP). The problem is that when i try to upload all the 500 documents my app takes so much time, around 2 hours. I would like to know what is the best way to upload these documents using the Django Framework? How can i upload them one by one so i will not have time out problems or too big file errors? P.D The user wants to upload the 500 documents compressed in .zip/.rar file. He wants to upload this file once so the system has to process the 500 documents once. So i have to find a way to upload them without overloading my Web App. I tryied to upload them once, but the server process takes so much time uploading 500 documents and i can find http time out errors or too big entity errors. -
Pass a function result to html in Django
While learning Django, I can't figure out one simple thing. May be very obvious to any Django devs. I've read the docs and it seem to have to work. Here's my code: #views.py def function_name(): return 'Hello, World!' #index.html <div> <h1>{{ function_name }}</h1> </div> Yet the result is: <div> <h1></h1> </div> I must be missing something fundamental but can't find out what it is. -
Coping good from web-sites.(django)
Oh,hello there! I am now writing a site, where I need to copy the goods fron another web-site. Is there any idea of doing this? -
is_ajax() POST to Django fails
So here is my code: export.html: $(document).ajaxSend(function (event, jqxhr, settings) { jqxhr.setRequestHeader("X-CSRFToken", '{{ csrf_token }}'); }); $("#form-info").submit(function(event) { var myEvent = {'timestart': start, 'timeend':end}; $.ajax({ url: "/export/", cache:false, type: 'POST', headers: {'X-Requested-With': 'XMLHttpRequest'}, dataType: "json", contentType: "application/json; charset=utf-8", data: myEvent, success: function(){ alert("Whoooo"); }, error: function(){ alert("Boooo"); }, crossDomain: false }); }); }); views.py @csrf_exempt def post(self, request): print("post func") print(request.is_ajax()) if request.is_ajax(): print("Wheee") args = {} return render(request, 'edashboard/export.html', args) What I'm getting in my terminal is the "post func" print call and then "false" from printing out request.is_ajax(). In my browser I'm getting the alert saying "Boooo" from my error function. I'm not sure what's going on at all, and I'm fairly new to Django. Im running Django 2.1.5 for this project. -
Like function error: getting null queryset while filtering
I am trying to implement a normal like function on a post comment. I am getting an error - 'QuerySet' object has no attribute 'liked'. I am presuming this is because my filter is returning an empty queryset. I tried to look for why this is happening and it seems there is something wrong with the primary key and hence it is not filtering the queryset rightly and hence the like function is not working. Also, note that I have also tried logging in with different user-id. Can anyone findout the error here. Thanks in advance. views.py class AbcListAPIView(generics.ListAPIView): serializer_class = AbcModelSerializer queryset = Abc.objects.all().order_by("-created") class LikeToggleAPIView(APIView): permission_classes = [permissions.IsAuthenticated] def get(self, request, pk, format=None): abc_qs = Abc.objects.filter(pk=pk) user = self.request.user print(pk) print(Abc.objects.all()) print(abc_qs) message = "Not Allowed" if request.user.is_authenticated(): if user in abc_qs.liked.all(): is_liked = False abc_qs.liked.remove(user) else: is_liked = True abc_qs.liked.add(user) return Response({'liked':is_liked}) return Response({"message": message}, status=400) models.py class Abc(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL) body = models.CharField(max_length=250, null=True) liked = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True, related_name='liked') def __str__(self): # return self.body return '%s : %s : %s' % (self.body, self.liked) def get_absolute_url(self): return reverse("blog:Frpost", kwargs={"pk":self.pk}) urls.py - blog/api urlpatterns = [ url(r'^$', AbcListAPIView.as_view(), name='list'), #/api/blog/ url(r'^(?P<pk>\d+)/like/$', LikeToggleAPIView.as_view(), name='like-toggle'),] Frpost.html <script> $(document.body).on("click", ".abc-like", … -
Including Django-Tagulous tags in a Q Search
I have a blog style Django app and have implemented Django-Tagulous to manage tags. I have a Post model with standard fields like Title and Content and I also have a tags field tags = tagulous.models.TagField() When I create a Post the tags are working and saving correctly, I'm now starting to work on search functionality and have the following in my post_list view queryset_list = Post.objects.all().order_by('-timestamp') query = request.GET.get("q") if query: queryset_list = queryset_list.filter( Q(title__icontains=query)| Q(content__icontains=query) ).distinct() I'd really like to include the associated tags but can't get my head round how to do it. Does anyone have any pointers how to include tags in searches? I'd really appreciate the help -
How to prevent django from running multiple instances of a command?
We have a custom command in a django app that performs synchronization of data with an external service. The command is started hourly. Usually, the command is finished within half an hour or less, but recently, we ran into a situation where the process took several hours. In the meantime, the command was started several times again in the background, causing inconsistent access to the models (because our code was not designed for this situation). Is it possible to prevent django from running the command if it is already running? One way I think of solving this problem is to use a file as a mutex for the command. But this does not seem very elegant to me, as it could cause any amount of extra trouble in case the command gets interrupted and the file might not be cleaned up properly. What is the best way to approach this problem? -
django - display all groups with their users
With django auth group and user models, I want to query all groups with their users. (user_id list would be fine). I tried Group.objects.all().select_related('user') But it isn't working. -
Is it good to store messages in json field django?
In my django app, I need a app for conversation between user and author for that I am planning to make a model as - class AuthorContact(models.Model): messages = JSONField(default=dict) user = models.ForeginKey(User,related_name="contact_user",on_delete=models.CASCADE) author = models.ForeginKey(Author, related_name="contact_manager",on_delete=models.CASCADE) what I am planning to store messages as - { '1':{'sender':'user','date':'02/12/2019','message':'Hi I read your book, it\'s amazing !'}, '2':{'sender':'author','date':'0312/2019','message':'Thank you, it\'s my pleasure.}' } If message is CharField then I need to create object for every message with user and author. I am doing this so I need not to create object for every message and its easy for db to find conversation between specific user and author. My questions are - Is is good practice ? How much max size does PostgreSQL allow to store in this json field? Is this trick beneficial, rather then creating object for every message and then searching for a specific chat ? Is their any another better way? -
Django 2.1.7, database updating
After a change is made to the database (E.G. a image upload), the return or redirect methods display the returned webpage WITHOUT the updated image... it either shows no image or the previous image that is stored in the database. There is a timing issue between update and getting the new file. I initially began using a for loop with a time.sleep() function to wait and periodically call a new user instance to see if the new file exists but this seems unsophisticated and crude. What other ways (built-in modules? / 3rd party code?) could I use to cause the browser to wait and check for completeness while the file/image uploads before redirecting the user to a new page? -
password mismatch in registration form that inherits fro UserCreationForm - Django
I have a form that inherits from the UserCreationForm. the file looks like this: from django import forms from django.contrib.auth import password_validation from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User, Group from main.models.users import PandaUser class PmyUserCreationForm(UserCreationForm): email = forms.EmailField(required=True) group = forms.CharField(max_length=50, required=True) class Meta: model = PandaUser fields = ("group", "email", "username", "email", "password1", "password2") def save(self, commit=True): user = super(PandaUserCreationForm, self).save(commit=False) user.email = self.cleaned_data["email"] if commit: user.save() return user For some reason, when trying to fill up the form, I get a password mismatch error like so: ERROR - {'password_mismatch': "The two password fields didn't match."} I tried overriding the clean_password1 and clean_password2 with no help. Code: def clean_password1(self): password1 = self.cleaned_data.get('password1') try: password_validation.validate_password(password1, self.instance) except forms.ValidationError as error: # Method inherited from BaseForm self.add_error('password1', error) return password1 Any ideas why this is happening/why is it thinking that both of my passwords are not identicle (im sure they are, I tried a million times and copy and pasted) -
Django paginator changes pages content every iteration
I'm using Django 2.1 I'm trying to iterate over a queryset using paginator. For some reason it looks like every iteration the pages content is different. for example on first iteration the first page contains some item, and in the next iteration, that item is now on the second page. This is how I'm using it: items_qs = Item.objects.all().filter( created_at__lte=on_date ) all_items_paginator = Paginator(items_qs, 1) for page_number in all_items_paginator.page_range: page = all_items_paginator.page(page_number) items_ids_list = [item.id for item in page.object_list]