Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
I Disabled a method in a ViewSet (django-rest-framework) but Swagger keep showing it in the documentation
I Disabled a method in a ViewSet (Retrive and List), but swagger (Open API) keep showing it in the documentation. I tried this, based on this question: def list(self, request): response = {'message': 'List function is not offered in this path.'} return Response(response, status=status.HTTP_403_FORBIDDEN) But its still present the endpoint. -
Custom form field class with dynamic widget attributes
I often use Django form fields with various lengths. I would like to create a custom form field class MyFloatField with a dynamic widget attribute so I could set the max_width when defining each form field such as: quantity = MyFloatField(label='Quantity:', max_width='50px') price = MyFloatField(label='Price:', max_width='100px') I have already created a custom form field where the max_width is a constant. class MyFloatField(forms.FloatField): def widget_attrs(self, widget): attrs = super().widget_attrs(widget) attrs.setdefault("style", 'max-width: 50px') return attrs I assume that in order to make it dynamic (pass the value from field definition) I need to somehow get the argument max_width='100px' from the definition of the form field and pass it as a variable to the attrs.setdefault(). I have tried the following but I get a TypeError: __init__() got an unexpected keyword argument 'max_width' error. class MyFloatField(forms.FloatField): def widget_attrs(self, widget): my_max_width = kwargs['max_width'] attrs = super().widget_attrs(widget) attrs.setdefault("style", 'max-width: '+my_max_width) return attrs Any help would be greatly appreciated. -
Django Models Excel-Like relations
I want to achieve a relationship between two fields in Django models. I understand that the desired view can only be achieved with additional views.py and forms.py. However, I need to choose the right models beforehand. Relations In the image provided, the relationship between the "A-ID" and "Important for" fields is illustrated. When an "A-ID" is marked as "YES" the "Important for" field should be dynamically split based on the number of "A-ID" entries labeled as "Yes." Is a many-to-many field necessary here? Unfortunately, I haven't found a similar structure online. My Code in models.py so far class MyClass(models.Model): yes_no_choices = [ ('YE', 'YES'), ('NO', 'NO'), ] A_ID = models.PositiveIntegerField(null=True) Information = models.CharField(max_length=255, null=True) Importance = models.CharField( max_length=2, choices=yes_no_choices,) B_ID = models.PositiveIntegerField(null=True) Information_2 = models.CharField(max_length=255, null=True) Important_for = ? -
How to send custom unique id to back in the twilio webhook
I am sending mail using twilio 6.10.0 sdk, but I'm unable to send the custom key value which I'll get back in the twilio webhook. from_email = Email("contact@codingnap.com") to_email = To(email) subject = "Codingnap login" content = Content("text/plain", "OTP for login in codingnap is 548568") event_webhook_url = "https://webhook.site/342ff89d-fc5e-483f-a4b2-778ed144fb3f" mail = Mail(from_email, to_email, subject, content) mail.unique_args = { 'custom_key': 'unique_value' } mail.headers = smtpapi_header.json_string() response = self.sg.send(mail) Can someples give any way to send custom id to the sendgrid which I get back in the webhook -
How can I solve issues with constructing a Django view for a small project?
Issues constructing a small project namely with the view. It doesn't give me any results and by changing some lines of codes. At this moment I can't even go from my landingpage to the next view I constructed. I was wondering if someone can help me with this kind of problem. Under this block of text you can see the view I want to implement but I can't reach it through my landingpage anymore. On top of that i am not even sure that it will work and give me the output that i would like to have. class StructurerenView(generic.TemplateView): template_name = 'ssc/filter.html' success_url = '/Definieer_zoekopdracht/results/' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) infrastructuren = ['Zonnepanelen', 'BiomassaInstallaties', 'Windturbines', 'WaterkrachtInstallaties'] bedrijfstypes = ['Kleine onderneming', 'Middelgrote onderneming', 'Grote onderneming'] remaining_durations = ['1 jaar', '2 jaar', '3 jaar'] household_compositions = ['Samengesteld gezin', 'Alleenstaand', 'Alleenstaande ouder'] # Haal de filterresultaten op selected_infrastructuren = self.request.GET.getlist('infrastructure') selected_bedrijfstypes = self.request.GET.getlist('business_type') selected_klasse = self.request.GET.getlist('model_class') remaining_length = self.request.GET.get('remaining_duration') samenstelling = self.request.GET.get('household_composition') prosumenten = Prosument.objects.filter(infrastructuur__in=selected_infrastructuren) bedrijven = Bedrijf.objects.filter(type__in=selected_bedrijfstypes) huishoudens = Huishouden.objects.filter(samenstelling=samenstelling) contracts = Contract.objects.filter(producent__in=selected_klasse, einddatum__gte=remaining_length) context['infrastructures'] = infrastructuren context['business_types'] = bedrijfstypes context['remaining_durations'] = remaining_durations context['household_compositions'] = household_compositions context['selected_infrastructuren'] = selected_infrastructuren context['selected_bedrijfstypes'] = selected_bedrijfstypes context['selected_klasse'] = selected_klasse context['remaining_length'] = remaining_length context['samenstelling'] = … -
Why is the full_name field not being populated when customer submits payment form in Django and Stripe integration?
I'm having trouble retrieving the customer's name when they submit a payment form in my Django application. I'm using Django for the backend and Stripe for payment processing. The customer's name is not being saved in the database when the form is submitted. I have a 'add' view that handles the form submission and creates an order. Here's the relevant code: views.py: `from django.http.response import JsonResponse from django.shortcuts import render from basket.basket import Basket from .models import Order, OrderItem def add(request): basket = Basket(request) if request.POST.get('action') == 'post': order_key = request.POST.get('order_key') cust_name = request.POST.get('custName') # Get the custName value user_id = request.user.id baskettotal = basket.get_total_price() if Order.objects.filter(order_key=order_key).exists(): pass else: order = Order.objects.create(user_id=user_id, full_name=cust_name, address1='add1', address2='add2', total_paid=baskettotal, order_key=order_key) order_id = order.pk for item in basket: OrderItem.objects.create(order_id=order_id, product=item['product'], price=item['price'], quantity=item['qty']) response = JsonResponse({'success': 'Return something'}) return response ` The form submission is handled by the following JavaScript code: script.js: var stripe = Stripe(''); var elem = document.getElementById('submit'); clientsecret = elem.getAttribute('data-secret'); var elements = stripe.elements(); var style = { base: { color: "#000", lineHeight: '2.4', fontSize: '16px' } }; var card = elements.create("card", { style: style }); card.mount("#card-element"); card.on('change', function(event) { var displayError = document.getElementById('card-errors') if (event.error) { displayError.textContent = event.error.message; $('#card-errors').addClass('alert alert-info'); …