Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django on Heroku continues to process an old worker request on repeat?
I finally set up RQ on Django, and for some reason the worker dyno continues to run on repeat with old values I was testing. As soon as the job results return, it once again starts. I tried FLUSHALL with redis, I tried stopping my front end app engine, I tried restarting and redeploying my Django app on Heroku, but the only thing that seems to temporarily work is turning off the worker dyno until I turn it back on. My current add on list is Heroku Postgress, Heroku Redis, and Heroku Redis To Go. I don't know why it continues to restart the worker queue with the same values, and no amount of fiddling is working. -
When I try to validate 'username' field in Django form with clean_method I get a NameError
Here is my forms.py file. I got a "NameError: name 'username' is not defined" on this row: def clean_username(self): trying to submit this form, but, AFAIK, there are nothing wrong with it. from .models import Blog from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from django.core.exception import ValidationError class PostForm(forms.ModelForm): class Meta: model = Blog fields = ('title', 'description',) class SignUpForm(UserCreationForm): username = forms.CharField(max_length=30) first_name = forms.CharField(max_length=150) #, help_text='First Name') last_name = forms.CharField(max_length=150) #, help_text='Last Name') email = forms.EmailField(max_length=200, help_text='Required. Enter a valid email address') def clean_username(self): nom_de_guerre=self.cleaned_data['username'] if User.objects.filter(username=nom_de_guerre).exists(): raise forms.ValidationError('User with this name is already exists!') def clean_email(self): addresse_de_mail=self.cleaned_data['email'] if User.object.filter(email=addresse_de_mail).exists(): raise forms.ValidationError('User with this email is already exists!') class Meta: model = User fields = ('username', 'email', 'first_name', 'last_name', 'password1', 'password2', ) ``` -
Is there a way to create a back button in Django that understands a tree structure?
I have a Django website that looks like this: The arrows represent hyperlinks that take you to the next page. All pages except the Main Page need a "Back" button. For Page A and Page B, the back button is pretty simple - it always takes you to the Main Page. For Page C however, there are 2 different ways to get to it (technically 3, if you count the back button on Page D), so it's no longer obvious where the back button should take you. The way it should work is this: If the user came from Page A to get to Page C, the Back button should take them back to Page A If the use came from Page B to get to Page C, the Back button should take them back to Page B If the user didn't come from either Page A or Page B to get to Page C (they could have just entered the URL of Page C into their browser), default to having the Back button take them to Page A This has been asked before, and none of the answers/suggestions make sense for anything other than the most basic scenario, where … -
TypeError: Planet() got an unexpected keyword argument 'name'
from django.db.models.fields import CharField # Create your models here. class Planet(models.Model): name: models.CharField(max_length=50) number: models.IntegerField() I used python shell to run: python manage.py shell from planet_universe.models import Planet large_jupiter = Planet(name="Jupiter1", number=1) I get the following error: TypeError: Planet() got an unexpected keyword argument 'name'. How do I correct this error? -
I'm trying to deploy django web app on heroku but i couldn't after deploy heroku shows first method not allowed then bad request
[here is project structure ][1] when I write Heroku local then enter terminal shows an error no procfile but here we can see above [1]: https://i.stack.imgur.com/d54wN.png -
How to use clickhouse in django project?
I have a Chat model that is stored in postgresql class Chat(StatusModel, MyTimeStampedModel): closed_at = MonitorField(monitor='status', when=['closed']) channel = models.ForeignKey(Channel, on_delete=models.PROTECT, null=True) I need to count the number of open and closed chats using clickhouse. How can I do this? -
How can show django auth-views URLs on swagger?
I set the Urls like belows. users>urls.py from django.urls import path from django.contrib.auth import views as auth_views from users import views .... path( "changePassword/", auth_views.PasswordResetView.as_view(), name="password_reset" ), # 비밀번호 변경 (링크 발송) path( "changePasswordDone/", auth_views.PasswordResetDoneView.as_view(), name="password_reset_done", ), # 비밀번호 변경(링크 선택 후 화면) path( "changePasswordConfirm/<uidb64>/<token>/", auth_views.PasswordResetConfirmView.as_view(), name="password_reset_confirm", ), # 비밀번호 변경(사용자 전송 링크) path( "changePasswordComplete/", auth_views.PasswordResetCompleteView.as_view(), name="password_reset_complete", ), # 비밀번호 변경(사용자 새 비밀번호 입력 후) ] but the auth_views doesn't appear in the swagger like below images. I guess there is some problem in the settings.py.... but don't know the detail. config>settings.py # Rest_Framework JWT REST_FRAMEWORK = { "DEFAULT_PERMISSION_CLASSES": ( # 'rest_framework.permissions.IsAuthenticated', #401 에러 회피 "rest_framework.permissions.AllowAny", # 401 에러 회피 ), "DEFAULT_AUTHENTICATION_CLASSES": ( "rest_framework_simplejwt.authentication.JWTAuthentication", # 'rest_framework.authentication.SessionAuthentication', # 'rest_framework.authentication.BasicAuthentication', ), } could you help kindly please? -
can i let the field in the html to have a specific layout when this value is not the default values
i made some fields useing Django as models.CharField and set the default values to default="-" i also made the html tamplat to show the fields. so can i let the field in the html to have a specific layout or text effect when this value is not the default values default="-" modeks.py Iron_Fe = models.CharField(max_length=100, default="-", blank=True, null=True) Carbon_C = models.CharField(max_length=100, default="-", blank=True, null=True) html <td id="Fe" title="Iron"><sup>{{ object.Iron_Fe }}</sup>Fe</td> <td id="C" title="Carbon"><sup>{{ object.Carbon_C }}</sup>C</td> -
Django, looping inside a father-child tree
I am trying to loop over a father-child tree relationship were the child also can be a father and print it's children for the far being i'v only been able to print the primitive father and the children (but i cant figure out how to print the children's children) Here is the Model : class Component(models.Model): component_name = models.CharField(max_length=100) component_manufacturer = models.CharField(max_length=100) component_model = models.CharField(max_length=100) component_number = models.CharField(max_length=255) component_price = models.IntegerField() component_note = models.TextField() parent_component = models.ForeignKey("self", verbose_name=( "Parent Component"), blank=True, null=True, related_name='children', on_delete=models.CASCADE) is_child = models.BooleanField(default=False) def __str__(self): return f"{self.id}, {self.component_name}" the view : def index(request): f = Component.objects.all() context = { 'f': f } return render(request, 'maintenance/index.html', context) the template : <div class='component'> Components<ol> {%for f in f%} {%if f.is_child is False %} <li> {{f.component_name}}</li> <ol> {% for f in f.children.all %} <li> {{f.component_name}}</li> {%endfor%} </ol> {%endif%} {%endfor%} </ol> </div> Thanks plenty! -
Value errror don't mix args and kwargs
ValueError at /postsignin Don't mix *args and **kwargs in call to reverse()! Request Method: POST Request URL: http://127.0.0.1:8000/postsignin Django Version: 3.2.3 Exception Type: ValueError Exception Value: Don't mix *args and **kwargs in call to reverse()! Exception Location: C:\Users\ASUS\AppData\Local\Programs\Python\Python39\lib\django\urls\resolvers.py, line 624, in _reverse_with_prefix Python Executable: C:\Users\ASUS\AppData\Local\Programs\Python\Python39\python.exe Python Version: 3.9.6 Python Path: ['S:\Work\Fortech', 'C:\Users\ASUS\AppData\Local\Programs\Python\Python39\python39.zip', 'C:\Users\ASUS\AppData\Local\Programs\Python\Python39\DLLs', 'C:\Users\ASUS\AppData\Local\Programs\Python\Python39\lib', 'C:\Users\ASUS\AppData\Local\Programs\Python\Python39', 'C:\Users\ASUS\AppData\Roaming\Python\Python39\site-packages', 'C:\Users\ASUS\AppData\Local\Programs\Python\Python39\lib\site-packages', 'C:\Users\ASUS\AppData\Local\Programs\Python\Python39\lib\site-packages\win32', 'C:\Users\ASUS\AppData\Local\Programs\Python\Python39\lib\site-packages\win32\lib', 'C:\Users\ASUS\AppData\Local\Programs\Python\Python39\lib\site-packages\Pythonwin'] Server time: Sat, 25 Dec 2021 14:45:40 +0000 Views def postSignIn(request): try: email = request.POST.get('email') password = request.POST.get('password') auth.sign_in_with_email_and_password(email, password) return redirect('/', request) except error: return redirect(reverse('signin', args=request, kwargs={'msg': 'id'})) urls urlpatterns = [ path('', views.index, name='index'), path('signin', views.signIn, kwargs={'msg': 'None'}, name='signin'), path('postsignin', views.postSignIn, name='postsignin'), ] -
Why does model not connect with user?
I have a model that appers in admin. But it doesn't connect with user automatically. I always have to specify user in admin. I have a form for creation. But when I create with this form it doesn't appear on the screen. Models class Notion(models.Model): user = models.ForeignKey( User, on_delete=models.CASCADE, related_name='notions', null=True, blank=True) title = models.CharField(max_length=100) body = models.TextField() -
How to print many-to-many field
models.py: from django.db import models class Course(models.Model): course = models.TextField(blank=True) class Student(models.Model): first_name = models.TextField() last_name = models.TextField() course = models.ManyToManyField(Course) forms.py: from django import forms from .models import Student, Course class StudentForm(forms.ModelForm): class Meta: model = Student fields = ['first_name', 'last_name', 'course'] class CourseForm(forms.ModelForm): class Meta: model = Course fields = ['course'] views.py: def students_view(request): if request.method == 'POST': students_form = StudentForm(request.POST) if students_form.is_valid(): students_form.save() print(Student.objects.all().values()) students_form = StudentForm() context = { 'form':students_form } return render(request, 'courses/courses.html', context) If I print print(Student.objects.all().values()) than I see student's ID, first_name and last_name. But I don't see in which groups they belong to. How to print that? -
(fields.E300) Field defines a relation with model 'Product', which is either not installed, or is abstract Django
I'm new in django, I faced with following error when I wanted to define two models which have foreignkey to each other . I searched about it and I find out this might happen when the models have been in two different apps, but my models are in one app . would you please help me about this . Thanks ERRORS: ?[31;1mstore.Collection.featured_product: (fields.E300) Field defines a relation with model 'Product', which is either not installed, or is abstract.?[0m class Collection(models.Model): title = models.CharField(max_length=255) featured_product = models.ForeignKey( 'Product', on_delete=models.SET_NULL, null = True, related_name= '+') class Product(models.Model): title = models.CharField(max_length=255) description = models.TextField() price = models.DecimalField(max_digits=6, decimal_places=2) inventory = models.IntegerField() last_update = models.DateTimeField(auto_now=True) collection = models.ForeignKey(Collection, on_delete=models.PROTECT) promotion = models.ManyToManyField(Promotion) -
How to upload and deploy zip folder?
I want to upload and deploy the zip folder downloaded from repl.it to AWS eb, but it is difficult to find even if I google it.. -
Error10060 Time our when trying to send_mail with django
Here is my setting:(I'm pretty sure the password and user is correct, becauese if I intentionally input wrong password it will returen authenticationException but not time out) DEFAULT_FROM_EMAIL = 'xxxx' EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = 'xxxx' EMAIL_HOST_PASSWORD = 'xxxxxxxx' I try this in python shell: send_mail('Test', 'This is a test', 'xxxx@gmail.com', ['xxxx@gmail.com'], fail_silently=False) It return timeout exception. plus:I'm using vpn, I think may be this is the culprit, but I don't know how to solve it, thanks for your help. -
How to get the name of the month instead of the month number from db
I am picking some data from the db to make some analytics in my website. I am rendering out the data graphically with the help of chart js. This is how I am doing it in views, views.py monthly_visitor = VisitorCount.objects.all().filter(date_of_record__year = currentYear.year).values( 'date_of_record__month' ).annotate( total_in_month=Count('ip') ).order_by('date_of_record__month') Here, I am picking up the data of all the visitors of every month of the current year. Now if I print the monthly_visitor I get the below result <QuerySet [{'date_of_record__month': 9, 'total_in_month': 1}, {'date_of_record__month': 10, 'total_in_month': 2}, {'date_of_record__month': 11, 'total_in_month': 3}, {'date_of_record__month': 12, 'total_in_month': 5}]> Which is correct but what I want is <QuerySet [{'date_of_record__month': sept, 'total_in_month': 1}, {'date_of_record__month': oct, 'total_in_month': 2}, {'date_of_record__month': nov, 'total_in_month': 3}, {'date_of_record__month': dec, 'total_in_month': 5}]> So that I can display names of the month in the graph rather the numbers. I came across some methods to use tags in the html. But I am importing this data into a different javascript file with the help of ajax. Please suggest me what should I do. -
Python Django html templating
I'm building a web portfolio for albums photography and others features, but the html templating is a bit messy for me, I have few diferents questions related to this subject. Here are my models: class Album(models.Model): title = models.CharField(max_length=150) date_init = models.DateField("From", default=date.today) date_end = models.DateField("To", default=date.today) album_cover = models.ForeignKey('Photo', null=True, blank=True, on_delete=models.RESTRICT, related_name='Album') class Photo(models.Model): image = models.ImageField(upload_to="photos/") alt_text = models.CharField(max_length=100) album = models.ForeignKey(Album, on_delete=models.CASCADE, related_name='photos') tags = TaggableManager(blank=True) 1- I have a Navbar in a base.html : {% block sidebar %} ... <ul class="dropdown-menu" aria-labelledby="navbarDropdown"> <li><a class="dropdown-item" href="#">2021</a></li> <li><hr class="dropdown-divider"></li> <li><a class="dropdown-item" href="#">2018</a></li> <li><a class="dropdown-item" href="#">2014</a></li> ... {% endblock %} </ul> My idea is to show only years for where at least one album is saved in database (ghost 2020 and 2019 cause there is no data for example). But my problem is that this code is in the base.html that I extend everywhere. I know I can modify this with {% block sidebar %}, but this informations need to be in all templates too. If I'm right I can't send data to the base.html to populate the list ? Is there a way to achieve this without copy/paste code into all html templates? If needed, my request … -
Why is my frontend (VueJS) being blocked by CORS policy in API (Django)
I am using Django-Rest-Framework for a project, and VueJS as the frontend. I send the API requests using Axios. For all endpoints, I have not faced any issues. But I created an endpoint for changing an account's user, it takes the old password, new password, and the token of the user. When I try to hit that endpoint I get an error such as this: I tried most of the solutions here, like adding the localhost to CORS_ALLOWED_ORIGINS and setting CORS_ORIGIN_ALLOW_ALL = DEBUG. I also download cors-headers Here is my settings.py: DEBUG = True CORS_ORIGIN_ALLOW_ALL = DEBUG ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken', 'accounts', 'clubs', 'events', 'announcements', 'comments', 'corsheaders', 'requests', 'clubenrollment' ] 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', 'corsheaders.middleware.CorsMiddleware', ] CORS_ALLOWED_ORIGINS = [ 'http://localhost:8080' ] this is the urls.py path('api/change-password/', ChangePasswordView.as_view(), name='change-password'), This is my views.py class ChangePasswordView(generics.UpdateAPIView): """ An endpoint for changing password. """ serializer_class = ChangePasswordSerializer model = Account permission_classes = (permissions.IsAuthenticated,) def get_object(self, id): obj = Account.objects.get(id=id) return obj def update(self, request, *args, **kwargs): self.object = self.get_object() serializer = self.get_serializer(data=request.data) if serializer.is_valid(): # Check old password if not self.object.check_password(serializer.data.get("old_password")): return Response({"old_password": ["Wrong … -
Save coordinates from Folium map to Django
I want to make a web application that let user create notes about different places. Is there a way to save coordinates from the folium map to the Django database, SQLite 3 for example? -
Django: Slow query set to retrieve the order in which the specified tags are mostly included
I would like to get the so-called similar posts, but for some reason the following query set is For some reason, the following query set takes a long time. (500-1000ms) What we are doing below is trying to filter by tags associated with a particular object and retrieve articles in order of the number of tags included. Removing annotate and order_by improves the speed but still takes about 200ms. tag_pks = Video.objects.get(pk=video_pk).tags.values_list("pk") Video.objects.annotate(n=Count("pk")) .exclude(pk=video_pk) .filter(tags__in=tag_pks) .order_by("-n") QUERY PLAN ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Limit (cost=1059.82..1059.87 rows=20 width=24) (actual time=461.401..461.407 rows=20 loops=1) -> Sort (cost=1059.82..1063.43 rows=1444 width=24) (actual time=461.400..461.404 rows=20 loops=1) Sort Key: (count(videos_video.id)) DESC Sort Method: top-N heapsort Memory: 26kB -> HashAggregate (cost=1006.95..1021.39 rows=1444 width=24) (actual time=385.859..445.844 rows=144784 loops=1) Group Key: videos_video.id Batches: 5 Memory Usage: 4145kB Disk Usage: 7000kB -> Nested Loop (cost=39.20..999.73 rows=1444 width=16) (actual time=0.076..330.037 rows=150442 loops=1) -> Nested Loop (cost=38.78..354.85 rows=1444 width=16) (actual time=0.059..48.867 rows=150445 loops=1) -> HashAggregate (cost=38.35..38.41 rows=6 width=32) (actual time=0.041..0.046 rows=3 loops=1) Group Key: u0.id Batches: 1 Memory Usage: 24kB -> Nested Loop (cost=0.71..38.33 rows=6 width=32) (actual time=0.032..0.039 rows=3 loops=1) -> Index Only Scan using videos_video_tags_video_id_tag_id_f8d6ba70_uniq on videos_video_tags u1 (cost=0.43..4.53 rows=6 width=16) (actual time=0.015..0.016 rows=3 loops=1) Index Cond: (video_id = '9af2f701-6272-4714-b99f-afe5e4deb741'::uuid) Heap Fetches: 0 -> Index Only … -
django 4.0 - can't login with registered user
Here is the django shell output: >>> for user in User.objects.all(): ... print(user.username, user.password, len(user.password)) ... ll_admin pbkdf2_sha256$320000$zm6RcAswZJR6B7uXaCVNVd$hRs9nZKWBPpfemhC2yL16XE0wLCRa4Z0dlbUATywleA= 88 ams 1243 4 who 1243 4 whos 1243 4 whosa 1243 4 maksd 1243 4 1243 1243 4 abcde 12345 5 ids 1243 4 amsfd 1234567 7 cancal 1111 4 >>> Here is the login view code: def user_login(request): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return HttpResponseRedirect(reverse('homepage:index')) else: message = "User doesn't exist or password is incorrect." + "( " + username + ", " + password + " )" else: message = '' form = UserForm() context = {"form": form, "message": message} return render(request, 'users/login.html', context) I sign in with ams, 1243 for example, it shows: https://imgur.com/a/XmJr1Aj I checked the password and username and they match. So kind of feel confused right now. Thanks for your help! -
How do I create , test (and if possible deploy) a django project using only an android 10 device?
How do I create,test(and if possible deploy) a django project using only an android 10 device? -
expected str, bytes or os.PathLike object, not tuple django media file upload
I created a model and add a filefield in it and trying to add this model from admin panel but when I save it it shows me this error. This is emergency pls help me. Thanks -
Django Unit Test not executed
I'm still struggling with tests in Django. Now i've rewrite a test, but it's not executed, so i see no results when i run the test command. Is it because of the wrong test or i'm missing something? Thank you once again :) Models: class Lab(models.Model): lab_name = models.CharField(max_length=200) category = models.ForeignKey(Category, unique=True, null=True, on_delete=models.PROTECT) pub_date = models.DateTimeField('date published') lab_theory = models.TextField() def __str__(self): return self.lab_name class QuestionMultipleChoice(models.Model): lab = models.ForeignKey(Lab, on_delete=models.CASCADE) type = QuestionType.multiplechoice question = models.CharField(max_length=200,null=True) option1 = models.CharField(max_length=200,null=True) option2 = models.CharField(max_length=200,null=True) option3 = models.CharField(max_length=200,null=True) option4 = models.CharField(max_length=200,null=True) answer = models.IntegerField(max_length=200,null=True) def __str__(self): return self.question @property def html_name(self): return "q_mc_{}".format(self.pk) @property def correct_answer(self): correct_answer_number = int(self.answer) correct_answer = getattr(self, "option{}".format(correct_answer_number)) return correct_answer def check_answer(self, given): return self.correct_answer == given Test: def test_past_question(self): """ Questions with a pub_date in the past are displayed on the index page. """ past_date = date(1997, 3, 2) lab2 = Lab.objects.create(lab_name="test lab past question", pub_date=past_date, lab_theory="test lab past question") past_question = QuestionMultipleChoice.objects.create(lab=lab2, question='This is a test question', option1='1', option2='2', option3='3', option4='4', answer='1') response = self.client.get(reverse('labs:index')) print (response) self.assertEqual(str(past_question),'This is a test question') -
How to make reverse nested serialization when we have ManytoMany field in relation? using DRF
my data model is like ''' class Rack(models.Model): rack_id = models.CharField(primary_key=True,max_length=30, verbose_name="Rack Id") rack_set = models.ForeignKey(RackSet, on_delete=models.CASCADE, related_name='wh_rack_set', verbose_name="Rack Set") class Meta: db_table = "rw_rack" def __str__(self): return self.rack_name class RackBay(models.Model): bay_id = models.CharField(primary_key=True,max_length=30, verbose_name="Bay Id") rack = models.ForeignKey(Rack, on_delete=models.CASCADE, related_name='wh_rack', verbose_name="Rack") class Meta: db_table = "rw_bay" def __str__(self): return self.bay_name class RackShelf(models.Model): shelf_id = models.CharField(primary_key=True,max_length=50, verbose_name="Shelf Id") bay = models.ForeignKey(RackBay, on_delete=models.CASCADE, related_name='wh_rack_bay', verbose_name="Bay") class Meta: db_table ="rw_shelf" def __str__(self): return self.shelf_name class RackBin(models.Model): bin_id = models.CharField(primary_key=True,max_length=50, verbose_name="Bin Id") class Meta: db_table = "rw_bin" def __str__(self): return self.bin_name class CargoWarehouseSurvey(models.Model): job_id = models.ForeignKey(WarehouseJob, on_delete=models.CASCADE, null=True, related_name='inputted_job_order', verbose_name="Job Id") warehouse_locations = models.ManyToManyField(WarehouseCell, help_text='Assigned warehouse locations for current survey job.', related_name='warehouse_locations_set') rack_bin_locations = models.ManyToManyField(RackBin, help_text='Assigned rack_bin locations for current survey job.', related_name='rack_bin_locations_set') def __str__(self): return self.id class Meta: db_table = 'warehouses_survey' ordering = ['id'] ''' This is my data model, in CargoWarehouseSurvey has bins relation what ever the selected, i need to get bin belogs to which rack, bay, shelf, bin. like expected Response is "allotted_bins": [ { "rack_id": "A-1", "bays": [ { "bay_id": "B-1", "shelves": [ { "shelf_id": "S1", "bin_ids": [ "12343", "21232" ] }, { "shelf_id": "S2", "bin_ids": [ "43234", "42354" ] }, ] } ] } ] }