Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why is my form not being saved to my database?
Hi I'm developing a website for an online store using Django. I want to use Ajax to handle the view of my checkout form after it has been submitted. After the form is submitted, I want it to go to : return HttpResponseRedirect(reverse(str(next_page))+"?address_added=True") , i.e http://127.0.0.1:8000/checkout/?address_added=True But for some reason, it is not going there. Rather it's being going to http://127.0.0.1:8000/checkout/?csrfmiddlewaretoken=W4iXFaxwpdtbZLyVI0ov8Uw7KWOM8Ix5GcOQ4k3Ve65KPkJwPUKyBVcE1IjL3GHa&address=123+Main+Street&address2=&state=MA&country=USA&zipcode=55525&phone=%28877%29+314-0742&billing=on As a result, the form data is also not getting saved. I was thinking if it were because of the new version of Django. What I want to do is that after they submit the place order button, the form is going to be None, i.e disapper and then I would add a credit card form there for payment. But it is not happening. What is wrong here? Can anyone please help me out of this or is there a better way to do this? My forms.py: class UserAddressForm(forms.ModelForm): class Meta: model = UserAddress fields = ["address", "address", "address2", "state", "country", "zipcode", "phone", "billing"] My accounts.views.py: def add_user_address(request): try: next_page = request.GET.get("next") except: next_page = None if request.method == "POST": form = UserAddressForm(request.POST) if form.is_valid(): new_address = form.save(commit=False) new_address.user = request.user new_address.save() if next_page is not None: return HttpResponseRedirect(reverse(str(next_page))+"?address_added=True") … -
Celery task called three times, but the data supplied to the task does not change
I have a Document model with a FileField for uploading images, pdfs, etc., and ImageFields for eight different images sizes created from the single uploaded file. I convert the uploaded image into 8 different sizes using Pillow. I allow multiple file uploads in the DocumentAdmin, and in save_model I create a thumbnail and large image for display in the DocumentAdmin page, and then use a celery task (with redis) to create the other different image sizes in the background and save them to the Document model. My code creates the different images correctly, but I seem to have a strange situation in the celery task. The celery task uses the same code to create the different image sizes as the code used in save_model to create the thumb and large image. The relevant part of the save_model code: def save_model(self, request, obj, form, change): if form.is_valid(): if not change: # Uploading one or more images files = request.FILES.getlist('storage_file_name') if files: for f in files: original_file_name, extension = os.path.splitext(f.name) new_file_name = original_file_name + "." + settings.DEFAULT_IMAGE_EXTENSION obj2 = Document() # save the original file if extension.lower() == ".pdf": obj2.pdf_file = f else: obj2.storage_file_name = f save_document_images(obj2, new_file_name, image_file=f, rot_angle=0, thumbnail=True, xsmall=False, … -
how can be solved AttributeError: 'QuerySet' object has no attribute 'exits'.?
This error occurs while trying to signup I got this error when i tried to login the signup page which I have created. Exception Location: C:\Users\Sunil\PycharmProjects\PyShop\products\views.py in register, line 32 Python Executable: C:\Users\Sunil\PycharmProjects\PyShop\venv\Scripts\python.exe Python Version: 3.8.2 Python Path: ['C:\Users\Sunil\PycharmProjects\PyShop', 'C:\Users\Sunil\AppData\Local\Programs\Python\Python38-32\python38.zip', 'C:\Users\Sunil\AppData\Local\Programs\Python\Python38-32\DLLs', 'C:\Users\Sunil\AppData\Local\Programs\Python\Python38-32\lib', 'C:\Users\Sunil\AppData\Local\Programs\Python\Python38-32', 'C:\Users\Sunil\PycharmProjects\PyShop\venv', 'C:\Users\Sunil\PycharmProjects\PyShop\venv\lib\site-packages', 'C:\Users\Sunil\PycharmProjects\PyShop\venv\lib\site-packages\setuptools-40.8.0-py3.8.egg'] -
How to get location based Admin views in Django?
I am new to Django and I am working on online food ordering system. I am going to use Django for backend. I am not sure about how to show various admin views based on different restaurants suppose I have restaurants in 3 three cities A,B and C. How to implement different admin views for A,B and C so that each restaurant can view it's order in it's admin views. Also how to make driver view and how to separate delivery boy login and how to assign ordered to him. Also which API to use to detect location and assign order. Anyone know how to complete this project using Django? -
pre_save signal method being called after model's save method
I'm using pre_save signal for performing some functionality, but when I used print statements to print log, I found that my Model's save method is being called before the pre_save bound method, from what I know pre_save method should be called before, I'm posting my Part of my Code for reference: Models.py : class RedeemCode(models.Model): code = models.CharField(max_length=128) reward = models.ForeignKey(Reward, on_delete=models.CASCADE) is_active = models.BooleanField(default = True) class Meta: unique_together = ['code'] def save(self, **kwargs): print("In model save method") super().save(**kwargs) in Views.py my pre_save method: @receiver(pre_save,sender=RedeemCode) def send_noti(sender, instance, **kwargs): print("Pre_save Method called ----->",instance) When I add new values from admin panel , and submit it, The model's save method is called First it prints In model save method and later pre_save bound method is called, so the output is like: In model save method Pre_save Method called From my understanding shouldn't the pre_save bound method be called first and then save method of Model,and output should be like this : Pre_save Method called In model save method I don't understand what is happening , could anyone please explain why this is happening or If I'm doing something wrong , thanks in Advance:) -
Filtering code example optimization issue in Django Rest Framework (DRF) or Not
Recently I came up with the following code in DRF documentation for filtering the queryset in an APIListView, class PurchaseList(generics.ListAPIView): serializer_class = PurchaseSerializer def get_queryset(self): """ Optionally restricts the returned purchases to a given user, by filtering against a `username` query parameter in the URL. """ queryset = Purchase.objects.all() username = self.request.query_params.get('username', None) if username is not None: queryset = queryset.filter(purchaser__username=username) return queryset It seems if the above code snippet is written as follow, it will be more efficient, class PurchaseList(generics.ListAPIView): serializer_class = PurchaseSerializer def get_queryset(self): """ Optionally restricts the returned purchases to a given user, by filtering against a `username` query parameter in the URL. """ queryset = None username = self.request.query_params.get('username', None) if username is not None: queryset = queryset.filter(purchaser__username=username) else: queryset = Purchase.objects.all() return queryset Am wrong ? or am i miss something about Django ORM ? -
Alternative approach to retrieve the "self" value while using "queryset" instead of using "def get_queryset(self)"
Usual Approach def get_queryset(self): return Test.objects.values( 'test_id', 'test__title').annotate( Count('test_id'), count=Sum(Case(When(~Q(user=self.request.user), then='count'), default=0, output_field=IntegerField())) ).filter(test_id__count__gt=0) While using the above approach, columns sorting functionality is not working. But while using the below approach using queryset, sorting functionality is working but unable to get the self value, so I commented the line containing self. Current Approach queryset = Test.objects.values( 'test_id', 'test__title').annotate( Count('test_id'), #count=Sum(Case(When(~Q(user=self.request.user), then='count'), default=0, output_field=IntegerField())) ).filter(test_id__count__gt=0) As of now, I commented the line containing self ... #count=Sum(.... It would be helpful, if I able to retreive the self value while using queryset. Thanks in advance. -
Django template not rendering for category
i had created a function for category listing. which renders successfully if URL is '/admin/category/list/' but template extended template does not show for '/admin/category/' only shows base template. Here is function from views.py: def categoryList(request): q_name = request.GET.get('query','') c_name = request.GET.get('select_category','') hasform = request.GET.get('type','') if q_name: data = Category.objects.filter(Q(name__contains=q_name)) elif hasform: frmid =[] forms = FormModel.objects.all() for form in forms: frmid.append(form.category_id) data = Category.objects.filter(id__in=frmid,parent_id__isnull=True) print(data) else: data = Category.objects.filter(parent_id__isnull=True) if c_name: c_name = int(c_name) data = Category.objects.filter(id=c_name) paginator = Paginator(data, 10) page = request.GET.get('page', 1) try: data = paginator.page(page) except PageNotAnInteger: data = paginator.page(1) except EmptyPage: data = paginator.page(paginator.num_pages) all_category = Category.objects.filter(parent_id=None).order_by("name") return render(request,'admin/category/categorylist.html',{'categories':data, 'q_name' : q_name,'all_category':all_category,'c_name':c_name}) Here is urls.py: from django.urls import path from category import views app_name = "category" urlpatterns = [ path('list/',views.categoryList,name="categorylist"), ] -
TypeError: 'UniqueConstraint' object is not iterable in Django
When I set multiple unique fields with UniqueConstraint: class Meta: constraints = (models.UniqueConstraint(fields=['student', 'classroom', 'code'], name='student_classroom_code')) and run python manage.py makemigrations Raise this error: TypeError: 'UniqueConstraint' object is not iterable What is wrong with this? -
Processing events using Zappa and Django app
I'm trying to use Zappa to deploy a Django event-driven application that will process events based on SQS and Kinesis. I have the following as part of my zappa.settings file: "django_settings": "myproject.settings", "events": [ { "function": "myproject.processor.process_messages", "event_source": { "arn": "[ARN IS HERE]", "batch_size": 10, "enabled": true } } ] When an item is queued via SQS, I am getting the following error from the Lambda: ModuleNotFoundError: No module named 'myproject' Traceback (I also tried dropping the "myproject" from the path and use just "processor", but that resulted in a similar error) It appears as though the event-based code cannot be invoked if it is part of the Django project. Is this true? Thanks! -
Serving django media files in cpanel
When workin with django in localhost with debug=True media files are served correctly using MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' But when deployed on cPanel with debug=False media files are not displayed. I am displaying media files using: <img src="{{ demo.image.url }}" alt="-"> How to serve media files on cPanel? -
Django other apis are getting response only after the upload api is completed
we have a django server serving both mobile and front end(angular). The mobile application has a functionality where the user will upload files to the server. POST request with files as multipart/form data to http://api.example.com/api/upload. It typically takes 10-15 seconds for this api to complete and return a response. During this time if we access the web application, the requests wait for that upload from mobile to complete. Example: let us say there is a login page on my web app. I am uploading files from my mobile and then trying to login from the mobile app. The login request waits for that upload to complete. How can i overcome this situation or is there any work around? -
**extra_fields argument in Django
I'm trying to create a custom user model in Django using this article And there a model manager given in this article as : from django.contrib.auth.base_user import BaseUserManager from django.utils.translation import ugettext_lazy as _ class CustomUserManager(BaseUserManager): """ Custom user model manager where email is the unique identifiers for authentication instead of usernames. """ def create_user(self, email, password, **extra_fields): """ Create and save a User with the given email and password. """ if not email: raise ValueError(_('The Email must be set')) email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save() return user def create_superuser(self, email, password, **extra_fields): """ Create and save a SuperUser with the given email and password. """ extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_active', True) if extra_fields.get('is_staff') is not True: raise ValueError(_('Superuser must have is_staff=True.')) if extra_fields.get('is_superuser') is not True: raise ValueError(_('Superuser must have is_superuser=True.')) return self.create_user(email, password, **extra_fields) What I dont understand is **extra_fields passed as argument in the create_user and create_superuser function. What is **extra_fileds ??What is the purpose of it and what it is doing here?? Thanks in advance!! -
limit_choices_to with A or B logic
I've got a model named MyUser with a user_type field which can be of the following different user types USER_TYPE_STUDENT USER_TYPE_TEACHER USER_TYPE_DIRECTOR In one of the models, I've got the following field student = models.ForeignKey(MyUser, null=True, related_name='requests', limit_choices_to={'user_type': MyUser.USER_TYPE_STUDENT}, ...) As you can read, it uses limit_choices_to={'user_type': MyUser.USER_TYPE_STUDENT} Thing is, in another field (students_or_teachers), I would like to declare that field is limited to user_type USER_TYPE_STUDENT or USER_TYPE_TEACHER. How can that be done? -
Django generating inlineformset based on models not defined in inlineformset_factory
I have managed to get part way to the behavior I am aiming for. I have two questions: My approach seems to be quite convoluted and I am wondering if there is a better way In the current approach I manage to get the basic behavior I am looking for however if the form is invalid I lose the initial values in the reception inlineformset when the form is re-displayed I have four models that are related to one another in a purchase process: Order OrderLine Reception ReceptionLine Both the purchase order and it's child purchase order lines are generated via an inlineformset - this works just fine. When it comes to the recording a reception I am trying to get the reception inlineformset to generate the initial receptionlines based on whatever was entered as purchase order lines. The status of the reception is recorded in the purchase order line via signals. models.py class Order(models.Model): requestor = models.CharField(max_length=10) class OrderLine(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE) item = models.CharField(max_length=30) quantity_ordered = models.PositiveIntegerField() quantity_received = models.PositiveIntegerField(blank=True, default=0) quantity_remaining = models.PositiveIntegerField(blank=True, default=0) class Reception(models.Model): order = models.ForeignKey('purchase.Order', on_delete=models.SET_NULL, null=True) receiver = models.CharField(max_length=10) class ReceptionLine(models.Model): reception = models.ForeignKey(Reception, on_delete=models.CASCADE) order_line = models.ForeignKey('purchase.OrderLine', on_delete=models.SET_NULL, null=True) quantity … -
How to create microservices in django rest frame work
I am new to micro service development, trying to create micro service in django rest frame work. Any guidance to how to work with it. -
Reverse for 'actor_event' with arguments '('',)' not found. 1 pattern(s) tried: ['events/actor(?P<actor_slug>[^/]+)/events/$']
I'm not sure which part I wrote. I wrote a link to another app. I think it's correct. But it still says wrong. I want to link to another app. I'm in the actor app's information page. And on that page, There is event information. I want to click to see the event information. Which the event will be in the other app is the event app. urls.py in app Events urlpatterns = [ path("events/", EventListView.as_view(), name="eventlist"), path("events/<str:slug>/", EventDetailView.as_view(), name="event"), path( "actor<str:actor_slug>/events/", EventDetailView.as_view(), name="actor_event", ), ] template in app Actor <a href="{% url 'actor_event' actor.actor_slug %}"> -
Django ReCAPTCHA with Model Form
I have a ModelForm like so: # forms.py class UploadForm(forms.ModelForm): class Meta: model = Upload fields = ['email', 'title', 'language', 'file'] labels = { 'email': 'E-Mail', 'title': 'Video Title', 'file': 'Attach File' } I am trying to add ReCAPTCHA functionality like so: # forms.py from captcha.fields import ReCaptchaField class UploadForm(forms.ModelForm): captcha = ReCaptchaField() class Meta: model = Upload fields = ['email', 'title', 'language', 'file'] labels = { 'email': 'E-Mail', 'title': 'Video Title', 'file': 'Attach File' } However, whenever I view this form, there is no Captcha field, from what I suspect is Django only taking in the fields from the ModelForm. How do I tell Django to also add the Captcha field? Project settings for good measure NSTALLED_APPS = [ 'about.apps.AboutConfig', 'users.apps.UsersConfig', 'content.apps.ContentConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'crispy_forms', 'storages', 'captcha' ] # ReCAPTCHA for forms RECAPTCHA_PUBLIC_KEY = '*****' RECAPTCHA_PRIVATE_KEY = '***** -
Setting up a detail view in Django
I'm new to Django and learning about creating apps and projects. Recently I've set up a view and everything appears to be working but I'm wanting to set up a detailed view for each object. I'm getting the following error Invalid block tag on line 11: 'endblock', expected 'empty' or 'endfor'. Did you forget to register or load this tag? {% extends "layout.html" %} 2 {% block title %}{{course.title}}{% endblock %} 3 {% block content %} 4 <article> 5 <h2>{{course.title}}</h2> 6 {{ course.description }} 7 <section> 8 {% for step in course.step_set.all %} 9 <h3>{{ step.title }}</h3> 10 {{ step.description }} 11 {% endblock %} 12 </section> 13 </article> 14 {% endfor %} -
How to link one app detail page with a link redirect to another app detail page?
I'm new to Django. I have a question about link one app detail page with a link redirect to another app detail page. I have 2 apps. The first app I have to show all the singer's information. The second app is to display the singer's event information. And I want to When I choose to click to see the singer's information It will display information, music, videos, including events, and when I click on an event I would like it to be linked to on that event's details page on the second app. What should I do? I want to know which app should I create the URL? app singer : urls.py urlpatterns = [ path("singer", views.PlayerListView.as_view(), name="singers"), path("singer/<str:slug>", views.PlayerDetailView.as_view(), name="singer"), ] views.py class SingerDetailView(DetailView): model = Singer def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["event"] = Event.objects.filter(singer=self.object) return context singer_detail.html {% for events in event %} <div> <a href="..............................."> <img src="src="{% static "img/events.png" %}"> <p>{{ events .name }}<p> </a> /div> {% endfor %} When I click the link on the singer_datail page I want it to display information of Events I clicked on the event_detail page app event : urlpatterns = [ path("events/", EventListView.as_view(), name="eventlist"), path("events/<str:slug>/", EventDetailView.as_view(), name="event"), ] … -
How to create/implement messages in django for when user registration input data is invalid?
I have a form in django that inherits from UserCreationForm (the only addition is that it asks for an email by default as well). I have manually entered input html into the template instead of just using {{ form }} so I have more customization over how it looks. The form works fine and I can create users with it, the issue I have is I can't seem to be able to get messages to work for when user data input does not meet the required criteria (e.g passwords don't match, username already exists, etc.). Since I am not using {{ form }} those messages aren't coming through automatically. Is there a way I can easily bring in the default messages from the django form? Or if not how can I create my own messages. I've tried a few things like what I have below: EDIT: Maybe I should mention that my messages do come through and display in the HTML, but the conditionals I try to use don't work as intended. My django form: class CreateUserForm(UserCreationForm): class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] My view: def registerPage(request): form = CreateUserForm() if request.method == 'POST': form … -
Django ORM Filtering inside db functions returning multiple duplicate rows
I have to list all clients and annotate them total amount of loan and payments inside of one sql query. I tried it with next fragment of code: clients = Client.objects.all().order_by('fullname').annotate( loans_total=ArrayAgg( 'sales__loan', filter=Q(Q(sales__created__gte=start_date) & Q(sales__created__lte=end_date)) ), payments_total=ArrayAgg( Case( When(payments__amount_currency="SUM", then=F('payments__amount') / F('payments__rate')), default=F('payments__amount'), output_field=FloatField() ), distinct=True, filter=Q(payments__created__gte=start_date) & Q(payments__created__lte=end_date) ), ) but it returns multiple duplicated records of rows and result of their sum is multiplied by 30 in this case; -
Django Query Reversed StartsWith
I have a model that contains folder path , and I want to get directories which contains an exact path. This is my model : class Directory(models.Model): name = models.CharField(max_length=5) path=models.CharField(max_length=100) In this model; name field is allways somethng like this "A" or "ZDCF" Naming rule is simple : a uniqeu char by using least character ( A, B, ....Z, AA, AB...) Path names have two simple rules : Always finishes with a dot "." Sum of upperside paths "A.B." And this is what I want : I want to select all upperside directories that contains a specific directory path. I will try to explain with an Image : Lets say these circles are my directories. In this example I picked the 'D' named directory and want to get upper directories "C" , "B" and "A". I dont't want to get 'E' , 'F' , 'G' , 'H' and 'J' named directores. If I use this code : myDir = Directory.objects.get(name='D') listDir = Directory.objects.filter(path__startswith=myDir.path) listDir QuerySet will contains 'E' , 'F', 'G' , 'H' and 'J'. But I don't want them. And if I use this code : myDir = Directory.objects.get(name='D') listDir =[] for xDir in Directory.objects.all(): if myDir.path.startswith(xDir.path): listDir.append(xDir) … -
Inserting data in django
I have this code in views where data inserted V_insert_data = StudentsEnrollmentRecord( Student_Users=studentname,Old_Student=old,New_Student=new, Payment_Type=payment,ESC_Student=esc,Last_School_Attended=last,Address_OF_School_Attended=add, Education_Levels=educationlevel,School_Year=schoolyear,Courses=course,strands=strands,Student_Types=stype ) V_insert_data.save() studentenrolment = StudentsEnrollmentRecord.objects.filter(id=V_insert_data) return render(request, 'accounts/print.html', {"studentenrolment":studentenrolment} ) I don't know what is wrong with this code, can somebody help me to configure this ? I just want that after the record inserted I can get the id and print it to the another html. I received this error -
Asgi deployement to ubuntu using django, nginx, daphne always results in 502 Bad Gateway
I had a working django server and then after adding channels i had to use asgi and i did so by following this tutorial which didnt work then i referred to the official deployement documentation But no luck always 502 Bad Gateway supervisor config [program:project_name_asgi_daphne] directory=/home/ubuntu/Lamar/ command=/home/ubuntu/env/bin/daphne -u /home/ubuntu/Lamar/daphne.sock --root-path=/home/ubuntu/Lamar/ walidproject.asgi$[program:project_name_asgi_workers] command=/home/ubuntu/env/bin/python /home/ubuntu/Lamar/manage.py runworker process_name=asgi_worker%(process_num)s numprocs=1 environment=LANG=en_US.UTF-8,LC_ALL=en_US.UTF-8 autostart=true autorestart=true redirect_stderr=True stopasgroup=true nginx config upstream channels-backend { server 0.0.0.0:8000; } server { listen 80; server_name 35.178.143.19; location /static/ { autoindex on; alias /home/ubuntu/Lamar/main/static/; } location /media { autoindex on; alias /home/ubuntu/Lamar/media/; } location / { proxy_pass http://channels-backend; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; } }