Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How Django integrated with firebase database
requests.exceptions.HTTPError: [Errno 401 Client Error: Unauthorized for url: https://sampleproject-bc0b2.firebaseio.com/users.json] { "error" : "Permission denied" } This is Linux server -
Django: SMTPAuthenticationError (535, b'Authentication Failed')
So I keep getting this error, someone please help. Will be really grateful. I'm trying to send a contact form message to an email. Settings.py EMAIL_HOST = 'smtp.zoho.com' EMAIL_HOST_USER = 'xyz@gmail.com' EMAIL_HOST_PASSWORD = 'xyz' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' Views.py def emailView(request): if request.method == 'POST': message = request.POST['message'] send_mail ('Contact Form', message, settings.EMAIL_HOST_USER, ['xyz@gmail.com'], fail_silently=False, ) return render(request, "email.html") I used the same email in both the settings and views. The password is correct and I have reviewed it. -
How to save refresh_token (token_secret) and expire time with django allauth google social?
I'm trying to set up Google authorization using django-allauth and django-rest-auth, but I can’t get and save refresh_token (token_secret) and expire_time to database. I need it to update the access_token without user intervention. How i can do it? -
Plugin mysql could not be loaded: The specified module could not be found
Using pipenv, I am trying to follow the "Writing your first Django app" tutorial and am getting stuck on part 2. I have an AWS free tier MySQL database up and running and am trying to configure my app to connect to MySQL instead of SQLite. Every time I try to move forward and use the python manage.py migrate command listed on that page, I get the above error (full stack trace at the bottom of this post). This also happens when I simply try to python manage.py runserver like in part 1. I have tried searching for all different parts of the final line of the stack trace, django.db.utils.OperationalError: (2059, "Plugin mysql could not be loaded: The specified module could not be found. Library path is 'lib/mariadb/plugin/mysql.dll'") and all of my searching has brought me to unrelated resources such as GIS applications and tons upon tons of posts directing me to look at my authentication method. Despite none of these matching my error specifically, I worked on the assumption that there could be an error being buried somewhere so they were worth a shot. I checked my existing user, who has the "Standard" authentication type according to MySQL Workbench. … -
How to hook a debugger to a python code running via django crontab?
I have a Django based web application, some functionality of the application is scheduled to be run as a part of cron jobs using django-crontab. I want to hook a debugger so that I can inspect some odd behaviours of my code. I normally use visual studio code. Is it possible to hook a debugger, since cron jobs basically run independently apart from server? -
Django best way to condition middleware
Currently, I used conditional middleware like this. class TestMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) if len(request.path) == 1: # Health check path print("Health check") return response return response if request.path == 1 ('/'), do some stuff for that endpoint. But if endpoint is increasing, I have to specify all the endpoint into middleware. I want to trigger for specific view class like permission_classes. Is there any solution here or above example is best way for it? Thanks. -
How to fix "Uncaught reference error : FilePond is not defined" in FilePond drag and drop
I am trying to use FilePond to implement drag and drop functionality on my website. I have downloaded the filepond css and js files and attatched them correctly. I keep getting an "Uncaught reference error : FilePond is not defined" whenever I try to finish the setup. <input type="file"> <script> const inputElement = document.querySelector('input[type="file"]'); const pond = FilePond.create( inputElement ); </script> -
Django Installed Apps - path full/partial
I was creating this django project and it has a class named "jobs". Now how do i add this "jobs" app in my setting.py. Some say we need to add full path like INSTALLED_APPS = [ 'jobs.apps.JobsConfig' ] and some say just add the app name like INSTALLED_APPS = [ 'jobs' ] can anyone tell me which is correct please? -
How are periodic tasks deleted from Celery?
In Celery and Django, whenever I delete the code for a periodic task from its tasks.py file it is not removed from the django_celery_beat_periodictask table in Postgres and thus is still called. I have attempted the following: Stopping Django, Celery and Beat. Restarting Django, Celery and Beat. Killing all workers via "kill". Using app.autodiscover_tasks(). Creating new periodic tasks in new tasks.py files in different modules works as expected but deleting them does not. Deleting the tasks via Django's admin page works but this is not ideal. I want the task discovery process to handle it. Is there a way for the tasks discovery process to handle deleted periodic tasks? -
JOIN Two table in DJANGO with aggregate
I've been playing around with django for a month now and i'm stuck with JOINING Two tables with Aggregate with it. Here's my models.py class Student(models.Model): student_number_format = RegexValidator(regex=r"^20{1,2}[1-2][0-9]-[0-9]{6}", message="Please enter a valid student number (example:2019-123456)") student_number = models.CharField(validators=[student_number_format], max_length=11, blank=True, unique=True, help_text="Student number must be this format 20YY-99999") student_course = models.ForeignKey(Course, on_delete=models.CASCADE) first_name = models.CharField(max_length=255) middle_initial = models.CharField(max_length=2) last_name = models.CharField(max_length=255) profile_picture = models.ImageField(upload_to=user_directory_path) date_registered = models.DateTimeField(default=timezone.now) class DataSets(models.Model): student_info = models.ForeignKey(Student, on_delete=models.CASCADE) dataset_image = models.ImageField(upload_to=dataset_directory_path) date_upload = models.DateTimeField(default=timezone.now) In here i have two models the DataSets class have a Foreign Key to Student. And i want to show only is Students that have 5 or more data inside DataSets. Here's the SQL representation: SELECT Count(student_info) as Count, A.first_name as Name FROM Student A JOIN DataSets B ON A.id = B.student_info_id WHERE Count >= 5 -
Instance construction fails on form data check
I have a custom Widget that allows for a dynamic number of key/value pairs to be entered into a form, which are assembled into a dict by the widget's value_from_datadict method. When I check the form's cleaned_data, I see exactly what I'm expecting: {'fieldname': {'key1': 'value1', ....} However, when the form is saved, fieldname isn't being updated. I've traced this down to the implementation of django.forms.models.construct_instance: def construct_instance(form, instance, fields=None, exclude=None): """ Constructs and returns a model instance from the bound ``form``'s ``cleaned_data``, but does not save the returned instance to the database. """ from django.db import models opts = instance._meta cleaned_data = form.cleaned_data file_field_list = [] for f in opts.fields: if not f.editable or isinstance(f, models.AutoField) \ or f.name not in cleaned_data: continue if fields is not None and f.name not in fields: continue if exclude and f.name in exclude: continue # Leave defaults for fields that aren't in POST data, except for # checkbox inputs because they don't appear in POST data if not checked. if (f.has_default() and form[f.name].field.widget.value_omitted_from_data(form.data, form.files, form.add_prefix(f.name))): continue # Defer saving file-type fields until after the other fields, so a # callable upload_to can use the values from other fields. if isinstance(f, models.FileField): file_field_list.append(f) … -
Filter and count in a for loop
In Django (2.0) I'm looping through records to display them in a table, I want a summary count to be displayed at the end for each record, I have this working using count = Fraction.objects.all().filter(botany_id=13).count() and the displaying {{ count }} however this is setup for record 13, the next record on the row has a botany_id=14 So how do I do this dynamically, essentially botany_id=botany_id #views.py def allflotation(request): botany = Botany.objects.all() fraction = Fraction.objects.all() count = Fraction.objects.all().filter(botany_id=13).count() fractioncomposition = FractionComposition.objects.all() # fractionmaterialspresent = FractionMaterialsPresent.objects.all() return render(request, 'flotation/allflotation.html', { 'botany':botany, 'fraction':fraction, 'count':count, 'fractioncomposition':fractioncomposition, # 'fractionmaterialspresent':fractionmaterialspresent }) -
Django smpt email backend slowing down performance
I'm developing/serving currently locally. I'm using django-admin for internal users to add items. I add in my signal code. My signal is post_save and it's purpose is to send an email to a user for approval. I test my signal using console.EmailBackend EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' I add a new item, there is no performance impact to the web browser. My models item page reloads quickly. I update my EMAIL_BACKEND too use smpt details EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' I add a new item, the performance impact is massive, my web browser now takes 15-30 seconds to to reload the items page after adding. Any thoughts around why the performance is so terrible? -
Django - Ajax POST JS variables to initialize form
I am working on a django project in which I have gathered up all of my variables in js and am trying to initialize a form (inside a modal popup) on same page without any refresh. I have the form showing up inside my modal, but can't quite figure out the Ajax post method to get my js variables into the initial form fields. Any help would be much appreciated! index.html - this function fires where I need it, but returns the page url instead of the data object I am trying to define. Index.html $.ajax({ method: "POST", url: '', data: { geology: ('#geology').value, latitude: ('latitude').value, longitude: ('longitude').value, csrfmiddlewaretoken: '{{ csrf_token }}', }, success: function(data){ console.log(data.geology); }, error: function(error_data){ console.log("error"); console.log(error_data); } }); views.py def home_view(request): geology = request.GET.get('geology') latitude = request.GET.get('latitude') longitude = request.GET.get('longitude') form = MineralForm(initial={'mineral': mineral, 'geology': geology, 'latitude': latitude, 'longitude': "INITIAL", 'description': description}) # populates form with what user tried to submit... -
How to retrieve values from multiple forms at once
So I am using dropzone js to create drag and drop file upload forms with django. Dropzone requires that you use a django form with a class of dropzone, since I am also allowing users to put in text, I just went ahead and created two forms with django. One for dropzone drag and drop file uploader and one for the normal input field. I created a submit button that submits both forms simultaneously when the button is clicked, did this with javascript. I've been trying to retrieve information from the submitted forms but keep getting None returned even though I submitted something. Any idea why? <button type="submit" id="add">Save</button> <button id="cancel">Cancel</button> <div class="col-sm-12 col-lg-6" id="inner"> <form method="POST" enctype="multipart/form-data" id="inputform" name="form1"> {% csrf_token %} <h4>Title</h4> <input type="text" name="product_title" id="product_title" placeholder="Give your product a name"> <h4>Price</h4> <input type="text" name="product_price" id="product_price" placeholder="0.00"> <h4>Description</h4> <input type="text" name="product_description" id="product_description" placeholder="Write a description about your product"> </form> </div> <div class="col-sm-12 col-lg-6" id="inner2"> <h3>Images</h3> <form method="POST" action="#" class="dropzone col-sm-8 col-lg-8" id="dropzone" name="form2"> {% csrf_token %} </form> def add(request): if request.method == "POST": print(request.POST.get("product_title")) return render(request,"main/add.html") -
Get Previous/Next item by using PK
views.py class ContentView(TemplateView): model = Content template_name = 'capt/pages/details.html' def get_context_data(self, pk, **kwargs): context = super().get_context_data(**kwargs) context['dataC'] = get_object_or_404(Content, title_id =self.kwargs.get('pk')) return context so, I want to get the next object of my model: class Section(models.Model): name = models.CharField(max_length=80, unique=True) def get_absolute_url(self): return reverse("media", kwargs={"pk":self.pk}) def __str__(self): return self.name class Meta: ordering = ["-pk"] But I'm not familiar with CBV. I made dynamic urls by overriding the get_context_data but now idk how to get the next or previous object using the pk. I thought using: context['previtem'] = Content.objects.get(pk=self.pk-1) would help me but I'm a lil bit stuck on this one. -
Djando templates with notepad++
Just want to give a solution i found about Django's templates with notepad++.If you want keywords like block, endblock,for,endfor to be bold by examples. You go to language, define your language,keywords list and you put the keywords, select style. You click "save as". Go select the new language at the bottom in the language menu ! have nice day! -
Django update field using a form in a many to many relationship
I have two models in many to many relationships. I want to use a form to update fields, the form has a drop list when authorizers have an option to reject or approve the leave. once the leave has been approved I want to be able to adjust the Leave_current_balance. However, I am getting the error message: 'float' object has no attribute 'save' from the line of code current_balance.save() def unitDirectorForm(request,id): if request.method=='POST': getstaffid=NewLeave.objects.get(id=id) form = DirectorForm(request.POST, instance=getstaffid) if form.is_valid(): form.save() total_days = getstaffid.Total_working_days current_balance = getstaffid.user.leave_balance.Leave_current_balance diff_balance = current_balance - total_days current_balance = diff_balance current_balance.save() return HttpResponse('You have successfuly Authorise the leave') else: form=DirectorForm() balance_form = leavebbalanceForm() return render(request,'managerauthorisedform.html',{'form':form}) class LeaveBalance(models.Model): user=models.OneToOneField(User,on_delete=models.CASCADE,primary_key=True,) Leave_current_balance= models.FloatField(null=True, blank=True, default=None) Year=models.CharField(max_length=100,default='') def __unicode__(self): return self.Year class NewLeave(models.Model): user=models.ForeignKey(User,default='',on_delete=models.CASCADE) leave_balance=models.ManyToManyField(Leave_Balance) Leave_type=models.CharField(max_length=100,blank=False,default='') Total_working_days=models.FloatField(null=True, blank=False) leave=( ('annual','annual'), ('sick','sick'), ) Leave_type=models.CharField(max_length=100,choices=leave,blank=False,default='') def __unicode__(self): return self.Leave_type -
How do I access the row values when importing a file with Django Import-Export?
I am importing a file with django import-export and I want to take the values of each row. For example: import_resource = ImportResource() dataset = Dataset() imported_data = dataset.load(import_file.read().decode('utf-8')) result = import_resource.import_data(dataset, dry_run=True) I iterate through the rows of the Result with result.rows and each row seems to have a raw_values property but it returns an empty list. -
Django in Docker - Deploy 2 instances with different settings
I have a Django 2.1 application and I have configured it to run in Docker. I need to deploy 2 instances of the same application and the differences are the Database each instance is connected to and some parameters in settings.py. Each instance has to be assigned to a different port, (lets say 8000 and 8001). Actually I have 2 different folders, like if there were 2 projects with their own environment and settings and each one is being launched using manage.py runserver 0.0.0.0:800x command (because is still in development). Main question: Is there any way to deploy this 2 instances in 1 single docker image, with this 2 ports and each instance running with its own settings file? Note: As I have some specific parameters in setting.py, I am using them in views importing the parameter like this: from MyApp.settings import COMPANY_ID Note2: This is the Dockerfile to deploy one single instance: FROM python:3.7 # COPY startup script into known file location in container COPY start.sh /start.sh # EXPOSE port to allow communication to/from server EXPOSE 8000 # The enviroment variable ensures that the python output is set straight # to the terminal with out buffering it first ENV … -
How can I run and test my production locally?
First of all, thank you ahead of time for any help on this thread. I have been meaning to ask for help with this matter for a while now and thought it was about time I asked. For the past 6 months I have been working for this company as the only developer (full stack developer). I am running the whole shebang here. Prior to this job I have been able to deploy webapps through UBUNTU on AWS with experience in Django, Nginx, Gunicorn and Angular. Nothing too advanced. The problem is that for the past 6 months I have been testing and developing through a very tedious manner. I would write a little bit of code, I git add,git commit, git push, and then git pull on the server followed by manage.py collectstatic. At first I went with it but now I would like to test changes locally and I am not sure how to do that. The webapp is a Django, with AWS MySQL database. From my personal experience, I was able to run and test my own apps just by a simple python manage.py runserver but that doesn't seem to be the case here. -
Joining two tables and getting sum of all items that belong to the order
In the order model - I'm trying to get the sub_total from the orderItems model - so essentially a sub total of all the order items that belong to that order number 1.b. Also suppose tax default value is 20%, is there an automated way to do sub_total + Tax = "total_gross"? In the django admin I have to manually data for now, but when I add more than "1" quantity, I have to manually count and add to net price, is there a way to do net_price multiplied by quantity = value of "net_total" and "total" in the order_items. class Order(models.Model): order_number = models.IntegerField(default="1", unique=True) sub_total = models.DecimalField(max_digits=6, decimal_places=2) tax = models.DecimalField(max_digits=6, decimal_places=2, default="20.00") total_gross = models.DecimalField(max_digits=6, decimal_places=2) class OrderItem(models.Model): order_number_fk = models.ForeignKey(Order, on_delete=models.CASCADE) net_price = models.DecimalField(max_digits=6, decimal_places=2) quantity = models.IntegerField() net_total = models.DecimalField(max_digits=6, decimal_places=2) total = models.DecimalField(max_digits=6, decimal_places=2) -
Sorting Model A by Model B returning duplicates
I have Model called Games that has many posts connected by Model Posts. When I sort Games by Model Posts date posted it returns duplicates from Model Games. I'm wondering how I can display Games by most recent post date without returning duplicates. Views.py 'recent': Game.objects.all().order_by('post', 'date_posted')[:5], Models.py class Post(models.Model): article_title = models.CharField(max_length=100, default="Article Title Place Holder") content = HTMLField(default="Article Content Pace Holder") date_posted = models.DateTimeField(default=timezone.now) game = models.ForeignKey('library.Game', on_delete=models.CASCADE) article_image = models.ImageField(default='/media/default.png') class Game(models.Model): title = models.CharField(max_length=100) description = models.TextField() date_posted = models.DateTimeField(default=timezone.now) cover = models.ImageField() cover_display = models.ImageField(default='default.png') developer = models.CharField(max_length=100) -
Making server talk to client devices connected to restricted internet WiFi
I am working on a social networking app that is being used by my fellow university students to socialise and form communities. The problem is most devices on college campus are connected to the college WiFi and the college WiFi has a lot of restrictions in terms of which websites can be accessed. As of now my backend server is not able to talk to devices that are connected to college WiFi but works just fine if connected through mobile data. As a backend developer how should I solve this issue. I want students to be able to use my app even through college Wifi. Are there some guidelines that I can incorporate that allows devices connected through college Wifi to talk to be able to talk to my server? I am using Django server. I am new at this and hence any help in terms of right resources and advices is hugely appreciated. -
Which database design to choose for a survey app?
I'm creating a survey app and I don't know how to design database. I need surveys with multiple questions and multiple types of questions. There are 3 ways that I could think of: a) Create a database table for surveys and every type of question and connect them with Survey_id column. b) Create a database table for questions and surveys and have them stored in JSON like text field. Those Text fields could look like this: { question: 'Who is the best student?' type: 'multiple-choices', choices: [ 'Bob', 'Alice', 'Alex', ], } c) Last option is to create a database table just for surveys and have them stored in JSON like format. Like this: { heading: 'My survey' date: '2019-01-01', questions: [ {...}, {...}, {...}, ], } Thanks for any suggestions.