Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django sends error report showing {% elif tag%} line
{% if category %} {% with posts=category.blogpost_set.all %} {% for post in posts %} {% include 'blog/compenent/_post.html' %} {% endfor %} {% elif tag %} {% with posts=tag.blogpost_set.all %} {% for post in posts %} {% include 'blog/compenent/_post.html' %} {% endfor %} {% endwith %} {% endif %} message :emplateSyntaxError: Invalid block tag on line 20: 'elif', expected 'endwith'. Did you forget to register or load this tag? -
Fetching nested data to reactjs
How can I fetch this nested data and display in Reactjs [ { "pk_id": "HTR4q", "name": " Contagious Bovine Pleuropneumonia(CBPP)", "species": "cattle", "language": "en-uk", "translations": { "en-uk": { "subcategory": "Diseases with respiratory/breathing signs", "subcategory_desc": "Diseases described in this section are those that have respiratory/breathing signs as the main indication of illness. These include Contagious Bovine Pleuropneumonia and East Coast fever.", "name": "Contagious Bovine Pleuropneumonia (CBPP)", "local_names": "Somali Berfur, Sambab\r\nBorana Sombes\r\nRendille Argab Looyo\r\nSamburu Lkipei, Loonkishu\r\nTurkana Loukoi Angaatuk\r\nGabra Sombes", "other_livestock_affected": "It affects cattle only.", "transmission": "Susceptible cattle become infected by inhalation of droplets from an affected animal. Urine droplets from a sick animal can also transmit the disease. Transmission can occur even if a healthy animal is between 20 to 200 metres away from an infected one.", "distribution": "", "number_affected": "In unexposed populations, up to 100% are affected. In areas where the disease is common, 10–60% of the animals are affected.", "death_rate": "In unexposed populations, the disease can kill more than 50% of the animals. In areas where the disease is common, less than 10% of the– animals die from the disease.", "predisposing_factors": "Occurs in all seasons\r\nLivestock movement – mixing of herds at watering points and on grazing fields\r\nPresence of susceptible animals\r\nSub … -
Not redirecting to homepage in django
I Have a problem in redirecting in django: code:- def search(requests): return HttpResponse("<a href="{% url 'home' %}">home</a>") but it is showing error:- Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/search/%7B%25%20url%20''%20%25%7D Using the URLconf defined in example.urls, Django tried these URL patterns, in this order: admin/ [name='home'] search/ [name='search'] I was expecting it will redirect to homepage but..... -
django sending file to another server using threads
"I am sending file to another server using request.post . For reducing the time i am using the daemon thread. I am not doing any operation on the file but still getting ValueError: I/O operation on closed file. " class UploadDocument(APIView): permission_classes = ([DeviceDocumentLimitAuth]) def post(self, request): try: notebookId=request.data.get('notebookId') file= request.FILES['file'] notebook = get_single_notebook_sercive(notebookId) file_name = request.data.get('file').name upload_file = request.FILES.getlist('file') upload_file_link=upload_file[0] daemon = Thread(target=uploadDocument_service, daemon=True, name='Monitor',args=(file, notebookId, file_name, upload_file_link)) daemon.start() return success(message="successfully uploaded the document", response_data={'data': "ingestion in progress"}) except Exception as err: return error(message=str(err)) def uploadDocument_service(file,notebookId,file_name,upload_file_link): source_response = requests.post(create_source_api, data={ 'notebook_id':notebookId, 'source_type': 'PDF' }, files={'file': file}) print('made the request',source_response.status_code,source_response.json()) if source_response: result = source_response.json()['result'] source = result['source'] sourceId = source['source_id'] document = create_document_model( file_name=file_name,upload_file_link=upload_file_link,notebookId=notebookId, sourceId=sourceId) -
some objects of ForeignKey not display in dropdown form
some of objects of Foreign Key in model skipped to show! report = models.ForeignKey( Report, on_delete=models.SET_NULL, verbose_name="انتخاب پرونده" ,related_name='report', null=True) skipped objects with id 591 , 592 and 599 !!! and not display in drop down list to select them! -
I am trying to block submit form. any advice?
HTML Forms First name: Last name: submit with button submit with button not blocked becquse id blockfor; already used above If you click the "Submit" button, the form-data will be sent to a page called "/action_page.php". document.getElementById("blockform").addEventListener("click", function(event){ event.preventDefault() }); is that correct? I am not sure it is the best way -
How can i iterate the blog contents and display properly in django
i have one blog page here im trying to implement if i click the blog title or readmore link it will be redirect and display the detailed contents of the blogs Model class Blog(models.Model): title = models.CharField(max_length=200) content = RichTextField() posted_by = models.CharField(max_length=100) image = models.ImageField(upload_to='media/blogs') posted_date = models.DateField(auto_now_add=True) slug = models.SlugField(default='', max_length=500, null=True, blank=True) def __str__(self) : return self.title def get_absolute_url(self): from django.urls import reverse return reverse("blog_detail", kwargs={'slug': self.slug}) class Meta: db_table = "core_Blog" def create_slug(instance, new_slug=None): slug = slugify(instance.title) if new_slug is not None: slug = new_slug qs = Blog.objects.filter(slug=slug).order_by('-id') exists = qs.exists() if exists: new_slug = "%s-%s" % (slug, qs.first().id) return create_slug(instance, new_slug=new_slug) return slug def pre_save_post_receiver(sender, instance, *args, **kwargs): if not instance.slug: instance.slug = create_slug(instance) pre_save.connect(pre_save_post_receiver, Blog) View def BlogView(request): blog = Blog.objects.all() context ={ 'blog' : blog } return render(request, 'main/blog.html', context) def BlogDetail(request,slug): blog = Blog.objects.filter(slug = slug) if blog.exists(): blog = Blog.objects.get(slug = slug) else: return redirect('404') context = { 'blog' : blog, } return render(request, 'main/blog_detail.html', context) HTML for blog page {% for i in blog %} <div class="col-xl-6" style="height: 500px;"> <div class="single-smblog mb-30"> <div class="smblog-thum"> <div class="blog-image w-img"> <a href="blog-details.html"><img src="{{i.image}}" height="180px" alt=""></a> </div> <div class="blog-tag blog-tag-2"> <a href="blog.html">Food Beverage</a> </div> … -
Roles in django models
I have forgot Django and i was trying to write a model that will have 3 roles, staff individual and business. can someone review my code? And can i make the code a bit cleaner? lass Role(models.Model): STAFF= 'staff' INDIVIDUAL = 'individual' BUSINESS = 'business' ROLL_CHOICES =( (STAFF, 'staff'), (INDIVIDUAL, 'Individual'), (BUSINESS, 'Business'), ) Role= models.CharField(max_length=20,choices=ROLL_CHOICES) class Authuser(AbstractBaseUser): role = models.CharField(choices=ROLL_CHOICES, primary_key=True) email=models.CharField(primary_key=True,max_length=155) active=models.BooleanField(default=True) staff=models.BooleanField(default=False) admin=models.BooleanField(default=False) time_stamp=models.TimeField(auto_now_add=True) USERNAME_FIELD='email' REQUIRED_FIELDS=['email'] def get_first_name(self): return self.email def get_short_name(self): return self.email def __str__(self): return self.email def has_perm(self,perm,obj=None): return True def has_module_perms(self,app_label): return True @property def is_admin(self): "Is the user a admin member?" return self.admin @property def is_active(self): "Is the user active?" return self.active object=UserManager() class Staff(models.Model): user = models.OneToOneField(Authuser, on_delete=models.CASCADE) full_name = models.CharField(max_length=255) email = models.EmailField(unique=True) phone_number = models.CharField(max_length=20) staff = models.BooleanField(default=True) class Business(models.Model): Business_name=models.CharField(max_length=225) email=models.EmailField(unique=True) user = models.OneToOneField(Authuser, on_delete=models.CASCADE) staff=models.BooleanField(default=False) KYC_docs=forms.FileField() class Individual(models.Model): staff = models.BooleanField(default=False) user = models.OneToOneField(Authuser, on_delete= models.CASCADE) full_name=models.CharField(max_length=226) address = models.TextField() any input will be appreciated. -
How can I sync changes between my Django models and SQL database?
i have a django backend, in which i have a database, in sql, i wasnt using migrations earlier, but now i am planning to , i have created the initial migration files, and have fake migrated them for once, now i am ready to use it , when next time i change something in the models, or create some new model, but the catch is i made have difference in my current models and my database actual fields, so when next time i run migrations and migrate, it made change my database, for the fields that are different and i avoided editing them during the fake migrations that will make no point of my fake migrations, as well as affect my data as well so I need to know, if there is a way that i can do the following things effectievely To know that what are the current differences between by database, and my models To somehow sync these changes and make the db consistent, (I am trying to avoid the manual work as it is a very big database) I have fake migrated the inital migrations, so that it wont change my db, but I dont know on … -
I want dynamic dropdown like if user select the type as dog then five dogs dropdown should shown
I have two dropdown list first has two elements dogs and cat second has 5 subtype of type like 5 dogs or 5 breed of cat I want to create same functionality using forms.py but it giving me error like clean data isn't found.Error code: add_pet_form1: class add_pet_form1(forms.ModelForm): type=forms.ChoiceField() category=forms.ChoiceField() class Meta: model=Pet fields="__all__" widgets={ 'user':forms.Select(attrs={'class':'hidden-field'}), 'dob':forms.DateInput(attrs={'type':'date'}), 'vaccination_date':forms.DateInput(attrs={'type':'date'}) } def __init__(self, *args, **kwargs): super(add_pet_form1, self).__init__(*args, **kwargs) self.fields['category'].choices = self.get_category_choices() def get_category_choices(self): selected_type = self.cleaned_data.get('type') category_choices = [] if selected_type == 'dog': category_choices = [ ('labrador', 'Labrador'), ('poodle', 'Poodle'), ('bulldog', 'Bulldog'), ('beagle', 'Beagle'), ('german_shepherd', 'German Shepherd'), ] elif selected_type == 'cat': category_choices = [ ('siamese', 'Siamese'), ('persian', 'Persian'), ('maine_coon', 'Maine Coon'), ('ragdoll', 'Ragdoll'), ('sphynx', 'Sphynx'), ] return category_choices add_pet_view: @login_required def add_pet_view(request): form=add_pet_form1 if request.method=='POST': form=add_pet_form1(request.POST,request.FILES) if form.is_valid(): form.save() user=form.cleaned_data['user'] pet=form.cleaned_data['pet_name'] return redirect(f'/dashboard/?data={pet} of {user} is added successfully.') context={ 'form':form } return render(request,'admin_hub/add_pet.html',context) add_pet.html {%extends 'base.html'%} {%load crispy_forms_tags%} {%block title%} <title>Add Pet</title> {%endblock%} {%block css%} {%if default_user%} <style> .hidden-field { display: none; } label[for='id_user']{ display: none; } </style> {%endif%} {%endblock%} {%block content%} <div class="container"> <h1>Welcome..Please add Your Pets here</h1> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {{form.as_p}} <button type="submit" class="btn btn-primary">Submit</button> <a href={%if default_user %}"{% url 'all_pets' user.pk %}"{%else%}"{% url 'dashboard' %}"{%endif%}><button … -
django models errors in makemigrations
ERRORS: client_board.previous_jobs.description: (fields.E304) Reverse accessor 'active_jobs.previous_jobs_set' for 'client_board.previous_jobs.description' clashes with reverse accessor for 'client_board.previous_jobs.price'. HINT: Add or change a related_name argument to the definition for 'client_board.previous_jobs.description' or 'client_board.previous_jobs.price'. client_board.previous_jobs.price: (fields.E304) Reverse accessor 'active_jobs.previous_jobs_set' for 'client_board.previous_jobs.price' clashes with reverse accessor for 'client_board.previous_jobs.description'. HINT: Add or change a related_name argument to the definition for 'client_board.previous_jobs.price' or 'client_board.previous_jobs.description'. Error in makemigrations Python manage.py makemigrations not running. make migration of models. -
Django project with templates Internet Service Provider caching?
On a Django project using templates, I had the issue (rarely) that a user believed he was logged in as another user. He saw data from another user under /my-user-info where a template with data specific to the logged in request.user was served. I have checked everything around login and couldn't find a bug in the code that might cause this. Is it possible that somewhere along the way (in the realm of the Internet Service Provider?) /my-user-info is being cached for User B and then it's shown to User A? (The app is running on EC2 without CloudFront, so I don't think there's caching at the AWS level.) If this is not possible, do you have any ideas what might cause such a bug? Is it going to be something around logging in the wrong user by accident sometimes (so bug in the code)? It's hard for me to believe that Internet Service Provider caching is the reason, because that would seem to me like a crazy weakness of the Internet? Should I exclude this explanation and look for bugs in the code or is this possible? -
What steps are necessary to migrate a Django application within the same cPanel?
I have existing Python and Django Application hosted in cPanel, need to move application from one domain to another domain. in same cPanel. what are we need to change, example www.abcd.com to www.xyz.com Need information how to move the application. -
Got an unexpected eeror Blog' object has no attribute 'slug'
Blog' object has no attribute 'slug' here im trying to to if i click the blog link it will redirected the blog page so i created an tml page called blog.html and i click the readmore link it will redirected to the blogdetail page but i got an unexpected eror 'Blog' object has no attribute 'slug' Read More shows in this line also it shows an error in blog view return render(request, 'main/blog.html', context) Model class Blog(models.Model): title = models.CharField(max_length=200) content = RichTextField() posted_by = models.CharField(max_length=100) image = models.ImageField(upload_to='media/blogs') posted_date = models.DateField(auto_now_add=True) def __str__(self) : return self.title def get_absolute_url(self): from django.urls import reverse return reverse("blogs", kwargs={'slug': self.slug}) class Meta: db_table = "core_Blog" def create_slug(instance, new_slug=None): slug = slugify(instance.title) if new_slug is not None: slug = new_slug qs = Blog.objects.filter(slug=slug).order_by('-id') exists = qs.exists() if exists: new_slug = "%s-%s" % (slug, qs.first().id) return create_slug(instance, new_slug=new_slug) return slug def pre_save_post_receiver(sender, instance, *args, **kwargs): if not instance.slug: instance.slug = create_slug(instance) pre_save.connect(pre_save_post_receiver, Blog) View def BlogView(request): blog = Blog.objects.all() context ={ 'blog' : blog } return render(request, 'main/blog.html', context) def BlogDetail(request,slug): blog = Blog.objects.filter(slug = slug) if blog.exists(): blog = Blog.objects.get(slug = slug) else: return redirect('404') context = { 'blog' : blog, } return render(request, … -
django: request.POST is empty
I have the following rest API endpoint: def post(request, *args, **kwargs): print(request.POST) short_description = request.POST.get("short_description", "") long_description = request.POST.get("long_description", "") # rest of the code goes here when I call response = client.post("/foo/bar/api/v1/error/1", {"short_description": "hello", "long_description": "world", format='json') it gives me <QueryDict: {}> so both short_description and long_description is empty strings. How can I get that to pass the correct parameters in the POST? -
Is it possible to deploy a Django project with MongoDB to AWS?
How can I deploy a Django project that uses MongoDB to AWS? I have a project made using Django and have been using MongoDB and its Compass app and was wondering if you could deploy said project and database together to AWS. I'm not very familiar with AWS. -
Django staticfiles.W004 warning when using os.path.join
I'm getting this warning: ?: (staticfiles.W004) The directory '/home/chuox/Desktop/Projects/trade-bot/trade_bot/static' in the STATICFILES_DIRS setting does not exist. But only when I use this definition for the staticfiles dir BASE_DIR = Path(__file__).resolve().parent.parent STATICFILES_DIRS = [os.path.join(BASE_DIR, '/static')] If I use this instead STATICFILES_DIRS = ['/home/user/Desktop/Projects/project/project/project/static'] I have no issue. -
How to make the urls with and without a language prefix work in Django i18n?
This is my django-project as shown below. *I'm learning Translation with Django 4.2.1: django-project |-core | |-settings.py | └-urls.py |-app1 | |-models.py | |-admin.py | └-urls.py └-locale └-en └-LC_MESSAGES |-django.mo └-django.po And, this is core/settings.py which sets fr to LANGUAGE_CODE as a default language as shown below: # "core/settings.py" MIDDLEWARE = [ # ... 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', # ... ] # ... LANGUAGE_CODE = 'fr' # Here TIME_ZONE = 'UTC' USE_I18N = True USE_TZ = True from django.utils.translation import gettext_lazy as _ LANGUAGES = ( ('fr', _('Français')), ('en', _('Anglais')), ) LOCALE_PATHS = [ BASE_DIR / 'locale', ] And, this is app1/views.py which returns the default french word Bonjour from test view as shown below: # "app1/views.py" from django.http import HttpResponse from django.utils.translation import gettext as _ def test(request): # Here return HttpResponse(_("Bonjour")) And, this is app1/urls.py with the path set test view in urlpatterns as shown below: # "app1/urls.py" from django.urls import path from . import views app_name = "app1" urlpatterns = [ path('', views.test, name="test") # Here ] And, this is core/urls.py with i18n_patterns() set admin and app1 paths in urlpatterns as shown below: # "core/urls.py" from django.contrib import admin from django.urls import path, include from django.conf.urls.i18n import i18n_patterns … -
How to call custom logout function automatically in Django WITHOUT needing to send a request
I have a custom logout function, which updates the isCurrentlyActive value in the user's backend and logs them out: def logoutUser(request): try: user = request.user user_detail = UserDetail.objects.get(user = user) user_detail.isCurrentlyActive = False # set users activity to false user_detail.save() logout(request) return redirect('home', ) except: return redirect('home', ) I want to automatically log the user out after more than 10 minutes of inactivity. I implemented a custom middleware to do so, but this fails as a request such as a reload is needed in order for the function to be called. I've experimented with backend processes such as Celery and Redis but they all are overkill and don't necessarily work. I was wondering what the easiest way to accomplish this would be? I want to automatically call the custom logout function without the user needing to make a request to the server. Essentially, this should happen in the background. -
How to deploy django app using nginx+ waitress?
I want to deploy a django app on nginx. I am trying to deploy a using nginx + waitress. The app is getting deployed successfully but when I check the response header the server header has the value waitress instead of nginx.Response header Image. How to deploy it on nginx? -
Nginx and Waitress server setup in windows server
I have nginx running in win server 2019 at port 82. I also have django web application being served by waitress-server at port 8000. Both urls are working fine. I would like to setup nginx as a proxy with urls like my-server:82/dj/ which serves the waitress-server. i've modified the nginx.conf with below setup server { listen 82; # listen somename:8080; server_name localhost; location /dj/ { proxy_pass http://localhost:8000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } } After reloading nginx with "nginx -s reload", i've tried 'https://my-server:82/dj/ and i get "Not Found" "The requested resource was not found on this server" error. Can you help? -
Get the current and newly added m2m relation in a django model
I am using a manytomany relation on a model, while add(), I want to get the old and new instance of the relation. For that I am using pre_add and post_add m2m_changed signals. During post_add the value of the old instance is already modified to the saved instance. How do I store both of these instances. The code I am using right now. `class A: m2m = models.ManyToManyField(B, blank=True, related_name="m2m") def save_m2m(self, *args, **kwargs): action = kwargs.get("action", None) initial_instance = None if action == "pre_add": initial_instance = kwargs.get("instance") if action == "post_add": instance = kwargs.get("instance") # Operation involving initial_instance and instance def __init__(self, *args, **kwargs): super(A, self).__init__(*args, **kwargs) m2m_changed.connect(self.save_m2m, A.m2m.through)` -
How to get id from form in .html template in django python
I'm building a student management system and I need to fetch subject id in order to call a redirect method that takes in that subject id to enroll it. I don't use form.py to create a form (if there's a way to do it that way, I'm open to learning it), but I fetch all subjects and have user choose which one they want to enroll. Here is my code: This method is used to get .html form but I don't know how to retrieve data (in this case subject id) from the form when you click on submit: def enroll(request, id_user): subjects = Subjects.objects.all() if request.method == "GET": return render(request, 'enrollSubject.html', {'subjects': subjects}) if request.method == "POST": ----How to fetch anything from the .html above (in this case subject id)--- return redirect('../enroll/add/' + str(id_user) + '/' + str(id_subject)) This is my .html file: <form method="POST"> <select> {% for subject in subjects %} <option value="{{subject.id}}">{{subject.name}}</option> {% endfor %} </select> </form> Is there a way to fetch the value in <option value="{subject.id}">{subject.name}</option> Thanks in advance -
Django - Automatically Log User Out & Update Backend After Inactivity WITHOUT Needing To Send Request
I am creating a simple multiplayer system in Django. Part of this system is that I want to automatically update the isCurrentlyActive value in a model assosiated with the user, and then log them out. I implemented middleware as seen in this question. This works perfectly, however, it requires the user to reload the page or make some sort of request to the server in order to update. This doesn't work for me, as I want the backend to automatically update the User's backend data and log them out WITHOUT them needing to send a request to the server. Does anyone know how to do this? I saw implementations with Celery and django-auto-logout but they seemed too complicated and overkill. -
Getting issue in djano framework
On cmd prompt using python manage makemigrations after running it's showing no change detected problm Some resources show some issue but its already cleared by me like setting.py, makemigrations etc.. Everything I tried nothing change plz help me