Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Access GCP VM via HTTPS
Hi everyone I have a GCP VM (Debian 10 image) running a Django REST API via Nginx and Gunicorn. Since I need to call the API via HTTPS I created a load-balancer with HTTPS frontend and HTTP connection to the VM on the backend. When I call the load balancer domain it connects via HTTPS to the VM. However, instead of the Django REST API, the standard NGINX message is displayed. If I call the IP of the VM directly, without the load balancer, it still displays the Django REST API. How can I access the Django REST API via the load balancer through HTTPS? Also if there are other easy-to-implement ways of accessing the VM via HTTPS without the load balancer I d be interested. Cheers -
django reference to an entire table, not to a specific entry
I'm currently working on a setting system. here i create settings for the display of different models. I'm just missing an efficient reference to the model/table. With the foregnkey you can set a reference to a specific instance, but I'm looking for a reference to an entire table. I'm currently doing it via a charfield, but find it inefficient. is there some kind of modelField? class A(models.Model): pass class B(models.Model): pass class C(models.Model): pass Classes A, B and C are any datastores for which I want to store settings. class foo(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) classname = models.CharField(max_length=64) parameters of settings foo is the class in which I want to store the settings for the other classes settingsA = foo.objects.filter(user=user, classname = A.__name__) settingsB = foo.objects.filter(user=user, classname = B.__name__) settingsC = foo.objects.filter(user=user, classname = C.__name__) -
Update profile avatar DRF and Vue.js
I am not fully understanding why I can not update an image url in my DRF api. I am using djoser for the api endpoints and activation, django rest framework and vue.js for the frontend with axios making the API requests. I believe (and I may be wrong!) that I cannot make patch requests with Axios using FormData() so from googling I have found another method but Im still getting HTTP 500 error and Django error: Internal Server Error: /api/v1/users/me/ Traceback (most recent call last): File "/Users/markmckeon/Django_Stuff/Relate/environment_3_8_8/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/Users/markmckeon/Django_Stuff/Relate/environment_3_8_8/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/markmckeon/Django_Stuff/Relate/environment_3_8_8/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/Users/markmckeon/Django_Stuff/Relate/environment_3_8_8/lib/python3.8/site-packages/rest_framework/viewsets.py", line 125, in view return self.dispatch(request, *args, **kwargs) File "/Users/markmckeon/Django_Stuff/Relate/environment_3_8_8/lib/python3.8/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) File "/Users/markmckeon/Django_Stuff/Relate/environment_3_8_8/lib/python3.8/site-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "/Users/markmckeon/Django_Stuff/Relate/environment_3_8_8/lib/python3.8/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc File "/Users/markmckeon/Django_Stuff/Relate/environment_3_8_8/lib/python3.8/site-packages/rest_framework/views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "/Users/markmckeon/Django_Stuff/Relate/environment_3_8_8/lib/python3.8/site-packages/djoser/views.py", line 175, in me return self.partial_update(request, *args, **kwargs) File "/Users/markmckeon/Django_Stuff/Relate/environment_3_8_8/lib/python3.8/site-packages/rest_framework/mixins.py", line 82, in partial_update return self.update(request, *args, **kwargs) File "/Users/markmckeon/Django_Stuff/Relate/environment_3_8_8/lib/python3.8/site-packages/rest_framework/mixins.py", line 68, in update self.perform_update(serializer) File "/Users/markmckeon/Django_Stuff/Relate/environment_3_8_8/lib/python3.8/site-packages/djoser/views.py", line 149, in perform_update super().perform_update(serializer) File "/Users/markmckeon/Django_Stuff/Relate/environment_3_8_8/lib/python3.8/site-packages/rest_framework/mixins.py", line 78, in perform_update serializer.save() … -
Django VSCode debug raising exception for code that actually works
I have looked into similar questions, but found none exactly similar to the issue I'm facing. I am not using a virtual environment. I wanted to test debugging django project/app files in VSCode but I'm stuck with 'fake' import exceptions. Everything seems to be working as expected, but for some reason VSCode's debugger can't find my files. Here's the code snippet: from django.contrib import admin from .models import Paciente The first line doesn't raise any exceptions. The second one, though, raises this: Exception has occurred: ImportError attempted relative import with no known parent package So I put the parent folder in the path, like: from app.models import Paciente but then I get another exception: Exception has occurred: ModuleNotFoundError No module named 'app' So then, I tried removing the python path syntax, leaving just "models", as in: from models import Paciente I then get another exception, this time not in the admin file (the one I was trying to debug), but in the models file, complaining that: Exception has occurred: ImproperlyConfigured Requested setting USE_TZ, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. Except it is configured in settings.py. It's there(always … -
does Django HttpResponseRedirect suffer from xss attack?
As title, because of urlpatterns are setting numeral parameter, i tend to think that HttpResponseRedirect won't suffer from xss attack, am i right? If not, how does HttpResponseRedirect suffer from it? urls.py from django.urls import path from hello import views app_name = 'hello' urlpatterns = [ path("", views.home, name="home"), # ex: /hello/5/ path('<int:question_id>/', views.detail, name='detail'), path('<int:question_id>/results/', views.results, name='results'), ] views.py def detail(request, question_id): return HttpResponseRedirect(reverse('hello:results', args=(question.id,))) -
Has anyone else now got problems with Django emails?
I have a Django app which utilises the built in password reset option. This was working fine until a few days but now it doesn’t work (I now get a network error 500 error message). Has anyone else had similar problem with Django emails recently? -
Forigen Key not displaying in rendered model form
I am looking for guidance on where I am going wrong. My model form is rendering correctly however the author has no option to select or input. I suspect this is is because the author is a foreign key. How do I get around this so the form will display a list of users or allow to manually input a name. Any help would be greatly appreciated :) models.py class Post(models.Model): title = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name="workout_posts") updated_on = models.DateTimeField(auto_now=True) featured_image = CloudinaryField('image', default='placeholder') content = models.TextField(default='SOME STRING') excerpt = models.TextField(blank=True) created_on = models.DateTimeField(auto_now_add=True) class Meta: # ordered created on field starting with newest first ordering = ['-created_on'] def __str__(self): return self.title forms.py class MakeWorkOutForm(forms.ModelForm): class Meta: model = Post fields = '__all__' views.py def createWorkOut(request): form = MakeWorkOutForm context = {'form': form} return render(request, "add-workout.html", context) -
What's the difference between django.db.close_old_connections and django.db.connections.close_all?
I'm using Django command to do some schedule task. And before it start, I want to clear my old db connections.And it seems there're two ways to make it as below. import django django.db.close_old_connections() django.db.connections.close_all() Which one is better? Thanks -
In DJANGO, how do I query for records that do not exist after a certain date?
Assume I have a model as such: class Invoices(models.Model): customer = models.ForeignKey(Customer, ...) date = models.DateField() amount = models.FloatField() I want to know all customers that have not purchased for the last 30 days. Basically the inverse of this query: no_sales = Invoices.objects.filter( date__gte=certain_date_30_days_ago ).values( 'customer__code' ) using .exclude() just excludes the customers who have purchased in the last 30 days but not include the people who have not purchased in the last 30 days. Any thoughts? :) Thanks! -
Login, Register and Logout test failed AssertionError: 200 != 302 django
I am trying to create a test for my login, logout and register views but I keep on getting this error AssertionError: 200 != 302. Here are the codes: MODEL Here is the User model from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): full_name = models.CharField(max_length=300, null=True, blank=True) username = models.CharField(max_length=150) email = models.EmailField(unique=True) avatar = models.ImageField(upload_to='user-profile-images/', null=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] VIEWS Here is the login and register function view def loginPage(request): context = {} if request.user.is_authenticated: return redirect('home') if request.method == 'POST': email = request.POST.get('email') password = request.POST.get('password') try: user = User.objects.get(email=email) except: messages.error(request, 'User does not exist') user = authenticate(request, email=email, password=password) if user is not None: login(request, user) return redirect('home') return render(request,'registration/login.html', context) def registerPage(request): form = SignupForm if request.method == 'POST': form = SignupForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.username = user.username.lower() user.save() login(request, user) return redirect ('home') else: messages.error(request, 'An error occured during registration') return render(request, 'registration/register.html', {'form':form}) def logoutPage(request): logout(request) return redirect('home') URLS from django.urls import path from . import views urlpatterns = [ path('login/', views.loginPage, name='login'), path('logout/', views.logoutPage, name='logout'), path('register/', views.registerPage, name='register'), ] TEST from django.test import TestCase, Client from django.urls import reverse from mydp_app.models import User class … -
Django multiple filter in same table column
i want to get the type of enquiry and display the count for each product in that type In views.py def current(request): act=enquiry.objects.filter(type='Activity').values('product_name').distinct().annotate(Count('product_name')) wal=enquiry.objects.filter(type='Walkin').values('product_name').distinct().annotate(Count('product_name')) tele=enquiry.objects.filter(type='Tele').values('product_name').distinct().annotate(Count('product_name')) digital=enquiry.objects.filter(type='Digital').values('product_name').distinct().annotate(Count('product_name')) In models.py class product(models.Model): product_category=models.CharField(null=True,max_length=5000) product_category_id=models.CharField(null=True,max_length=5000) branch=models.CharField(default='',max_length=100) products=models.CharField(null=True,max_length=5000) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(default=timezone.now) def __str__(self): return '{},{}'.format(self.products, self.product_category) class enquiry(models.Model): comment=models.CharField(default='',max_length=100,null=False) branch=models.CharField(default='',max_length=100) created_at = models.DateField(auto_now_add=True) updated_at = models.DateTimeField(default=timezone.now) created_by=models.CharField(default='',max_length=100) status=models.CharField(default='',max_length=100) commentupdate=models.CharField(default='',max_length=100) product=models.ForeignKey(product,models.CASCADE,default='') product_name=models.CharField(default='',max_length=100) product_category=models.CharField(default='',max_length=100) type=( ('Walkin','Walkin'), ('Activity','Activity'), ('TeleEnq','TeleEnq'), ('Digital','Digital'), ) type=models.CharField(choices=type, default='',max_length=100) status_type=( ('Retail','Retail'), ('Closed','Closed'), ) status_update=models.CharField(choices=status_type, default='open',max_length=100) In html {%for pr in act%} <tr> <td>{{forloop.counter}}</td> <td>{{pr.product_name}}</td> <td>{{pr.product_name__count}}</td> {%endfor%} {%for pr in wal%} <td>{{pr.product_name__count}}</td> {%endfor%} {%for pr in tele%} <td>{{pr.product_name__count}}</td> {%endfor%} {%for pr in digital%} <td>{{pr.product_name__count}}</td> {%endfor%} </tr> I want output like this: product walkin Activity Tele DIgital Total p1 4 1 3 0 8 p2 0 6 0 1 7 p3 2 1 3 0 6 p4 3 2 0 4 9 :------: :------: :-------: :----: :-------: :-----: total 9 10 6 5 30 -
Modals in Django are not showing
I am trying to add another model in django admin, called Posts. I have few other modules that are working and showing, but I don t know why this new one down not appear. Below is my code Models.py from django.db import models import datetime from django.contrib.auth.models import User STATUS = ((0, "Draft"), (1, "Published")) class Post(models.Model): title = models.CharField(max_lenght=1048) slug = models.SlugField(max_lenght=1048) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts') content = models.TextField() status = models.IntegerField(choices=STATUS, default=0) class Meta: ordering = ['-created_on'] def __str__(self): return self.title admin.py from django.contrib import admin from .models import Post, Application, Message, FloaterMessage # Register your models here. admin.site.register(Post) admin.site.register(Message) admin.site.register(FloaterMessage) admin.site.register(Application) settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'visionStudios', 'contact', 'crispy_forms' ] -
Django Admin panel overflows the selected model window
I have a problem in the Django admin panel. When I select any model from the list, it seems to open it "under" the main page, instead of opening a new window with it. Highlighted is what belongs to the Message model. How can I fix it? -
django ManyToMany doesn't retrieve relavant objects
I have a model as follows: class Question: text = models.TextField(_("Quiz")) votes = models.ManyToManyField( verbose_name=_("Votes"), related_name="questions", to="myapp.QuizVote", blank=True, ) def __str__(self): return self.text and another one: class QuizVote: quiz = models.ForeignKey( verbose_name=_("Quiz"), to="myapp.Question", on_delete=models.CASCADE ) vote = models.ForeignKey( verbose_name=_("QuizVote"), to="myapp.Vote", on_delete=models.CASCADE, null=True, blank=True, ) def __str__(self): return "{}".format(self.vote.name) and the last one class Vote: name = models.TextField(_("Vote")) When I look into Question admin, in the field of votes I expect to see just those QuizVote records which have the same id as each specific Question. However each Question objects shows all available records in QuizVote without filtering based on ids. I tried to add this method to Question model this but doesn't work: @receiver(m2m_changed, sender=Question.votes.through) def retrieve_quiz_vote(sender, instance, action, **kwargs): if action == "post_add": instance._get_relavant_votes() in Question model added thid then: def _get_relavant_votes(self) -> None: if isinstance(instance, Question) \ and hasattr(instance.__class__, 'objects'): relevant_votes = instance.__class__.objects.filter( votes__name__in=instance.votes.all() ).distinct() return relevant_votes -
Printing PDF with selenium on Heroku (Django)
I'm really struggling with an issue. I spent the evening trying to solve it, made multiple researches but I can't find a hint to solve it. My project : print a specific webpage as PDF, using selenium and chrome webdriver, on a heroku app via django. The idea is that the user (me) get a pdf file just after he fill a form on a website with a link of it's choice. My printing script works perfectly locally (my pdf is downloaded with the right parameters), my heroku app works well (I managed to retrieve the link from my Django form). Here is my index method, linked to the form I use in my template. Once the form is filled, it calls the function (MyPdfSaver()) that is supposed to print the pdf. def index(request): submitbutton = request.POST.get("submit") study_url = '' test_value = '' form = UserForm(request.POST or None) if form.is_valid(): study_url = form.cleaned_data.get("study_url") test_value = MyPdfSaver(study_url) #calling the function that prints as PDF. context = { 'form': form, 'study_url': study_url, #the link I want to print a PDF from 'submitbutton': submitbutton, 'test_value' : str(test_value) #just a test value } return render(request, 'index.html', context) Here is my MyPdfSaver function (the idea … -
FOR UPDATE cannot be applied to the nullable side of an outer join on Postgres Django app
I'm trying to create a Django app for a course to learn it and I use this repo to practice: https://github.com/hltcoe/turkle However, I ran into an issue where I keep on getting this error. Note that the issue only exists when I use postgres. NotSupportedError at /batch/1/accept_next_task/ FOR UPDATE cannot be applied to the nullable side of an outer join -
DjangoQ fails in bitbucket pipeline
I am creating a scheduled task with DjangoQ and to register it I have this code on my apps.py: from django.apps import AppConfig class ShiftsConfig(AppConfig): name = 'shifts' def ready(self): from django_q.models import Schedule func: str = 'path_to_func' schedule = Schedule.objects.filter(func=func).exists() if not schedule: Schedule.objects.create(func=func, hook='path_to_hook', schedule_type=Schedule.MINUTES, minutes=15, repeats=-1 ) It's working fine locally. Then, I wanted to deploy it and I have some pipeline steps being triggered on every commits. The steps are about linting and testing: - step: &run-linter image: python:3.7 name: Run linter caches: - pip script: - pip3 install -r requirements.txt - export DJANGO_SETTINGS_MODULE=main.settings - export DB_NAME=django - export DB_USER=django - export DB_PASS=django - export DB_POSTGRES_HOST=localhost - pylint ./* > pylint_report.txt artifacts: - pylint_report.txt - step: &run-test name: Run Test caches: - pip script: - export DB_NAME=django - export DB_USER=django - export DB_PASS=django - export DB_POSTGRES_HOST=localhost - coverage erase - coverage run manage.py test - coverage xml -i services: - postgres artifacts: - coverage.xml But on the testing step when I call coverage run manage.py test I receive: The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 17, in execute_from_command_line(sys.argv) File "/usr/local/lib/python3.8/dist-packages/django/core/management/init.py", line 419, in execute_from_command_line … -
Django- SummerNote- Staticfiles
How to grab local resource of image after copying image from summernote text area? for ex. i'm taking screenshot and pasting it into comment section configured with summernote editor. after posting it i can see image source in inspect like this : img src="/resources/ec/resources/WYSIWYG_images/2022/1/20/dc72bc03-d2ae-4e15-9252-1f1dacb8c6e0.png" style="height: 250px;" but after copying that image from posted comment and using it to another comment. it changes image source like this : img src="http://192.168.1.213:8006/resources/ec/resources/WYSIWYG_images/2022/1/20/dc72bc03-d2ae-4e15-9252-1f1dacb8c6e0.png" looks like its getting hosted by local server. but whenever i delete the first comment i posted which HAS ORIGINAL SOURCE of Image then second comment is not displaying Image. so any solution how to handle that? -
Different structure path of python base program
when i works with coverage i see that when i want to run test with it i must code for example like "coverage run manage.py test src.apps.accounts.tests " in terminal and when i want see the result i must write "coverage report --include=src/apps/service/accounts/* -m " .my question is why we use ". " for run and use "/ " for see the result? and in general when we should use "." and when we should use "/" (this example did not only one case i see so i want a way to understand when should use each other of them) *in advance i am tank you for get me full solution and read the my question that write with my weak english understand. -
Django: Unknown column error when running on production server
When I attempt to login to my django application on the production server (AWS EBS), it keeps returning the following error (1054, "Unknown column 'two_factor_phonedevice.throttling_failure_timestamp' in 'field list'"). Strangely, the app works fine when running locally using the same MYSQL database (AWS RDS). I have tried dropping the database and re-running migrations believing it was due to an inconsistency between my db and migrations files however I still keep getting the same error. I am using the django_two_authentication module for the user authentication/logins. The table two_factor_phonedevice is created by the module to track the user devices registered for two factor authentication. I cannot seem to solve why the column can be found when running locally but cannot be found on the production server despite both using the same database. -
Django Chart data and labels
I'm currently making a dashboard that shows data for staff. I have made a function to get chart data and labels, so far, I've managed to do the labels.. but I can't seem to get the count for the amount of occurrences for each of the dates. I need the output for get_chart_data to be a list or tuple like this: 20/01/2022: 1, That means that on that day I only had 1 object added to the database for example. The code I have tried so far have failed, or give me the count up to a certain date but nothing correct. The important part is that the date range is dynamic. Views.py @login_required(login_url='/accounts/login/') def get_chart_data(request, model, data_range): end_date = dt.localdate() print(end_date) start_date = dt.localdate()- timedelta(days=data_range) print(start_date) db_objects = model.filter(transaction_date__lte=end_date, transaction_date__gt=start_date).\ values('transaction_date').\ annotate(count=Count('purchase_id')) print(db_objects) amount_objects = list(db_objects) print(amount_objects) dates = [x.get('transaction_date') for x in amount_objects] print(dates) for d in (end_date - start_date for x in range(0,data_range)): if d not in dates: amount_objects.append({'createdate': d, 'count': 0}) data = amount_objects return data @login_required(login_url='/accounts/login/') def get_label_data(request, model, data_range): label = [] end_date = dt.localdate() start_date = dt.localdate()- timedelta(days=data_range - 1) delta = start_date - end_date # returns timedelta for i in range(data_range): day … -
How can i import export with foreign key relationship
I have csv file with user addresses, and his phone number, How can i import it in my address table. Since I dont know user id of each user. i'm getting following error Line number: 1 - null value in column "user_id_id" of relation "proj_auth_useraddress" violates not-null constraint DETAIL: Failing row contains (432, null, null, someaddress, , , null). But i know relationship of user and address is through his phone number. user_id__phone # Models.py class AppUser(AbstractUser): phone = models.CharField(max_length=15, unique=True, null=True) ... class UserAddress(models.Model): address_id = models.AutoField(primary_key=True) user_id = models.ForeignKey(AppUser, on_delete=models.CASCADE) lat = models.FloatField(null=True, blank=True) lng = models.FloatField(null=True, blank=True) address1 = models.CharField(max_length=100) address2 = models.CharField(max_length=100, null=True, blank=True) city = models.CharField(max_length=50) pincode = models.IntegerField() # Admin.py @admin.register(UserAddress) class AddressAdmin(ImportExportModelAdmin): resource_class = AddressAdminResource # Resource.py class AddressAdminResource(resources.ModelResource): class Meta: model = UserAddress import_id_fields = ('address_id',) -
django.db.utils.OperationalError: (1050, "Table 'profiles_category' already exists")
I am trying to host my website using FileZilla and PuTTY. For that, I have added the code in FileZilla remote site and I have created a database named jobs using following commands in PuTTY app. sudo mysql -u root #For Maria DB CREATE DATABASE jobs; GRANT ALL PRIVILEGES ON jobs.*TO 'hello'@'localhost'; flush privileges; exit Then python3 manage.py makemigrations command is executed and after that when I executed the python3 manage.py migrate command I got an error like this. django.db.utils.OperationalError: (1050, "Table 'profiles_category' already exists") Here the table profiles_category is not already existed. models.py class Category(models.Model): name = models.CharField(max_length=40) def __str__(self): return self.name class CategoryJob(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) name = models.CharField(max_length=40) def __str__(self): return self.name Can anyone suggest a solution for this? -
having issues with django installing
#!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main(): """Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'noonmusic.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if name == 'main': main() -
Set background color for each days of week in fullcalendar if a criteria matches?
I use django with fullcalendar and I want to change the color of days based of user's schedule. here is the structure of the user's schedule: Sunday: off // e.g. color should be blue Monday: work // e.g. color should be pink Tuesday: home // e.g. color should be yellow ... I want to change all Sunday's color to blue and so on. here is my code: $('#calendar').fullCalendar({ header: { left: 'prev', center: 'title', right: 'next' }, defaultView: 'month', eventLimit: true, events: [ {% for event in events %} { title: "{{ scheduled_event.title }}", date: '{{ scheduled_event.date|date:"Y-m-d" }}', time: '{{ scheduled_event.time }}', display: 'background' }, {% endfor %} ], });