Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to pass clickable image from one page to another html page in Django
I have a clickable image on my menu.html page which when clicked redirects to mycart.html. I want this same image on my mycart template **Below is my code for menu.html:** {%for count in item%} <div class="col-md-6 col-lg-4 menu-wrap"> <div class="heading-menu text-center ftco-animate"> <h3>{{count.supper}}</h3> </div> <div class="menus d-flex ftco-animate"> <a href="{% url 'mycart' %}"> <div style="background-image: url({{count.pic.url}});"></div> </a> <div class="text"> -
how to add custom method in django rest framework
i can handle the crud api of the model easily thanks to django rest frame work but what if i want to add the custom api to the booking model for example here is my code below : here is my serializer : from rest_framework import serializers from .models import Booking class BookingSerializer(serializers.ModelSerializer): class Meta: model = Booking fields =( 'user_id', 'computed_net_price', 'final_net_price', 'payable_price', 'booking_status', 'booking_status', 'guest_name', 'guest_last_name', 'guest_cellphone', 'guest_cellphone', 'guest_cellphone', 'operator_id', 'is_removed', ) and my view : from rest_framework import viewsets from .models import Booking from booking.serializers import BookingSerializer # Create your views here. class BookingView(viewsets.ModelViewSet): queryset = Booking.objects.all() serializer_class = BookingSerializer and my urls : from django.urls import path,include from . import views from rest_framework import routers router = routers.DefaultRouter() router.register('Booking',views.BookingView) router.register('BookingApi',views.BookingView) urlpatterns = [ #path('',include('facility.urls')) path('',include(router.urls)) ] so if i want to add the new api names bookingapi for example should i duplicate all thing in the same files??? or make new files the same name in the model or any thing else how can i achive it -
How can i update a page without reloading with Ajax and Django Rest Framework?
In my Django project, i'm trying to create a page where some data is uploaded in real time, without reloading the whole page. That data is retrieved from a database, so i created an API endpoint with Django Rest Framework, the problem is that i don't know how to go from here. I already know that, to update the page, i'll need to use Ajax. But i don't know how to create the Ajax part. I think that i need to add a POST request in my template, but that's all i know for now. Can someone give me some direction on where to go from here? Any advice is appreciated Basically the Ajax request should call the endpoint, which is http://127.0.0.1:8000/tst/, and update the data every X (something between 1 and 5 seconds). serializers.py class tstSerializer(serializers.ModelSerializer): class Meta: model = tst fields = ('ticker', 'Price', ) def create(self, validated_data): return tst.objects.create(**validated_data) views.py class tstList(generics.ListCreateAPIView): queryset = tst.objects.using('screener').all() serializer_class = tstSerializer class tstDetail(generics.RetrieveUpdateDestroyAPIView): queryset = tst.objects.using('screener').all() serializer_class = tstSerializer template.html <h3>Here will be a table with the data uploaded in real time..</h3> -
count and grouped by
I would like to count the number of fields (car_number) returned grouped by country. class CarViewSet(viewsets.ModelViewSet): queryset = car.objects.only('car_country').select_related('car_country') serializer_class = CarSerializer class CountrySerializer(serializers.ModelSerializer): class Meta: model = country fields = ('country_name',) class CarSerializer(serializers.ModelSerializer): car_country = CountrySerializer() class Meta: model = car fields = ('car_number','car_country',) The result I got now is as follows: [ { "car_number": "45678", "car_country": { "country_name": "Europe/UK" } }, { "car_number": "3333333", "car_country": { "country_name": "Europe / Netherlands" } }, { "car_number": "11111111111", "car_country": { "country_name": "Europe/UK" } } ] -
Django Rest Framework - Bad request
I'm trying to call an api endpoint on my Django project from my frontend. The endpoint is at the url /tst/. I need to retrieve data from that endpoint, in order to populate my page with that data. I'm using an ajax request for this, but i keep getting the error 400 - BAD REQUEST, but i don't know why this happens, since the api endpoint is at the right URL. function doPoll(){ $.post('http://localhost:8000/tst/', function(data) { console.log(data[0]); $('#data').text( data[0].data); setTimeout(doPoll, 10); }); } My endpoint's view: class tstList(generics.ListCreateAPIView): queryset = tst.objects.using('screener').all() serializer_class = tstSerializer -
Django: delete/update model only if respect the conditions
I am new in python/django and i need help for this situation: WeeklyCheck = start_Date >>> end_date - Week Active User Check the attendance in one of date in Week because that week is Active. User can delete/update that check that he made, but only if the week is Active. Then: Week = start_Date -> end_date - Week Not Active User now can not delete/update that check the attendance tha he made because the week is Not Active. models.py class WeeklyCheck(models.Model): start_date = models.DateField(blank=False, null=True, verbose_name='Start date') end_date = models.DateField(blank=False, null=True, verbose_name='End Date') active = models.BooleanField(default=True, verbose_name='Active?') def __str__(self): return '{} / {} to {} - {}'.format(self.department, self.start_date, self.end_date, self.active) class Attendance(models.Model): user = models.ForeignKey(User, related_name='attendance_user', on_delete=models.CASCADE) date = models.DateField(blank=False, null=True, verbose_name='Date') check = models.BooleanField(default=True, verbose_name='Check') def __str__(self): return '{} / {} / {}'.format(self.user, self.date, self.check) forms.py class WeeklyCheckForm(forms.ModelForm): class Meta: model = WeeklyCheck fields = [ 'start_date', 'end_date', 'enable', ] class AttendanceForm(forms.ModelForm): class Meta: model = Attendance fields = [ 'user', 'date', 'check', ] views.py def check_edit(request, pk=None, pkk=None): weeks = WeeklyCkeck.objects.all() user = get_object_or_404(User, id=pk) check = get_object_or_404(Attendance, id=pkk) form = AttendanceForm(request.POST or None, request.FILES or None, instance=check) if form.is_valid(): instance = form.save(commit=False) instance.save() return HttpResponseRedirect(reverse("check_list", kwargs={'pk': pk})) … -
AttributeError: 'HttpResponse' object has no attribute 'rendered_content'
i want to attach a pdf in mail (django python)and the function i have call on pdf_response variable is converting my html into pdf from email.mime.application import MIMEApplication from email.mime.multipart import MIMEMultipart msg = MIMEMultipart('related') attachment = msg.attach(pdf_response.rendered_content) attachment['Content-Disposition'] = 'attachment; filename="xyz.pdf"' msg.attach(attachment) -
How to connect plaid to stripe using django
I was using stripe in django but i am new for plaid . Now i want to connect plaid with my django app and than pay with plaid + stripe. I refer below document but i cant understand how to work document link: https://plaid.com/docs/stripe/ https://stripe.com/docs/ach#using-plaid I was test below code but than next what to do i don't know <button id='linkButton'>Open Plaid Link</button> <script src="https://cdn.plaid.com/link/v2/stable/link-initialize.js"></script> <script> var linkHandler = Plaid.create({ env: 'sandbox', clientName: 'Stripe/Plaid Test', key: '1bde1c39022bbcecaccde8cc92182d', product: ['auth'], selectAccount: true, onSuccess: function(public_token, metadata) { // Send the public_token and account ID to your app server. console.log('public_token: ' + public_token); console.log('account ID: ' + metadata.account_id); }, onExit: function(err, metadata) { // The user exited the Link flow. if (err != null) { // The user encountered a Plaid API error prior to exiting. } }, }); // Trigger the Link UI document.getElementById('linkButton').onclick = function() { linkHandler.open(); }; </script> -
I am newbie in programming. Can you please help me to dispatch this url in python?
I want to dispatch a url of type: /algorithms/algorithm_name/topic/ I am working on django. This is what I tried: url(r'^(?P<topic_name>[a-zA-Z a-zA-Z a-zA-Z]+)/$',views.topic,name='topic'), How to write the regex pattern for my url type? -
Best approach to building a student marks tracking system
Am trying to build a system in django which will allow me to track marks of students from various semesters in various subjects. I have sucessfully built the registration system and both Students and Teachers can register and login to the system. I want to be able to allow the teachers to enter marks students have secured in different examinations in different semesters. I want to have an easy and user friendly way that Teachers can enter marks and also allow students to be able to view their marks in the various tests and various papers over the semesters. In effect allowing them to monitor their progress in the courses they attend. I would appreciate any inputs on how I might approach this problem and implement it with django. Thank you all for your time -
Pip installation of pygdal with osx gdal binding fails
I'm trying to run a geoDjango project on OSX Mojave (10.14.5). Therefore I've installed the dependencies as suggested on the Django docs from kyngchaos (tried brew packages as well) Created my virtualenv which shows New python executable in /Users/ts/.virtualenvs/project_upstream/bin/python2.7 Also creating executable in /Users/ts/.virtualenvs/project_upstream/bin/python checked gdal with $ gdal-config --version 2.4.1 and tried to install pygdal with: pip install pygdal==2.4.1.* which fails with ERROR: Complete output from command /Users/ts/.virtualenvs/project_upstream/bin/python2.7 -u -c 'import setuptools, tokenize;__file__='"'"'/private/var/folders/j6/wr2vpjzn3698tdsng2j56d7m0000gn/T/pip-install-qTnsBS/pygdal/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record /private/var/folders/j6/wr2vpjzn3698tdsng2j56d7m0000gn/T/pip-record-vlffrN/install-record.txt --single-version-externally-managed --compile --install-headers /Users/ts/.virtualenvs/project_upstream/bin/../include/site/python2.7/pygdal: ERROR: running install running build running build_py creating build creating build/lib.macosx-10.14-x86_64-2.7 creating build/lib.macosx-10.14-x86_64-2.7/osgeo copying osgeo/gnm.py -> build/lib.macosx-10.14-x86_64-2.7/osgeo copying osgeo/__init__.py -> build/lib.macosx-10.14-x86_64-2.7/osgeo copying osgeo/gdalnumeric.py -> build/lib.macosx-10.14-x86_64-2.7/osgeo copying osgeo/osr.py -> build/lib.macosx-10.14-x86_64-2.7/osgeo copying osgeo/gdal.py -> build/lib.macosx-10.14-x86_64-2.7/osgeo copying osgeo/ogr.py -> build/lib.macosx-10.14-x86_64-2.7/osgeo copying osgeo/gdal_array.py -> build/lib.macosx-10.14-x86_64-2.7/osgeo copying osgeo/gdalconst.py -> build/lib.macosx-10.14-x86_64-2.7/osgeo running build_ext clang -fno-strict-aliasing -fno-common -dynamic -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk -I/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/usr/include -I/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/System/Library/Frameworks/Tk.framework/Versions/8.5/Headers -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -I/usr/local/Cellar/python@2/2.7.16/Frameworks/Python.framework/Versions/2.7/include/python2.7 -I/Users/ts/.virtualenvs/project_upstream/lib/python2.7/site-packages/numpy/core/include -I/Library/Frameworks/GDAL.framework/Versions/2.4/include/gdal -I/Library/Frameworks/GDAL.framework/Versions/2.4/include -c gdal_python_cxx11_test.cpp -o gdal_python_cxx11_test.o clang -fno-strict-aliasing -fno-common -dynamic -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk -I/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/usr/include -I/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/System/Library/Frameworks/Tk.framework/Versions/8.5/Headers -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -I/usr/local/Cellar/python@2/2.7.16/Frameworks/Python.framework/Versions/2.7/include/python2.7 -I/Users/ts/.virtualenvs/project_upstream/lib/python2.7/site-packages/numpy/core/include -I/Library/Frameworks/GDAL.framework/Versions/2.4/include/gdal -I/Library/Frameworks/GDAL.framework/Versions/2.4/include -c gdal_python_cxx11_test.cpp -o gdal_python_cxx11_test.o -std=c++11 building 'osgeo._gdal' extension creating build/temp.macosx-10.14-x86_64-2.7 creating build/temp.macosx-10.14-x86_64-2.7/extensions clang -fno-strict-aliasing -fno-common -dynamic -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk -I/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/usr/include -I/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/System/Library/Frameworks/Tk.framework/Versions/8.5/Headers -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -I/usr/local/Cellar/python@2/2.7.16/Frameworks/Python.framework/Versions/2.7/include/python2.7 … -
how to use django-ratelimit for graphene resolve
We cannot use django-ratelimit directly for graphql resolve method. Because the default decorator is get request from the first argument. -
Pass Django context to Ajax
I need to pass some data from Django to Ajax so the page will refresh every second. I've seen similar questions, for example this one, but it didn't helped me. The code on the Django side is following: @register.inclusion_tag('core/controller_data.html', name='controller_data') def controller_data(): current_controller_data = poll_controller() data = {'data': current_controller_data} return JsonResponse(data) In the template I have setInterval(function () { $.ajax({ url: "/", type: 'GET', data: {'check': true}, success: function (data) { console.log(data); } }); }, 1000); But instead of Django context, the html code of the template is being rendered in the console. Can you please help me? -
Saving Multiple Images in Form Wizard Django and ManyToMany Fields not Working
I am working on a project in Django that I have to use a Form Wizard. Part of the requirement is to save multiple images in one of the form steps, and to save a many to many field, which are not working as expected. Let me first share my code before explaining the problem. models.py from django.db import models from django.contrib.auth.models import User from location_field.models.plain import PlainLocationField from PIL import Image from slugify import slugify from django.utils.translation import gettext as _ from django.core.validators import MaxValueValidator, MinValueValidator from listing_admin_data.models import (Service, SubscriptionType, PropertySubCategory, PropertyFeatures, VehicleModel, VehicleBodyType, VehicleFuelType, VehicleColour, VehicleFeatures, BusinessAmenities, Currency, EventsType ) import datetime from django_google_maps.fields import AddressField, GeoLocationField def current_year(): return datetime.date.today().year def max_value_current_year(value): return MaxValueValidator(current_year())(value) class Listing(models.Model): listing_type_choices = [('P', 'Property'), ('V', 'Vehicle'), ('B', 'Business/Service'), ('E', 'Events')] listing_title = models.CharField(max_length=255) listing_type = models.CharField(choices=listing_type_choices, max_length=1, default='P') status = models.BooleanField(default=False) featured = models.BooleanField(default=False) city = models.CharField(max_length=255, blank=True) location = PlainLocationField(based_fields=['city'], zoom=7, blank=True) address = AddressField(max_length=100) geolocation = GeoLocationField(blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) expires_on = models.DateTimeField(auto_now=True) created_by = models.ForeignKey(User, on_delete=models.CASCADE, editable=False, null=True, blank=True ) listing_owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name='list_owner' ) def __str__(self): return self.listing_title class Meta: ordering = ['-created_at'] def get_image_filename(instance, filename): title = instance.listing.listing_title slug = slugify(title) … -
"how to fix "No module named 'core' in django"
"""ajax_pro1 URL Configuration The urlpatterns list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.2/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.conf.urls import url from core import views enter code here urlpatterns = [ url(enter code herer'^signup/$', views.SignUpView.as_view(), name='signup'), ] -
Django on Heroku: ModuleNotFoundError: No module named 'app_name'
I've been having some trouble getting my Django app with the django rest framework to deploy without errors to heroku. The strange thing is, there would be no issues in pushing and deploying to Heroku but would crash after deployment. Here is my file structure: Include/ man/ Procfile/ requirements.txt runtime.txt Scripts/ tcl/ webadvisorapi │ manage.py ├───src │ │ admin.py │ │ apps.py │ │ models.py │ │ serializers.py │ │ tests.py │ │ urls.py │ │ views.py │ │ __init__.py │ │ │ ├───management │ │ │ __init__.py │ │ │ │ │ └───commands │ │ runrequest.py │ │ __init__.py │ │ │ ├───scripts │ request.py │ __init__.py │ ├───static │ .keep │ ├───staticfiles └───webadvisorapi │ settings.py │ urls.py │ wsgi.py │ __init__.py │ ├───static │ .keep I have already ran this on my own machine and it worked just fine. Interestingly, my app could not be pushed and deployed to Heroku when I use any other path other than src.apps.SrcConfig in INSTALLED_APPS as it gives me the same ModuleNotFoundError. Besides that, I did get a successful deployment but the app crashed. I even cloned my project from heroku and ran my project locally and there was no issue. Here … -
Django formset: file upload does not work
I am using Django to build a help desk and I want to allow the client to upload multiple files when they submit a ticket. I am trying to do this by using a formset. I have found many questions related to a similar problem, but I still have not been able to get my form working. I will appreciate a pointer in the right direction. I have posted the relevant code below: # models.py class Ticket(models.Model): PRIORITY_CHOICES = ( (1, 'Critical'), (2, 'High'), (3, 'Normal'), (4, 'Low'), (5, 'Very Low'), ) STATUS_CHOICES = ( (1, 'Open'), (2, 'Reopened'), (3, 'Resolved'), (4, 'Closed'), (5, 'Duplicate'), ) ticket_number = models.CharField(max_length=50, blank=True, null=True, unique=True) client = models.ForeignKey(settings.AUTH_USER_MODEL, editable=True, on_delete=models.CASCADE, related_name="tickets") title = models.CharField("Summary", max_length=200, help_text='Provide a brief description of your request.') description = models.TextField(blank=True, help_text='Provide as much detail as possible to help us resolve this ticket as quickly as possible.') due_date = models.DateField(blank=True, null=True) assigned_to = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="assigned", blank=True, null=True, on_delete=models.CASCADE) priority = models.IntegerField(choices=PRIORITY_CHOICES, editable=True, default=3, help_text='Please select a priority carefully. If unsure, leave it as "Normal".', blank=True, null=True) status = models.IntegerField(choices=STATUS_CHOICES, editable=True, default=1, blank=True, null=True) closing_date = models.DateField(blank=True, null=True) closing_notes = models.TextField(blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) upload = models.FileField(upload_to='uploads/%Y/%m/%d/', … -
Django FactoryBoy Test creating nested object for a complex unit Test
I am trouble in writing a test-case... Note: My Test was worked nice once i create only a single post.. now i want to create a nested post: This is my current snippet that i am trying but failed: At first, see it, later i am explaining the problem from django.test import TestCase from django.urls import reverse from .. tests import CategoryFactory, ArticleFactory, AuthorFactory class TestSingleArticle(TestCase): def setUp(self): self.author = AuthorFactory() #create category self.category = CategoryFactory.create_batch( 4, name='my category' ) # create article self.article = ArticleFactory.create_batch( 4, category=self.category, author=self.author ) # Set the url self.url = reverse('article-single', args=[self.article.alias]) ####################### # Test Get Method ####################### def test_single_article_get(self): request = self.client.get(self.url) self.assertEqual('my category', request.data['category']) Please read these below carefully: Author will be one, I want to create 4 Category and create 4 Article with those 4 categories..., in each category, will be one article, total 4 categories. I tried much but i failed to create like this... Some people say I can achieve it with for loop but i couldnt do.. I also i want to pass the each article alias to self.url to request in my api end point... If you don't get above code, you can see my models: from … -
Why isn't there any tutorials on how to write your own django custom password reset
Search account by username or email for sending password reset link. You can request password reset 5 times a day . How to customize Django default reset password. I am Searching tutorials on YouTube and udemy. But no one is covering this topic. -
Save the data from a dynamic table to the backend using django
I am using django as my backend.I have a HTML Page which contains a dynamic table for the doctor to prescribe medicines to the patient.When a new row is added the name of the corresponding row also changes.How do I store all the rows with different names in the database in django? views.py for the HTML Page def prescription_form(request,id): book= Booking.objects.get(id=id) if request.method == 'GET': return render(request,'doc/prescription_form.html',{'book':book}) if request.method == 'POST': try: doc_name = request.POST['username'] patient_name = request.POST['PatientName'] weight = request.POST['Weight'] temp = request.POST['Temparature'] date = request.POST['datetime'] age = request.POST['age'] diagnosis = request.POST['Diagnosis'] remarks = request.POST['Remarks'] fees = request.POST['Fee'] med_name = request.POST['name0'] mor= request.POST['morning0'] afternoon = request.POST['afternoon0'] night = request.POST['night0'] food = request.POST['after_before0'] dose = request.POST['dose0'] days = request.POST['days0'] pres = Prescription() pres.Doctor_Name = doc_name pres.Patient_Name = patient_name pres.Weight = weight pres.Temperature = temp pres.Date = date pres.Age = age pres.Diagnosis = diagnosis pres.Remarks = remarks pres.Fees = fees pres.Medicine_Name = med_name pres.Morning =mor pres.Afternoon = afternoon pres.Night = night pres.After_Before_Lunch = food pres.Dose_ml = dose pres.Days = days pres.save() except Exception as e: return render(request,'prescription_form.html') messages.error(request,'Saved Successfully!', extra_tags='success') return render(request,'doc/prescription_form.html') HTML Page <table class="table table-bordered table-hover" id="tab_logic" style="font-size:12px;margin-right:100px;"> <thead> <tr > <th class="text-center" > # </th> <th class="text-center" > … -
Is it OK to use daphne as a production server in this situation?
I need to deploy a server with django rest framework, django-channels. It is used in-house and distributed for the Windows OS. It is a small-scale server with about 10~20 users. Is it OK to use daphne (without nginx, apache, etc..) as a production server that serves both asgi and rest api in this situation? -
How does formset function work for django-extra-views?
I am using the package django-extra-views to create inline forms. I want some help in understanding the working of formset function we use in javascript code while working with django-extra-views. How does it add 'Add Another' and 'Remove' link in the formset? I have taken help from Using django-dynamic-formset with CreateWithInlinesView from django-extra-views - multiple formsets In my views.py: class PriceDetailsInline(InlineFormSetFactory): model = models.PriceDetails form = forms.PriceDetailsForm fields = '__all__' factory_kwargs = {'extra': 1, 'can_delete': False} class CreateInvoiceView(LoginRequiredMixin, CreateWithInlinesView): model = models.Invoice form = forms.InvoiceForm inlines = [PriceDetailsInline] fields = '__all__' template_name = 'app/invoice_form.html' In my invoice_form.html: <table> {{ form.as_table }} </table> {% for formset in inlines %} <div id="{{ formset.prefix }}"> {% for subform in formset.forms %} <table> {{ subform.as_table }} </table> {% endfor %} {{ formset.management_form }} </div> {% endfor %} {% block extra_footer_script %} <script type="text/javascript"> $(function() { {% for formset in inlines %} $('div#FormSet{{ formset.prefix }}').formset({ prefix: '{{ formset.prefix }}', formCssClass: 'dynamic-formset{{ forloop.counter }}' }); {% endfor %} }) </script> {% endblock %} The code is working fine but I need to understand the flow in order to make changes to the 'add another' and 'remove' link and to apply crispy to the dynamically added forms. -
Django logging - default value of custom field in formatter
I am using below log formatter in my django app for keeping track of what class the logline belongs. 'format' : "[%(asctime)s] %(levelname)s [%(pathname)s:%(lineno)s:%(classname)s()] %(message)s" In this classname is custom field and I am accessing it as below. Sometimes I am collecting the logs from function that doesnt belongs to any class. In that case, I have to send logline with classname as 'NA' import logging logging.basicConfig(level=logging.INFO) log = logging.getLogger('django') # .......... SOME CODE ........ #Exception occurred inside class function log.error("EXCEPTION !!",extra={'classname': self.__class__.__name__}) # .......... SOME CODE ........ #Exception occurred in standalone function log.error("EXCEPTION in function !!",extra={'classname': "NA"}) Is there a way to put default value of classname as NA in formatter ? -
I can't register user in my user registration form
I have created a user registration form, every thing looks fine but when I try to register new user it brings back the same form while I redirected it to home page. Also when I go to admin to look for new registered user, I see nothing This is for python 3.7.3, django 2.2.3 and mysql 5.7.26. I have tried to check and recheck every thing seems to be ok but still I can't achieve what I want forms.py class NewUserForm(UserCreationForm): email = forms.EmailField(required=True) class Meta: model = User fields = ("username","email","password1","password2") views.py def register(request): if request.method == "POST": user_form = NewUserForm(request.POST) if user_form.is_valid(): user = user_form.save() login(request, user) return redirect("loststuffapp:IndexView") else: for msg in user_form.error_messages: print(user_form.error_messages[msg]) user_form = NewUserForm return render( request, "loststuffapp/register.html", context={"user_form":user_form} ) register.html {% extends "loststuffapp/base.html" %} {% block content %} <form method="POST"> {% csrf_token %} {{user_form.as_p}} <button type="submit" style="background-color: yellow">Register</button>> If you already have an account, <a href="/Register">login</a> instead {% endblock %} -
Could you please explain the add to cart view I have mentioned here?
I am following a tutorial for building my first e-commerce application. I am kinda stuck on his add to cart view. Kindly help me explain some code line in detail in that view which I don't understand. I will be writing the word "Detail" before the line of code I want to understand in detail. Here's the view def add_to_cart(request, slug): item = get_object_or_404(Item, slug=slug) order_item, created = OrderItem.objects.get_or_create( item=item, user=request.user, ordered=False ) Detail -- Why does the code filter order since this view is about order item not order order_qs = Order.objects.filter(user=request.user, ordered=False) if order_qs.exists(): order = order_qs[0] Detail -- Hint: Why it filters and where does this items come from and what query is in filter I don't known since it's repeating it if order.items.filter(item__slug=item.slug).exists(): Detail --- Why do we have to increase the quantitiy here order_item.quantity += 1 order_item.save() messages.info(request, "This item quantity was updated.") return redirect("core:order-summary") else: Detail --- why will we add it since it has to be in the card only order.items.add(order_item) messages.info(request, "This item was added to your cart.") return redirect("core:order-summary") Detail -- and what is written in this else why create the order and do unnecessary stuff else: ordered_date = timezone.now() order …