Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django.db.utils.OperationalError: could not connect to server: Connection timed out
Im trying to connect my project on heroku to a AWS RDS, I have checked everything, read many articles on stackoverflow and google to no avail. Please help... It keeps saying : django.db.utils.OperationalError: could not connect to server: Connection timed out I dont know why. I have created an IAM on AWS, I dont know if i need to connect that to the database somehow, and actually it was correctly correctly when it was connect to heroku default database. Please help. What do i need to provide to facilitate this? -
Error when trying to assign a group to a user
I am trying to assign a group to a user but without the need to use the django manager, but I run into a problem and it tells me that "<User: island>" must have a value for the field "id" before this many-to-many relationship can be used. This is my view: class UserCreationView(LoginRequiredMixin, PermissionRequiredMixin, SuccessMessageMixin, CreateView): permission_required = 'users.add_user' login_url = 'users:login' template_name = 'users/register.html' model = User form_class = UserForm success_message = 'El usuario fue creado exitosamente' success_url = reverse_lazy('users:user') def form_valid(self, form): self.object = form.save(commit=False) group = Group.objects.get(pk=self.request.POST.get('groups')) self.object.groups.add(group) self.object.save() -
Generating sub domain on registration [Django app]
I am creating a Django chat app in which after an admin registration I want to create a sub domain of newly registered name. Example- my domain is www.localhost.com::8000 after user with name XYZ registered a sub domain must be created as www.XYZ.localhost.com. Now admin can invite its employees to register on this subdomain to join this subdomain specific chat channels. -
Web Push Django in Safari
I am using push notifications in Django, I am using the library https://github.com/safwanrahman/django-webpush It work correctly in Chrome and Firefox, but in Safari I have a JS error. TypeError: undefined is not an object (evaluating 'reg.pushManager.getSuscription') -suscribe -Anonymus Function The code is this: function subscribe(reg) { // Get the Subscription or register one reg.pushManager.getSubscription().then( function(subscription) { var metaObj, applicationServerKey, options; // Check if Subscription is available if (subscription) { return subscription; } metaObj = document.querySelector('meta[name="django-webpush-vapid-key"]'); applicationServerKey = metaObj.content; options = { userVisibleOnly: true }; if (applicationServerKey){ options.applicationServerKey = urlB64ToUint8Array(applicationServerKey) } // If not, register one reg.pushManager.subscribe(options) .then( function(subscription) { postSubscribeObj('subscribe', subscription, function(response) { // Check the information is saved successfully into server if (response.status === 201) { // Show unsubscribe button instead subBtn.textContent = 'Eliminar suscripción'; subBtn.disabled = false; isPushEnabled = true; showMessage('La suscripción se ha eliminado correctamente'); } }); }) .catch( function() { console.log('Subscription error.', arguments) }) }); } -
Django form data with azure logic apps
I got a django form data which I need to post to azure logic app. When I post the data I get this error: {"error":{"code":"NoResponse","message":"The server did not receive a response from an upstream server. Request tracking id '08585915990752009043423379830CU49'."}} When I check azure logs I see this error: BadRequest. The property 'content' must be of type JSON in the 'ParseJson' action inputs, but was of type 'application/x-www-form-urlencoded'. So as I understand I need to change this data to json as its sent as application/x-www-form-urlencoded. So My question is how can I do that? I'm new to django so any help would be great. My code looks like this: Views.py def home(request): context = initialize_context(request) if request.method == 'POST': vardas = request.POST.get('vardas') ToDate = request.POST.get('ToDate') FromDate = request.POST.get('FromDate') Pastabos = request.POST.get('Pastabos') username = request.POST.get('username') Login_form.objects.create(vardas=vardas,ToDate=ToDate,FromDate=FromDate,Pastabos=Pastabos,username=username) return render(request, 'loginas/home.html', context) My form in home.html {% extends "loginas/layout.html" %} {% load static %} {% block content %} <div class="container"> <h1 class="d-flex justify-content-center">Login Testas</h1> <p class="d-flex justify-content-center">Dominari Prisijungimas</p> {% if user.is_authenticated %} <form action="http://link_to_azure" method="POST"> {% csrf_token %} <div class="form-group"> <label>Vartotojas</label> <input class="form-control" name="vardas" type="text" value="{{user.name}}"readonly> </div> <div class="form-group"> <input class="form-control" name="username" type="text" value="{{user.email}}"hidden> </div> <div class="form-row"> <div class="col"> <div class="form-group"> <label>Nuo</label> <input class="form-control" … -
Nested subquery distinction to annotate sum
So I'd like to annotate a sum to a queryset, which has a little calculation rule with vars from remote tables. facturen = Factuur.objects.values('inkoopopdracht').filter( inkoopopdracht=OuterRef('pk'),) gefactureerd = facturen.annotate( gefactureerd=Sum(Case( When( factuurpost__inkooppost__btw__systematiek=2, then=(F( 'factuurpost__inkooppost__aantal')*F('factuurpost__inkooppost__eenheidprijs'))), default=F( 'factuurpost__inkooppost__aantal')*F('factuurpost__inkooppost__eenheidprijs')*( 1+F('factuurpost__inkooppost__btw__percentage')), output_field=DecimalField(), )), ).values('gefactureerd') qs = qs.annotate( factuursom=Subquery(gefactureerd.values( 'gefactureerd'), output_field=DecimalField()), ) The result of the above query is satisfactory. Except when there is a multiple of 'factuurpost'. In this case the sum seems to be multiplied with factuurpost instances. A fix for this, would be 'distinct=True' on the Sum. However since it only distincts values and not instances, this introduces a new problem. Similar values are no ignored, yielding the wrong sum. This seems to be an issues other people have come across with as well, e.g. : Django Count and Sum annotations interfere with each other Now, I used the solution there, with the subquery. I tried to nest the subquery to no avail. Does anyone see a potential solution to have it calculate the right sum in all cases? -
django - apscheduler how to keep job when uwsgi restart
django - 2.2.12 apscheduler - 3.6.3 I would like to set the notification to be sent two weeks after the user executes a specific task. scheduler.py import logging import time from apscheduler.schedulers.background import BackgroundScheduler logger = logging.getLogger(__name__) class JobLauncher: _sched = None def __init__(self): JobLauncher._sched = BackgroundScheduler() JobLauncher._sched.start() def __str__(self): return "JobLauncher" def run(self, job): return self.run_job(job) def stop(self, job): JobLauncher._sched.remove_job(job.name) def shutdown(self): if JobLauncher._sched.running(): logger.debug('Scheduler is shutting down.') JobLauncher._sched.shutdown() else: logger.warn("Cannot shutdown scheduler because scheduler is not running at the moment. please check scheduler status.") def run_job(self, job): if JobLauncher._sched.get_job(job.name) is None: _job = JobLauncher._sched.add_job(func=job.runMethod, trigger='date', id=job.name, args=job.job_params,run_date = job.job_date) return True return False class CommonJob: def __str__(self): return "Job Infos : {name : %s, job_params : %s}" % (self.name, self.job_params) @property def name(self): return self._name @name.setter def name(self, new_name): self._name = new_name @property def job_date(self): return self._job_date @job_date.setter def job_date(self, new_job_date): self._job_date = new_job_date @property def job_params(self): return self._job_params @job_params.setter def job_params(self, new_job_params): self._job_params = new_job_params @property def runMethod(self): return self._runMethod @runMethod.setter def runMethod(self, new_runMethod): self._runMethod = new_runMethod class JobLauncherHolder: _launcher = None @staticmethod def getInstance(): if not JobLauncherHolder._launcher: JobLauncherHolder._launcher = JobLauncher() return JobLauncherHolder._launcher Add Job Code from utils.scheduler import JobLauncherHolder,CommonJob def event(self,userUID): launcher = JobLauncherHolder.getInstance() if launcher: … -
Django File Download Issue(filename issue & multiple files issue)
I am designing a django application which converts csv files to pipe delimited and download converted files. from more_itertools import chunked def submit(request): #form requests and file uploads #conversion function, this function converts csv files and chunks them into the 10000 rows and creates new files for every 10000 lines. def file_conversion(input_file,output_file_pattern,chunk_size): with open(input_file,"r+") as fin: # ignore headers of input files for i in range(1): fin.__next__() reader = csv.reader(fin, delimiter=',') for i, chunk in enumerate(chunked(reader, chunk_size)): with open(output_file_pattern.format(i), 'w', newline='') as fout: writer = csv.writer(fout,reader,delimiter='^') writer.writerow(fed_headers) writer.writerows(chunk) script_dir = os.path.dirname(os.path.abspath(__file__)) dest_dir = os.path.join(script_dir, 'temp') try: os.makedirs(dest_dir) except OSError: pass path =os.path.join(dest_dir,code+'{:01}.csv' ) #code is received from form # the function creates converted files such as code1.csv, code2.csv, code3.csv,etc file_conversion(i/p file from upload,path,10000) base_name = os.path.basename(path) #returns just a file name # all requirements are passed into context # 'submit.html' is also returned. def download(request): path = request.GET.get('path') base_name1 = os.path.basename(path) context = {'path': path, 'base_name1': base_name1} with open(path, 'rb') as fh: response = HttpResponse(fh.read()) response['Content-Disposition'] = 'inline; filename='+base_name1 return response The application creates files as code1.csv, code2.csv, code3.csv, etc. But in the params path and base_name, it looks to download code{01}.csv. How to properly arrange this filename format and … -
Django : ImportError
I have an app called users_auth and in the models.py file I have two Models. PENDING = 1 APPROVED = 2 REJECTED = 3 APPROVE_USER_STATUS = ( (PENDING, 'Pending'), (APPROVED, 'Approved'), (REJECTED, 'REJECTED'), ) class User(AbstractUser): is_doctor = models.BooleanField(default=False) is_police = models.BooleanField(default=False) is_manager = models.BooleanField(default=False) user_status = models.IntegerField(choices=APPROVE_USER_STATUS, default=1) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True, null=True, blank=True) class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='user_info') full_name = models.CharField(max_length=100, null=True, blank=True) cell = models.CharField(max_length=11, null=True, blank=True) address = models.CharField(max_length=200) profile_picture = models.ImageField(default='default.jpg', upload_to='profile_pics', null=True, blank=True) updated_by = models.ForeignKey(User, on_delete=models.SET_NULL, related_name='update_profile', null=True, blank=True) description = RichTextUploadingField(null=True, blank=True) def __str__(self): return "{username}'s Info".format(username=self.user) This code is Working Fine. But I want to add two more fields in UserProfile Model. expertise = models.ManyToManyField(Expertise) hospital = models.ForeignKey(Hospital, on_delete=models.SET_NULL, related_name='hospital', null=True, blank=True) After adding these two lines, If I run makemigrations command it shows: ImportError: cannot import name 'APPROVE_USER_STATUS' from 'users_auth.models' I have imported User & APPROVE_USER_STATUS from users_auth App in other app's model file by: from users_auth.models import APPROVE_USER_STATUS, User N.B : Import was working fine before adding these two fields. What could be the reason? -
How to make nested datatable using Django and Jquery
I have a master table and multi details tables. I want to display it using django-datatable. How to modify it to chow details as collapsible table inside master table row? -
Django Filter latest files
I have a model like, class Type(CommonBase): """ Allowed document types """ DOCUMENT_CLASS_CHOICES = ( ('C', 'Credit Card'), ('D', 'Debit Card'), ('SD', 'Supporting Documents'), ) MODEL_TYPE_CHOICE = ( ('person', 'Person'), ('bank', 'Bank'), ('all', 'All') ) document_title = models.CharField(max_length=100) document_class = models.CharField(choices=DOCUMENT_CLASS_CHOICES, max_length=3, default='C') model_type = models.CharField(choices=MODEL_TYPE_CHOICE, max_length=50, default='person') class Document(CommonBase): doc_type = models.ForeignKey(Type, on_delete=models.PROTECT) uploaded_datetime = models.DateTimeField(null=True, blank=True) user = models.ForeignKey(Person, on_delete=models.CASCADE) comment = models.CharField(max_length=200, null=True, blank=True) I can upload Multiple credit card or multiple debit card details against the same user. So if a user has uploaded 2 credit card documents and 3 debit card documents, how the djnago query is supposed to be for getting latest uploaded credit card and debit card document details. -
how to add current active user as foreign key to the create post model in djangorestframework?
how to add current active user as foreign key to the create post model in djangorestframework ? models: class DoctorProfile(models.Model): id=models.AutoField(primary_key=True) name = models.CharField(_('name'), max_length=50, blank=True) mobile = models.CharField(_('mobile'), unique=True, max_length=10, blank=False) email = models.EmailField(_('email address'), blank=True) password = models.CharField(_('password'),max_length=25,blank=False) otp = models.IntegerField(null=True, blank=True) class Doctor_clinic(models.Model): clinic_id = models.AutoField(primary_key=True) doc_profile = models.ForeignKey(DoctorProfile,related,on_delete=models.CASCADE) clinic_name = models.CharField(max_length=150) clinic_address = models.CharField(max_length=150) City = models.CharField(max_length=50) state = models.CharField(max_length=50) pincode = models.IntegerField() #how to get the forign key in serializers I wrote in this way, is this correct/relevent? class UserSerializer(serializers.ModelSerializer): # mobile = serializers.RegexField("[0-9]{10}",min_length=10,max_length=10) password = serializers.CharField(write_only=True) email=serializers.EmailField(max_length=155,min_length=3,required=True) name=serializers.CharField(max_length=55,min_length=3,required=True) class Meta: model = DoctorProfile fields = ("name", "email", "password", "mobile","otp") class ClinicSerializer(serializers.ModelSerializer): class Meta: model = Doctor_clinic fields =('clinic_name','clinic_address', 'City', 'state', 'pincode','doc_profile') class ClinicRegistrationView(generics.ListCreateAPIView): serializer_class = ClinicSerializer queryset = Doctor_clinic.objects.all() permission_classes = (IsAuthenticated,) -
Getting error "TypeError: Object type <class 'str'> cannot be passed to C code"
I'm following a tutorial on https://medium.com/@nipun.357/aes-encryption-decryption-java-python-6e9f261c24d6 for encryption and decryption in python. I'm getting error in my case: raise TypeError("Object type %s cannot be passed to C code" % type(data)) TypeError: Object type <class 'str'> cannot be passed to C code The code is coverting string to bytes then Why am I getting this error. Why code is not working and how can I reesolve this import base64 import hashlib from Crypto import Random from Crypto.Cipher import AES def get_private_key(secret_key, salt): block_size = 16 pad = lambda s: s + (block_size - len(s) % block_size) * chr(block_size - len(s) % block_size) unpad = lambda s: s[0:-ord(s[-1:])] iv = Random.new().read(AES.block_size) # Random IV return hashlib.pbkdf2_hmac('SHA256', secret_key.encode(), salt.encode(), 65536, 32) def encrypt_with_AES(message, secret_key, salt): block_size = 16 pad = lambda s: s + (block_size - len(s) % block_size) * chr(block_size - len(s) % block_size) unpad = lambda s: s[0:-ord(s[-1:])] iv = Random.new().read(AES.block_size) # Random IV private_key = get_private_key(secret_key, salt) message = pad(message) cipher = AES.new(private_key, AES.MODE_CBC, iv) cipher_bytes = base64.b64encode(iv + cipher.encrypt(message)) return bytes.decode(cipher_bytes) def decrypt_with_AES(encoded, secret_key, salt): block_size = 16 pad = lambda s: s + (block_size - len(s) % block_size) * chr(block_size - len(s) % block_size) unpad = lambda s: … -
How to horizontally space bootstrap form
Here's how my django filter form looks like: I need to horizontally space them a little so that 'Name contains' and the search bar, and 'result' etc are not glued to each other. Here's my html code: <form action="" method="get" class="form-inline text-white justify-content-center mx-3"> {{myfilter.form|bootstrap}} <button class="btn btn-primary" type="submit"> Search</button> </form> I have tried adding m-3, mx-3 etc but they don't work. Little help will be appreciated. Thanks! -
Creating an ecommerce site with Django
I am looking into setting up a box subscription-type business and have chosen Django as my ecommerce platform of choice. At first, I decided to build the back-end from scratch with custom models and such. However, I have since realised it would be much wiser to utilise a framework, to get up-and-running as fast as possible. I have concluded that django-shop would be the best option as it provides the most customisation, at least in my opinion. The problem is that I can't seem to find any resources about implementing it. The documentation provides a cookiecutter template, but I would prefer to build it from scratch and not struggle with changing or removing the aspects I don't want, such as React. If ayone has any resources or tutorials about setting up a custom django-shop app, I would really appreciate it! -
I am trying to display result table but subject1_title, subject1_credit_hour, subject1_grade and subject1_remarks are showing blank in frontend
I have created the models.py with folling value but unable to diplay in frontend. subject1_title=models.CharField(max_length=40) subject1_credit_hour=models.TextField() subject1_grade_point=models.TextField() subject1_grade=models.TextField() subject1_remarks=models.CharField(max_length=20, null=True, blank=True) my home.html page looks like this. <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> th, td { border: 2px solid #666; } table.t1 { table-layout: fixed; width: 40%; } </style> </head> <h1><center>Search Your Result</center></h1> <br> <form method="POST" action=" " align="center"> {% csrf_token %} {{ form }} <input type="submit" value="Submit"/> <br> <br> <br> {% for result_query in objects %} <table align="center"> <tr> <th>S.N</th> <th>Course Code No.</th> <th>Course Title</th> <th>Cr.Hr.</th> <th>Grade Point</th> <th>Grade</th> <th>Remarks</th> </tr> <tr> <td>{{ result_query.subject1_code }}</td> <td>{{ result_query.subject1_title }}</td> <td>{{ result_query.subject1_credit_hour }}</td> <td>{{result.query.subject1_grade_point}}</td> <td>{{result.query.subject1_grade}}</td> <td>{{result.query.subject1_remarks}}</td> </tr> <tr> <td>{{ result_query.subject2_code }}</td> <td>{{ result_query.subject2_title }}</td> <td>{{ result_query.subject2_credit_hour }}</td> <td>{{result.query.subject2_grade_point}}</td> <td>{{result.query.subject2_grade}}</td> <td>{{result.query.subject2_remarks}}</td> </tr> <tr> <td>{{ result_query.subject3_code }}</td> <td>{{ result_query.subject3_title }}</td> <td>{{ result_query.subject3_credit_hour }}</td> <td>{{result.query.subject3_grade_point}}</td> <td>{{result.query.subject3_grade}}</td> <td>{{result.query.subject3_remarks}}</td> </tr> <tr> <td>{{ result_query.subject4_code }}</td> <td>{{ result_query.subject4_title }}</td> <td>{{ result_query.subject4_credit_hour }}</td> <td>{{result.query.subject4_grade_point}}</td> <td>{{result.query.subject4_grade}}</td> <td>{{result.query.subject4_remarks}}</td> </tr> <tr> <td>{{ result_query.subject5_code }}</td> <td>{{ result_query.subject5_title }}</td> <td>{{ result_query.subject5_credit_hour }}</td> <td>{{result.query.subject5_grade_point}}</td> <td>{{result.query.subject5_grade}}</td> <td>{{result.query.subject5_remarks}}</td> </tr> <tr> <td>{{ result_query.subject6_code }}</td> <td>{{ result_query.subject6_title }}</td> <td>{{ result_query.subject6_credit_hour }}</td> <td>{{result.query.subject6_grade_point}}</td> <td>{{result.query.subject6_grade}}</td> <td>{{result.query.subject6_remarks}}</td> </tr> </table> {% endfor %} </form> </html> I taking register# and name to search the database result, able to … -
Insert data in postgresql table django
Here is how my views.py looks like @api_view(['GET', 'POST']) def AnswersList(request): if request.method == 'GET': # user requesting data snippets = PAResponse.objects.all() serializer = PAAnswersSerializer(snippets, many=True) return Response(serializer.data) elif request.method == 'POST': # user posting data serializer = PAAnswersSerializer(data=request.data) #print("serializer in post",type(serializer),serializer) if serializer.is_valid(): serializer.save() # save to db result=Calculate(serializer) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) in post method i am sending my serializer as an argument to the "Calculate" function which is written in calculations.py . Calculate function returns me a list . but i am struggling on how can i send the element of list in different model from calculations.py list looks like this Result_list= [1,20,14,14,38,8,82] which i want to send in AnalysisResult class of model. My models.py class AnalysisResult(models.Model): user_id=models.IntegerField(primary_key=True) E=models.IntegerField() A=models.IntegerField() C=models.IntegerField() N=models.IntegerField() O=models.IntegerField() total=models.IntegerField() class Meta: db_table='analysis_result' def __str__(self): return self.response Please let me know if you need any more information. i am new to this so please help me . In simple terms can i send "Result_list" to db_table='analysis_result' directly from calculations.py instead of views or models.py if not then how can i send data . Any kind of lead will be helpful DB=postgressql 13 -
access field of foregin key in django model function
Let's say I have the following models.py: from django.db import models class Person(models.Model): name = models.CharField(max_length=100) father = models.ForeignKey(Person, on_delete=models.CASCADE) And I need to add a function fullName(self) that will return a string, the person's name + space + the person's father name. What is the correct syntax to do this? I tried the following but it doesn't work from django.db import models class Person(models.Model): name = models.CharField(max_length=100) father = models.ForeignKey(Person, on_delete=models.CASCADE) def fullName(self): return self.name + " " + self.father.name pylint says: instance of 'ForeginKey' has no 'name' member -
Django data save model without form in template
I want to save a value in the database when the button is clicked without using a form. I want to save the value in h2 to another model when the button is clicked. What can i do? TEMPLATE <div class="widget-main"> <center><h2 name="urun" value="{{ urun.urun_adi }} ">{{ urun.urun_adi }}</h2></center> </a> <input type="submit" data-actions-icnt="sepete_ekle/" value = "sepete ekle" class="btn btn-sm btn-default pull-right"> Sepete Ekle </inputa> <a href="" class="btn btn-sm btn-success">{{urun.fiyat}} TL</a> </div> VIEWS def sepete_ekle(request): if request.method == 'POST': urun = request.POST["urun"] status = 0 urunler = Siparis.objects.create(urun,status) urunler.save() messages.success(request, " Sepete Eklendi") return redirect('/bayi/profil_duzenle') else: return HttpResponseRedirect("/") MODEL class Siparis(models.Model): bayi = models.ForeignKey('auth.User', verbose_name='bayi', on_delete=models.CASCADE, related_name='bayi',limit_choices_to={'groups__name': "BayiGrubu"}) urun = models.ForeignKey(Urun, on_delete=models.CASCADE) adet = models.IntegerField() tarih = models.DateTimeField() status = models.BooleanField() class Meta: verbose_name = 'Bayi Sipariş' verbose_name_plural = 'Bayi Siparişleri' -
can I send email once at a particular time using celery?
I am sending emails using Amazon SES using Django. but I want to know if I can send an email to the clients subscribed only once at a particular time. I think using Celery may be possible but I can't implement it. Please give me a solution. Thanks in advance. -
can we create separate view files in django app?
In my django app, i have user,employee,admin modules. do I can create seperate views.py files for user,employee and admin eg: i have folder called "AdminFolder" and I have added seperate adminView.py in it is it allowed in django? -
load templates from database in dajngo
I am working on a project where some templates are stored as part of a 'theme' in the database. Because of this, I'm not able to leverage a lot of Django's nice template rendering functionality immediately, i tried using dajngo-dbtemplates and added template to database but i couldn't find a way how to render those templates to let users to select their choice of template.basically i am working on a project for digitcards that let user to choose their choice of template and shows their details onto it -
django filter using ajax
I use django-filter to sort products. When I use ajax for this, after selecting the category, the sorting operation is not done properly and it query again for all the products and returns the results if it should be only on the products related to the same category that I selected do this. This is done correctly without using ajax. When I am not using ajax, after filtering the products, the url is as follows: category/shoes/10/?brand=4/ But when I use ajax after filtering the url products as follows: /category/shoes/10/ ( I use django-filter to sort products. When I use ajax for this, after selecting the category, the sorting operation is not done properly and it query again for all the products and returns the results if it should be only on the products related to the same category that I selected do this. This is done correctly without using ajax. When I am not using ajax, after filtering the products, the url is as follows: category/shoes/10/?brand=4/ But when I use ajax after filtering the url products as follows: /category/shoes/10/) filter.py: class ProductFilter(django_filters.FilterSet): brand = django_filters.ModelMultipleChoiceFilter(queryset=Brand.objects.all(), widget=forms.CheckboxSelectMultiple) url: path('filter/', views.product_filter, name='filter') views: def product_filter(request, slug=None, id=None): products = Product.objects.all() category = … -
How can I use email scheduling same as Gmail using Django?
Hii All I have a question as we all know that Gmail has a new feature of scheduling email on a given date and time. I am also trying to build the same feature for my project. And all I have completed, the dashboard, users email and everything. Can Anyone suggest me step by step guide to build this feature. Thanks in advance. For the information I am trying to build with django-post_office library, I also tried RabbitMq message broker and celery but I am unable to find a way. I want somthing like this no other changes Captcha Meaning -
Please anyone help me I'm getting IntegrityError at /cart/ in django ecommerce Duplicate entry
Please somebody help me I'm stuck here and don't know why I'm getting this error. I'm trying to build an e-commerce website and when I try to add a customer to the cart through Mixin I get this error. This is my models.py class Customer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) first_name = models.CharField(max_length=70) middle_name = models.CharField(max_length=70) last_name = models.CharField(max_length=70) email = models.EmailField(unique=True) mobile = PhoneField(unique=True) registered_date = models.DateTimeField(auto_now_add=True) def __str__(self): full_name = self.first_name + ' ' + self.middle_name + ' ' + self.last_name return full_name class Meta: ordering = ['first_name'] class Cart(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, unique=False, null=True, blank=True) total = models.PositiveIntegerField(default=0) def __str__(self): return 'Cart:' + str(self.id) class CartProduct(models.Model): cart = models.ForeignKey(Cart, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) size = models.CharField(max_length=100, blank=True, null=True) rate = models.PositiveIntegerField() quantity = models.PositiveIntegerField() subtotal = models.PositiveIntegerField() def __str__(self): return 'Cart:' + str(self.cart.id) + 'CartProduct:' + str(self.id) this is my views.py class CustomerToCartMixin(object): def dispatch(self, request, *args, **kwargs): cart_id = request.session.get('cart_id') if cart_id: cart_obj = Cart.objects.get(id=cart_id) if request.user.is_authenticated and request.user.customer: cart_obj.customer = request.user.customer cart_obj.save() else: pass return super(CustomerToCartMixin, self).dispatch(request, *args, **kwargs) class CartView(CustomerToCartMixin, generic.TemplateView): template_name = 'accounts/cart.html' def get_context_data(self, **kwargs): context = super(CartView, self).get_context_data() cart_id = self.request.session.get('cart_id', None) if cart_id: cart_obj = Cart.objects.get(id=cart_id) else: cart_obj = …