Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
display image from django model to template using for loop
so i want to show the image of the product from the the Product model to the template in a table but the code below that i wrote shows the broken image sign at the image and does not work here is my code : in models.py class Product(models.Model): Name = models.CharField(max_length=700, null=True) Price = models.FloatField(null=True) Link = models.URLField(max_length=2000, null=True) Image = models.ImageField(null=True) in my views.py : from django.shortcuts import render, redirect from django.http import HttpResponse from .models import * def home(request): Products = Product.objects.all() context = {'products':Products} return render(request, 'Cam/main.html', context) in the template (the html file): <div class="container "> <table class="table table-hover"> <thead> <tr class="row"> <th class="col-md-1" >Name</th> <th class="col " >Picture</th> <th class="col-md-1" >Price</th> </tr> </thead> <tbody> {% for product in products %} <tr class="row"> <td class="col-md-1"> {{product.Name}} </td> <td class="col-md-1"><img id="IMG" src="{{product.Image.url}}" ></td> <td class="col-md-1"> {{product.Price}} </td> </tr> {% endfor %} -
Form ModelChoiceField to exclude object being edited
I hope I can articulate myself properly. I have a model for MerchantGroup which has a one to many relationship with Merchants. I've added a feature that allows two MerchantGroups to be merged together - this basically moves all the Merchants from the two groups into one group and deletes the empty group. Below is the forms.py, views.py and forms.py. To do this merge the user opens the Update view for a MerchantGroup, and selects another MerchantGroup to merge with. The problem I have is that the form field merge_merchantgroup = forms.ModelChoiceField(required=False, queryset=MerchantGroup.objects.all().order_by('name'), empty_label="Merge with") displays the MerchantGroup being updated as one of the groups that can be merdged with, allowing a user to try to merge a MerchantGroup with itself - which is obvious non-sense. I can't think of hor to exclude the existing MerchantGroup from the ModelChoiceField so that users can try to merge a MerchantGroup with itself. Views.py @login_required def merchantgroups_update(request, pk): merchant_group = get_object_or_404(MerchantGroup,pk=pk) if request.method == 'POST': form = MerchantGroupForm(request.POST) if form.is_valid(): if form.cleaned_data['merge_merchantgroup']: merchant_group.merge(form.cleaned_data['merge_merchantgroup']) else: merchant_group.ledger = form.cleaned_data['default_ledger'] merchant_group.name = form.cleaned_data['name'] merchant_group.save() return HttpResponseRedirect(reverse('monzo:merchantgroups_show_all')) else: initial = { 'default_ledger': merchant_group.ledger, 'name': merchant_group.name, } form = MerchantGroupForm(initial=initial) return render(request, 'monzo/merchantgroups_update.html', {'form': form, 'merchant_group': merchant_group,}) Models.py … -
Gunicorn with Django giving a problem with static files
Got a Django project named django_server. When I run python manage.py runserver the page shows up as expected Then, if I run gunicorn django_server.wsgi:application --bind 0.0.0.0:8000 The page shows without styling Checking the console, can see the following errors for both .css and .js files The resource from “http://0.0.0.0:8000/static/....css” was blocked due to MIME type (“text/html”) mismatch (X-Content-Type-Options: nosniff). In the terminal where the gunicorn command was executed, can read NOT FOUND: /static/rest_framework/css/bootstrap.min.css NOT FOUND: /static/rest_framework/css/bootstrap-tweaks.min.css ... In settings.py I mention BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR,'static') This is the folder structure Checked the permissions in static folder (ls -l)and they show as drwxrwxr-x 4 tiago tiago 4096 jun 2 15:49 static Checking the permissions in the files where the problem happens and Added also to settings.py import mimetypes mimetypes.add_type("text/css",".css",True) mimetypes.add_type("text/javascript",".js",True) But the error remains. -
Blank username in Django allauth
I use Django-allauth for registration and login, without any social options right now. I have 2 issues with one specific user that is able to register with a blank username and incorrect e-mail. How can I avoid this behaviour in the future? I've added a couple of additional restrictions, but I can't validate if they will work. ACCOUNT_USERNAME_MIN_LENGTH = 4 ACCOUNT_USERNAME_BLACKLIST = ['',] I assume that special characters are used. Unfortunately, I can't replicate this behaviour myself. -
Django : I have a problem with showing the number of comments
I want to display the number of comments on this post Django posts app models.py class posts(models.Model): post_title = models.CharField(max_length=40) post_imge = models.ImageField(default='post.jpg', upload_to='post_images') post_text = models.TextField() Django comments app models.py from posts.models import posts class comments(models.Model): post = models.ForeignKey(posts, on_delete=models.CASCADE) comment = models.CharField(max_length=100) Django comments app views.py from django.shortcuts import render from .models import comments def posts(request): posts= comments.objects.all() template = 'comments /posts.html' context = { 'tum_posts': posts, 'title': 'tum post sayfası', } return render(request, template, context) Templates posts.html {% for comment in tum_posts %} {{ comment.post.post_title}} {{ comment.post.post_imge}} {{ comment.post.post_text }} {{ comment.count}} # is not runing {% endfor %} {{ comment.count}} is not runing how to fix this Thanks... -
How to get columns from joined table in django ORM
Keeping the problem simple : Trying to Learn ORM. And now I am stuck with simple left join issue . So Lets start with basic model : class City(models.Model): city=models.CharField(max_length=30) pin_code = models.IntegerField(null=False) class State(models.Model) city = models.ForeignKey(City,on_delete=models.CASCADE) state = models.CharField(max_length=30) province = models.CharField(max_length=30) Now, I basically want to do : select c.pin_code from State s left join City c on s.city = c.city; The equivalent of above in ORM that I could grasp from the mighty World Wide Web is : State.objects.select_related('city') The above querset on looping through gives me only data from State Table . I dont get 'pin_code' column . I did all the search possible on the internet , but couldnt find any solution . -
Stripe payment integration, error: does not exist on type 'HTMLElement'
I am integrating Stripe in my Angular 8/Django 3 app. I am so close... Following this doc page Payment Stripe I have already: 1. Set up stripe 2. Created a PaymentIntent object and received the clientSecret key from Stripe API (done on the Django server side) 3. Collected card details by mounting the Stripe Elements to the correct DOM Its the last step #4 "Submitting Payment to Stripe" that I am caught up on. I am currently trying to submit the payment on the client side using the stripe.confirmCardPayment() method. However to do this you are supposed to include the clientSecret. Problem is when I try to do this as shown below I get the error Property 'client_secret' does not exist on type 'HTMLElement'. I am not sure how to pass the clientSecret to that method. I am thinking that I could do step#4 on the backend, but I read that this should be done on the frontend. If i did this I guess i would just essentially build my own form for the card and bind it to an angular value, and then send that to the backend? Any help is appreciated. checkout.component.ts import { Component, OnInit, ChangeDetectorRef,} from … -
Django why models.py class attributes not instance attributes
I am new to Django and Python, so any help to clarify my question would be much appreciated! In models.py, why the attributes are not instance attribute but class attribute. Because I think each of these attributes will be different for each model instance created, so they should be instance attribute. For example: # articles/models.py from django.db import models from django.urls import reverse class Article(models.Model): title = models.CharField(max_length=255) body = models.TextField() In the last 2 lines, the title and body I think should be self.title and self.body because they contain information specific to each model instance created, right? If created as a class attribute, all model instances would have the same title and body, which is wrong. -
Django: use of __lte for automatic publication of a post
I'm developing a blog and I'm using this filter for put online the posts automatically: geopost_filter = GeoPost.objects.filter(draft=False, publishing_date__lte=timezone.now()) This filter run in local but doesn't run in production. For put online the post that pass from "it will be published in future" to "it is now online" I must restart the server in production. Why happen this? I can change the post's status using the draft field without problem, both in local than in production. But it seams not possible to publish automatically a post if it is marked as future post. -
How to combine to models in Django view
How do i combine this two model in 1 queryset? class ScheduleOfPayment(models.Model): GradeLevel_Category= models.ForeignKey("gradelevel_category", on_delete=models.CASCADE,blank=True, null=True) Education_Levels = models.ForeignKey(EducationLevel, on_delete=models.CASCADE, blank=True, null=True) Semester = models.ForeignKey("semestral", related_name='+', on_delete=models.CASCADE,blank=True,null=True) Courses = models.ForeignKey(Course, on_delete=models.CASCADE,blank=True, null=True) Payment_Type = models.ForeignKey(PaymentType, on_delete=models.CASCADE, blank=True, null=True) Date = models.DateField(null=True,blank=True) Amount = models.IntegerField(null=True, blank=True) class StudentsEnrollmentRecord(models.Model): Student_Users = models.ForeignKey(StudentProfile, on_delete=models.CASCADE,null=True, blank=True) School_Year = models.ForeignKey(SchoolYear, on_delete=models.CASCADE, null=True, blank=True) Courses = models.ForeignKey(Course, on_delete=models.CASCADE, null=True, blank=True, verbose_name="Track") strands = models.ForeignKey("N_strand", on_delete=models.CASCADE, null=True, blank=True) Section = models.ForeignKey(Section, on_delete=models.CASCADE, null=True,blank=True) Payment_Type = models.ForeignKey(PaymentType, on_delete=models.CASCADE, null=True ,blank=True) Discount_Type = models.ForeignKey(Discount, on_delete=models.CASCADE, null=True,blank=True) Education_Levels = models.ForeignKey(EducationLevel,on_delete=models.CASCADE,blank=True,null=True) Semester = models.ForeignKey("semestral", on_delete=models.CASCADE,blank=True,null=True) I have this code in my views.py I just want to combine the (studentenrollment query) and (scheduleofpayment query) gradelevel = request.GET.get('gradelevel') semester = request.GET.get('semester') payment = request.GET.get('payment') studentenrollment = StudentsEnrollmentRecord.objects.filter(Education_Levels=gradelevel).filter(Semester =semester).filter(Payment_Type=payment) scheduleofpayment = ScheduleOfPayment.objects.filter(Education_Levels=gradelevel).filter(Payment_Type = payment).filter(Semester=semester) and in my html {% for obj **Combination of two queryset**%} {% endfor %} -
Why do errors occur when connecting celery to sending mail with passord_reset?
I am trying to connect celery task to send mail when resetting the password. I use django views (PasswordResetView). I created a form and inherited from PasswordResetForm. Overrided the send_mail method, which sends a message to e-mail class CustomResetPasswordForm(PasswordResetForm): email = forms.EmailField(widget=forms.EmailInput(attrs={'class': 'form_control'})) def send_mail(self, subject_template_name, email_template_name, context, from_email, to_email, html_email_template_name=None): send_email_for_reset_password.apply_async(args=[subject_template_name, email_template_name, context, from_email, to_email, html_email_template_name]) I put the send logic in task send_email_for_reset_password def send_email_for_reset_password(subject_template_name, email_template_name, context, from_email, to_email, html_email_template_name): """ Send a django.core.mail.EmailMultiAlternatives to `to_email`. """ subject = loader.render_to_string(subject_template_name, context) # Email subject *must not* contain newlines subject = ''.join(subject.splitlines()) body = loader.render_to_string(email_template_name, context) email_message = EmailMultiAlternatives(subject, body, from_email, [to_email]) if html_email_template_name is not None: html_email = loader.render_to_string(html_email_template_name, context) email_message.attach_alternative(html_email, 'text/html') email_message.send() But an error occurs EncodeError at /user/password_reset/ Object of type CustomUser is not JSON serializable Also I only tried email_message.send (), but the error is the same. What am I doing wrong? -
How to combine list and retrieve API views in Django rest framework
I am new to DRF, and was thinking of providing List and Retrieve functionality from a single view. I figured out generic views are the shortest and easiest to handle with, but there isn't any views that allow only list and retrieve functionalities. There is a ListCreateAPIView but I dont want any post data. I guess i can use a mixin, but don't know how. Maybe like this?: class PostView(generics.ListAPIView, mixins.RetrieveModelMixin): queryset = Post.objects.all() serializer_class =myserializer is that the right way? -
how to prevent user to update a post after 24 hours django
i want to prevent the user to update the post after 24 hours from the post date class Post(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title= models.CharField(max_length=50) post = models.TextField(max_length=400) date = models.DateTimeField(auto_now_add=True) edit = models.DateTimeField(auto_now=True) class PostForm(forms.ModelForm): class Meta: model = Post fields = '__all__' class PostUpdateView(LoginRequiredMixin,SuccessMessageMixin,UpdateView): model = Post form_class = PostForm success_message = "updated successfully" template_name = 'store/create.html' success_url = reverse_lazy('lists') def form_valid(self,form): return super().form_valid(form) i want to let the user only be able to update the post before 24 hours during the Post date thanks -
How to filter the category in Django properly?
I have categories named 'person' in my Django Blog. In my blog, Each post(article) has 1 ~ multiple categories and when I click 1 of those categories, it will show all the posts under that category. However, for some categories especially which has only English Alphabet like 'Steve', shows the same post multiple times. I think using objects.filter has some problem with filtering it but am not sure what exactly the problem is. Do you have any solution for this issue? the below are my codes. models.py class Category(models.Model): person = models.CharField(max_length=20) description = models.TextField() slug = models.SlugField() def __str__(self): return self.person views.py def blog_category(request, category): posts = Post.objects.filter(categories__person__contains=category).order_by( "-created_on" ) context = {"category": category, "posts": posts} return render(request, "blog_category.html", context) -
local variable 'context' referenced before assignment in django
from django.shortcuts import render from main import (models,forms) from django.http import HttpResponseRedirect Create your views here. def index(request): return render (request, 'index.txt') def about(request): return render (request, 'about.txt') def contact(request): contactform = forms.ContactForm() if request.method == "POST": contactform = forms.ContactForm(request.POST) if contactform.is_valid(): contact = contactform.save() return HttpResponseRedirect('/contact') context = { "contactform" : contactform } return render(request, 'contact.txt', context) def post(request): return render (request, 'post.txt') -
Can Django-apps be treated and used as Microservices?
I theoretically know the concept of microservices and know and use the Django-apps. So, Django-apps are there for SOC(separation of concerns) by modularization. And the microservice idea is to bring scalability by breaking whole system into a number of independent systems. So, my confusion and question are Can we treat and make Django-apps as microservices? Or separate projects must be created for that, so as to handle the difference in database and server-deployment?. I hope I have made my question clear. Thanks -
Django Channels Routing with Mulitiple ProtocolTypeRouter
I have 2 different django routings, where one is used along withAuthMiddlewareStack and the other would work with unauthenticated. How do I define both the conditions for auth and unauth consumer URLs: something like this : from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter from channels.security.websocket import OriginValidator import chat.routing import dsock.routing application = ProtocolTypeRouter({ 'websocket': OriginValidator( AuthMiddlewareStack( URLRouter( auth.routing.websocket_urlpatterns ) ), ['http://127.0.0.1:8080','localhost','127.0.0.1','dflaws.io'], #https://channels.readthedocs.io/en/latest/topics/security.html ), 'websocket-unauth': URLRouter( un_auth.routing.websocket_urlpatterns ) }) -
Django App Not Working After Deployment to heroku
The App is A Blog Post App That is Working fine Locally But After I Deployed It To Heroku, The App Cannot run. I did more Than a week trying to fix it through the views and models with no success. This Is The Error When Trying To Open The App This My Views.py This The Models.py 1/2 The Models.py 2/2 -
from.is_valid() returns false
I want to save customer entry in my database. I have created a model form and trying to save it. but its not working. Where is the problem for this ? my models.py class Customer(models.Model): name = models.CharField(max_length=200, null=True) phone = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200, null=True) def __str__(self): return self.name my forms.py class CustomerEntryForm(ModelForm): class Meta: model = Customer fields = ['name', 'phone', 'email'] my views.py def customer_entry(request): if request.method == 'POST': form = CustomerEntryForm(request.POST) print(form.is_valid()) context = {'form': form} return render(request, 'accounts/entry.html', context) my urls.py urlpatterns = [ path('', views.customer_entry, name="entry"), path('register/', views.registerPage, name="register"), path('login/', views.loginPage, name="login"), path('logout/', views.logoutUser, name="logout"), path('home/', views.home, name="home"), ] my template <form method="POST" action="{% url 'entry' %}"> {% csrf_token %} <label for="">Name</label><br> <div class="input-group mb-3"> <input type="text" name="name" class="form-control"> </div> <label for="">Phone</label><br> <div class="input-group mb-2"> <input type="text" name="phone" class="form-control" > </div> <label for="">Email</label><br> <div class="input-group mb-2"> <input type="text" name="phone" class="form-control" > </div> <input class="btn login_btn" type="submit" value="save"> </form> -
how to get the values from manytomanyfield of another model in django
There are two models:Client and Event that is used.So Is there any way like i can access and save values in client_members that take only those values that are selected in Client objects. class Client(models.Model): company_name = models.CharField(_("Company name"), max_length=255) members = models.ManyToManyField(to=User,limit_choices_to={"is_staff":True}, blank=True) class Event(models.Model): title = models.CharField(_("Title"), max_length=255) client_members = models.ManyToManyField(to=User, limit_choices_to={"is_staff":False, "is_superuser":False}, related_name='%(class)s_clientmembers') -
Python 'different_locale' bad locale conversion
conditions = [] for i in range(1, 13): with different_locale('lt_LT'): conditions.append(calendar.month_name[i]) Trying to get all months in my native "Lithuanian" language. Result of the code : ['sausis', 'vasaris', 'kovas', 'balandis', 'geguþë', 'birþelis', 'liepa', 'rugpjûtis', 'rugsëjis', 'spalis', 'lapkritis', 'gruodis'] expected result: ['sausis', 'vasaris', 'kovas', 'balandis', 'gegužė', 'birželis', 'liepa', 'rugpjūtis', 'rugsėjis', 'spalis', 'lapkritis', 'gruodis'] Also tried "lt_LT.UTF-8" but got these results : 'gegužÄ\x97', 'birželis' Any ideas why? -
Object of type timedelta is not JSON serializable while using django-celery-beat
This is my first attempt with the celery so there might be some issues. Here I want to create Task Object every 1 minutes in the database so I used django-celery-beat. I want to use custom scheduler class later so for this purpose I used the django-celery-beat package. But I am not getting the results. I used the django form to create the TaskModel object and write a task in tasks.py to run the view every 1 minutes. But it throws this error Exception Type: EncodeError Exception Value: Object of type timedelta is not JSON serializable I started celery in one console with the command $ celery -A proj beat -l info --scheduler django_celery_beat.schedulers:DatabaseScheduler and started django server in another console with command py manage.py runserver settings.py CELERY_BROKER_URL = 'amqp://localhost' CELERY_BEAT_SCHEDULE = { 'task-first': { 'task': 'scheduler.tasks.create_task', 'schedule': timedelta(minutes=1) }, celery.py from __future__ import absolute_import, unicode_literals import os from celery import Celery # set the default Django settings module for the 'celery' program. from django.conf import settings os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'celery_demo.settings') app = Celery('celery_demo') # Using a string here means the worker doesn't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # … -
'NoneType' object is not iterable - issue with context in Django
I have this models.py: class dateEvent(models.Model): venue = models.ForeignKey(Venue, on_delete=models.CASCADE) event = models.ForeignKey('Event', on_delete=models.CASCADE) start_date_time = models.DateTimeField(auto_now=False, auto_now_add=False) def __str__(self): return "%s" % (self.start_date_time) This is my context_processors.py: def events(request): return { 'next_events': dateEvent.objects.all(), } which is registered in my settings.py: 'OPTIONS': { 'context_processors': [ 'nms_app.context_processors.events' I'm getting TypeError at / 'NoneType' object is not iterable Exception Location: /home/luca/python_ve/lib/python3.8/site-packages/django/template/context.py in bind_template, line 246 /usr/local/lib/python3.8/contextlib.py in __enter__ return next(self.gen) … ▼ Local vars Variable Value self <contextlib._GeneratorContextManager object at 0x7fe90a3e7a90> when visiting any page of my website, and I can't understand why. Can someone help me finding the culprit? I can't see why dateEvent is NoneType; it is populated with valid data. -
Django Models with both same and unique fields
I am working on an inventory management system and am looking to see if I can simplify and reduce the amount of hard coding. This is completely a conceptional question. Say I have two products: Clothing Shoes They share mostly the same fields: Style-ID Brand Name Size They also have some unique fields: Clothing Clothing Category Shoes Shoe Width And some fields which they share, but would have different choices: Age ("Adult", "Children", "Infant" for clothing. "Adult", "GS", "PS", "TS" for shoes) Currently I have two models: "ShoeProduct" and "ClothingProduct", but this seems redundant as they could conceivably share the same datatable and are certainly going to be used in the same functions and manipulated in the same ways. Is there a more efficient way of going about this? (My first thought is one Product model and then field kwargs for the unique fields, but I can't figure out if this is possible in django.) And to clarify, the base case vanilla use for these models is the user would enter data into an html form and once submitted would save this model to the database. Then, as purchase and sales data are fed to the server via various api's, … -
Problem with rq background jobs in Django Heroku
I have Django app which makes lots of different analysis Here is the structure of the view: def analysis(request): making analysis 1 ... making analysis 2 ... making analysis 3 ... ........ making analysis 50 ... return render(request, 'checkapp/shots.html', var) The problem is that all these analysis takes about 1-2 minutes. While development I tested my app locally and it is working fine there. But when I deployed it on Heroku, it turned out, that heroku has 30 sec timeout limit. I was told to use background jobs. I used python RQ. Now the code is def analysis(request): task_1 = q.enqueue(function-1) time.sleep(2) task_1_res = task_fb.result task_2 = q.enqueue(function-2) time.sleep(2) task_2_res = task_3.result task_3 = q.enqueue(function-3) time.sleep(2) task_3_res = task_3.result ..... task_50 = q.enqueue(function-50) time.sleep(2) task_50_res = task_50.result return render(request, 'checkapp/shots.html', var) But I still have the same problem. I have Request timeout error...