Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get Content-Disposition header
I want to get the content of the "Content-Disposition" my backend code using Django Rest Framework, the specific code like following: with open(results['filepath'], 'rb') as target: response = HttpResponse(target) response['Content-Type'] = 'application/octet-stream' filename = results['filename'] disposition = "attachment; filename*=UTF-8''{}".format(filename) response["Content-Disposition"] = disposition return response my frontend code use vue, the specific code like following: this.$axios.post( `/api/v1/applications/pod-dlfiles/?cluster=${this.dialogFile.cluster}&name=${this.dialogFile.name}&ns=${this.dialogFile.namespace}&cr=${this.dialogFile.container}`, data ).then((res) => { console.error('restest', res) var fileURL = window.URL.createObjectURL(new Blob([res])) var fileLink = document.createElement('a') fileLink.href = fileURL fileLink.setAttribute('download', `${this.dialogFile.name}` + '.txt') document.body.appendChild(fileLink) fileLink.click() }) I printed the value of the 'res', and the result is the contents of the file. There are no other attributes. why? -
Django Bootstrap - How to change width of dropdown menu items
I have created a menu and then submenu for my website. The links are all working as expected but I have an issue with layout. When I click on particular menu item, a submenu appears but the width of submenu box is too big as I just have to show 2 items (rent and buy). Can you please assist as to what can I do to correct this? I am using Bootstrap.min.css. Please see template file below [![{% load static %} <!-- Navbar --> <div id="sticky-header" class="header-middle-area transparent-header hidden-xs"> <div class="container"> <div class="full-width-mega-drop-menu"> <div class="row"> <div class="col-md-12"> <div class="sticky-logo"> <a href="{% url 'index' %}"> <img src="{% static 'index1/images/logo/logo3.png' %}" alt=""> </a> </div> <nav id="primary-menu"> <ul class="main-menu text-center"> <li><a href="{% url 'index' %}">{% if '/' == request.path %} <mark>Home</mark> {% else %} Home {% endif %}</a> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-display="static" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> {% if 'listings_residential_rent' in request.path %} <mark>Residential Rent</mark> {% else %} Residential {% endif %} </a> <div class="dropdown-menu aria-labelledby="navbarDropdown"> <a href="{% url 'listings_residential_rent' %}">Rent</a> <a href="https://www.youtube.com/"> Buy </a> </div> </li> <li><a href="{% url 'admin:index' %}">Realtor Login</a> </li> </ul> </nav> </div> </div> </div> </div> </div>][1]][1] -
why let's encrypt certificate(SSL) error installing django site which is hosted in Ubuntu vps
I have successfully deployed the Django project in my ubuntu VPS server. but when i try to install sudo certbot --apache -d amritshahi.com. I am getting the following error. Enabling available site: /etc/apache2/sites-available/365-le-ssl.conf Error while running apache2ctl configtest. Action 'configtest' failed. The Apache error log may have more information. AH00526: Syntax error on line 25 of /etc/apache2/sites-enabled/365.conf: Name duplicates previous WSGI daemon definition. Rolling back to previous server configuration... Error while running apache2ctl configtest. Action 'configtest' failed. The Apache error log may have more information. AH00526: Syntax error on line 25 of /etc/apache2/sites-enabled/365.conf: Name duplicates previous WSGI daemon definition. inside 365.conf file: <VirtualHost *:80> ServerAdmin me@amritshahi.com ServerName amritshahi.com ServerAlias www.amritshahi.com DocumentRoot /var/www/personal Alias /static /var/www/personal/Personal_Blog/static <Directory "/var/www/personal/Personal_Blog/static"> Options Indexes FollowSymLinks Order allow,deny Allow from all Require all granted </Directory> Alias /media /var/www/personal/Personal_Blog/media <Directory "/var/www/personal/Personal_Blog/media"> Options Indexes FollowSymLinks Order allow,deny Allow from all Require all granted</Directory> ErrorLog ${APACHE_LOG_DIR}/shahi_error.log CustomLog ${APACHE_LOG_DIR}/shahi_access.log combined WSGIDaemonProcess Personal_Blog python-home=/var/www/personal/Personal_> WSGIProcessGroup Personal_Blog WSGIScriptAlias / /var/www/personal/Personal_Blog/project/wsgi.py <Directory /var/www/personal/Personal_Blog/project> <Files wsgi.py> Require all granted </Files> </Directory> </VirtualHost> Help Please?? -
Django: exclude some objects
i want to exclude some user from the User model, who are exists in friends, i_requested, requested_me . models.py: class Relation(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) friends = models.ManyToManyField(User, related_name='my_friends', blank=True) i_requested = models.ManyToManyField(User, related_name='i_requested', blank=True) requested_me = models.ManyToManyField(User, related_name='requested_me', blank=True) views.py: def allUser(request): me = request.user f = Relation.objects.get(user=me) ff = f.friends.all() users = User.objects.all() exclude = users.exclude(id__in=ff) print(exclude) print(ff) serializer = SimpleUserSerializer(user, many=True) return Response(serializer.data) when i run this code, it prints: <QuerySet [<User: test5>, <User: test3>, <User: test2>]> <QuerySet [<User: test5>]> why it don't exclude test5? -
Method \"POST\" not allowed in Django rest framework ModelViewset
I am trying to POST with extra actions in Django Rest, but am getting this error {"detail":"Method \"POST\" not allowed."} This is the method for POST : class TemplateView(ModelViewSet): @action(detail=False, methods=['POST'], url_path=r'process_version_template/') def process_version_template(self, request): print("request", request) return JsonResponse({}, safe=False, status=200) In my urls.py : api_router = DefaultRouter() api_router.register(r'template', views.TemplateView, 'template') urlpatterns = [ path('predefined-comments', PredefinedCommentListView.as_view(), name='predefined_comments'), ] urlpatterns += api_router.urls Then my endpoint am using in Postman to send data is : http://127.0.0.1:8000/api/v1/financing-settings/template/process_version_template/ then, the body is : { "id":1784, "param":"block", "target":315 } What am I doing wrong ? -
How to use same django filter(filters.py) in two different views
I have a filter class defined below. filters.py class CTAFilter(django_filters.FilterSet): id = django_filters.NumberFilter(label="DSID") class Meta: model = CTA fields = ['id', 'EmailID','id','Shift_timing'] Now I want to use this CTAFilter in normal template(table data)view and in download views. I have observed that It is working fine for normal render view but when I am using it in my download views it is not working and I am getting all model data in the .xls file. Please find the below questions which I have posted. how to use Django filtered class data to 2 seperate view I am not able to resolve this problem I have tried to check if I can define it globally so that the filter will work for all views(like RESTAPI). Is there any way I can make my download view as a child view class of normal render view so that I will use the below code from the parent view(as it is working fine)? cta_list = CTA.objects.all() cta_filter = CTAFilter(request.GET, queryset=cta_list) allcta = cta_filter.qs A>Normal View where the filter is working fine. def retrievecta_view(request): if request.method == 'GET': allcta = CTA.objects.all() allcta1 = allcta allctagen = allcta1.filter(Shift_timing__exact='General') allctamor = allcta1.filter(Shift_timing__exact='Morning') allctseve = allcta1.filter(Shift_timing__exact='Evening') allctatotal = allcta1.filter(Shift_timing__exact='Total') … -
Watching for file changes with StatReloader Exception in thread django-main-thread, when i run python manage.py runserver using django
just started learning Django, this is what happened when I use python manage.py runserver SyntaxError: invalid syntax maonanbei:lecture3 duomi$ python3 manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py", line 950, in _bootstrap_inner self.run() File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py", line 888, in run self._target(*self._args, **self._kwargs) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/core/management/commands/runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/utils/autoreload.py", line 76, in raise_last_exception raise _exception[1] File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/core/management/__init__.py", line 357, in execute autoreload.check_errors(django.setup)() File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/apps/config.py", line 116, in create mod = import_module(mod_path) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 972, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked ModuleNotFoundError: No module named 'hellodjango' I added a new application call "hello", a function to send a request to ask for respond and in hello/view.py look … -
updated queue in RabbitMQ
I have a task that is to be executed after a POST or PATCH for an object, say ABC The code goes as follows: models.py class ABC(models.Model): start_at = models.DateTimeField() task.py @app.task def do_something(obj_id): try: abc = ABC.objects.get(id=obj_id) except ObjectDoesNotExist: return eta = settings.ETA do_something.apply_async([abc.id], eta=eta) return views.py class ABCPost(CreateAPIView): serializer_class = ABCSerializer def post(self, request): # create object # call task do_something def patch(self, request): # update the `start_at` field for ABC # call task do_something So, when the field is updated, the queued message should be executed at the updated start_at value. However, with the code above two messages are queued for the same object but different timestamps. How can I avoid that? Thanks in advance -
Fat Models, working out variables based on other date
I am still fairly new to Django but I am trying to stick to the fat model, thin controller aspects of Django. I have a price input that could change so this has been assigned to a form: class AdminData(models.Model): year1 = models.IntegerField() year3 = models.IntegerField() I want to work out the day_rate for these services based on different factors such as weeks in a year and hours per day which are fixed outside my model weeksinyear = 52 How can I get a day_rate fixed variable based on the user input for a 1 year and 3 year options, my initial thoughts were to create a variable like below, which does not work. week_rate_year1 = year1 / weeksinyear Any help is greatly appreciated, am I suppose to do this via models or should this code run in the template or view? As it is a static value based on the user inputted value I am not sure. Thanks for helping a noob. -
i need to host a django app to a shared VPS (latin cloud)
https://la.latincloud.com/938948-Soporte-para-Python i have to host a django website on a shared vps (latin cloud ).they provided in their document how to deploy i have provide the link but could not understand how to link to the env and wsgi file.i have to host a django website on a shared vps (latin cloud ).they provided in their document how to deploy i have provide the link but could not understand how to link to the env and wsgi -
Django + init.js + breakpoints
I am very new to Django. I am also not very knowledgeable in JS (at this point I am mainly interested in the backend side of things). I downloaded a portfolio and it seems to have JS scripts connected between each other (I am unsure if this is related to the issue). The init.js file controls the breakpoints and then depending of size of window opens up the appropiate CSS file. This might be a newbie thing but I used {% static '...' %} in the js files but the they don't load up when refreshing website. Do I meant to do something different? Below are few excepts from my files. Home.html init.js (I changed the init.js back to normal without {% static '...' %} -
Connect Django to MySql database on VPS
I am trying to run my Django project on a VPS. My Django project uses MySQL. While running it on my local computer I used the following code to connect MySQL to Django DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'db_name', 'USER': 'root', 'PASSWORD': 'password', 'HOST': 'localhost', 'PORT': 3306} } What must be the 'USER','HOST','PORT' here while connecting to MySQL? -
Modal dialogue does not open
I want a confirmation window to popup when a record is clicked for deletion. Below is mylibre/cms/templates/cms/base.html. {% load i18n static %} <!DOCTYPE html>{% get_current_language as LANGUAGE_CODE %} <html lang="{{ LANGUAGE_CODE|default:"en-us" }}"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="stylesheet" href="{% static 'cms/css/bootstrap.min.css' %}"> {% block extra_css %}{% endblock %} <title>{% block title %}My books{% endblock %}</title> </head> <body> <div class="container"> {% block content %} {{ content }} {% endblock %} </div> <script src="{% static 'cms/js/jquery-3.5.1.min.js' %}"></script> <!-- <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script> --> <script src="{% static 'cms/js/bootstrap.bundle.min.js' %}"></script> {% block extra_js %}{% endblock %} </body> </html> From which mylibre/cms/templates/cms/info_list.html is created. "Modal Dialogue Confirming Deletion" does not get called. At least I don't see any evidence of it being called. {% extends "cms/base.html" %} {% block title %}List of Comments{% endblock title %} {% block content %} <h4 class="mt-4 border-bottom">List of Comments<small class="text-muted ml-3">{{ ward.name }}</small></h4> <a href="{% url 'cms:info_add' ward_id=ward.id %}" class="btn btn-primary btn-sm my-3">Add</a> <table class="table table-striped table-bordered"> <thead> <tr> <th>ID</th> <th>コメント</th> <th>Manipulate</th> </tr> </thead> <tbody> {% for info in infos %} <tr> <td>{{ info.id }}</td> <td>{{ info.comment|linebreaksbr }}</td> <td> <a href="{% url 'cms:info_mod' ward_id=ward.id info_id=info.id %}" class="btn btn-outline-primary btn-sm">Modify</a> <button class="btn btn-outline-danger btn-sm del_confirm" data-toggle="modal" data-target="#deleteModal" data-pk="{{ … -
Django form not visible after redirect
I'm trying to make django form to appear after user is logged in and authenticated but the form just does not appear on the page here is my code. Is it something I do wrong in redirects or something else? If you guys could help me figure this out that would be nice views.py code from django.shortcuts import render from django.http import HttpResponse, HttpResponseRedirect from django.urls import reverse from loginas.auth_helper import get_sign_in_url, get_token_from_code, store_token, store_user, remove_user_and_token, get_token from loginas.graph_helper import get_user from .forms import Prasymas from .models import Post def home(request): context = initialize_context(request) return render(request, 'loginas/home.html', context) def initialize_context(request): context = {} # Check for any errors in the session error = request.session.pop('flash_error', None) if error != None: context['errors'] = [] context['errors'].append(error) # Check for user in the session context['user'] = request.session.get('user', {'is_authenticated': False}) return context def sign_in(request): # Get the sign-in URL sign_in_url, state = get_sign_in_url() # Save the expected state so we can validate in the callback request.session['auth_state'] = state # Redirect to the Azure sign-in page return HttpResponseRedirect(sign_in_url) def callback(request): # Get the state saved in session expected_state = request.session.pop('auth_state', '') # Make the token request token = get_token_from_code(request.get_full_path(), expected_state) # Get the user's profile user … -
Django url prefix association
I'm very new to Django & hoping I can get some guidance on a question I had. I want to have multiple URL prefixes each with a different site prefix for my client's projects for example client1.website.com. Each prefixed site will have a different database associated. Is this something that's possible to do with Django? Can some please point me in the right direction? -
Copy data between Django-Models (from View to table)
I’m new to Python and Django, and I’m trying to create WebApp with Django. I was trying to find a solution for two days. Thank you for your help in advance. Problem. In the app, I have a "view" where ingredients from Larder are listed, I want to choose ingredients and specify how much of it a ate and save it in the Ingredients_eaten model, but to do this, I need to pass few data from Larder (Ingredient name, quantity, unit). How can I do it? In View.py I know how to save data from the form (two fields), but I miss those three fields from Larder, and I don’t know to do it. I have three models Ingredients_bought – where the user specifies what kind of ingredient he/she buy, e.g. Milk, Eggs Larder – this is a MySQL view which group data from ingredients_bought by name and unit (e.g., If I buy milk twice, I will see one line with quantity two) Ingredient_eaten – in this model, I want to store information about what I ate. And here I have a problem. View: def larder_detail_view(request): obj = Larder.objects.all() form = EatForm() if request.method == 'POST': form = EatForm(request.POST) if … -
Django : filter object based on a date
I'm trying to filter my request based on a date field. I would like to check if a date is greater than the current date. This is what I tried, based on this answer : How do I filter query objects by date range in Django? orders.object.filter(deliveryDay__gt = date.today()).order_by('-id') Unfortunately it didn't work in my query which returns all orders to me regardless of the date. I don't understand where is my error. Thank you by advance for your help. -
Validation Error django not working in my template
In my register form i added a validation error when there is a used username or email But it is not working in my template... forms.py : from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django import forms class RegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] def clean_username(self): username = self.cleaned_data.get("username") if User.objects.filter(username=username).exists(): raise forms.ValidationError("Username is not unique") return username def clean_email(self): email = self.cleaned_data.get("email") if User.objects.filter(email=email).exists(): raise forms.ValidationError("Email is not unique") return email the template: <body> <div class="container"> <h1>Register</h1> <form action="" method="post"> {% csrf_token %} <label for="username">Username</label><br> {{forms.username}} <br> <label for="email">Email</label><br> {{forms.email}} <br> <label for="password1">Password</label><br> {{forms.password1}} <br> <label for="password2">Confirm Password</label><br> {{forms.password2}} <br> {% if form.errors %} {% for field in form %} {% for error in field.errors %} {{ error|escape }} {% endfor %} {% endfor %} {% for error in form.non_field_errors %} {{ error|escape }} {% endfor %} {% endif %} <br><br> <input type="submit" value="Register"> </form> </div> </body> when i run the website and i try to put the same email it did not give me any error it just reload the page with removing the email or the username -
Restrict user to update model form
I'm using Django auth for my model Dish. Each user manages many dishes (1-n relationship) # models.py class Dish(models.Model): user_id = models.ForeignKey(User, on_delete=models.CASCADE) dish_name = models.CharField(max_length=50) # views.py class ProfileFormView(LoginRequiredMixin, UpdateView): login_url = '/accounts/login' template_name = 'dish.html' model = Dish success_url = '/dish/updated' I want to restrict my UpdateView to only dish's owner (For example: user 1 owns dish 1 and 2; user 2 owns dish 3 and 4. user 1 can edit dish 1, but cannot edit dish 3 or 4). Assuming that user manages other models (for example: menu, ratings, etc), and they all need to be restricted to their owners. What is the proper way to achieve this? Thank you very much! -
implement Django admin TabularInline form in template
i want to implement forms like admin TabularInline forms in django template. ( i think we're gonna need inlineformset_factory for this kind of forms and jquery for dynamic add remove buttons ) write your answer for below model: models.py from django.db import models class Model_A(models.Model): field_1 = models.CharField(max_length=150) field_2 = models.CharField(max_length=150) class Model_B(models.Model): field_3 = models.ForeignKey(Model_A, on_delete=models.CASCADE, related_name='Model_B') field_4 = models.CharField(max_length=150) admin.py from django.contrib import admin from my_app import models class Model_B_Inline(admin.TabularInline): model = models.Model_B extra = 0 class Model_A_Admin(admin.ModelAdmin): list_display = ['field_1', 'field_2'] inlines = [Model_B_Inline] admin.site.register(models.Model_A, Model_A_Admin) Thanks in advanced. -
Django's list_select_related does not show foreign key's attributes
Basically I am trying to have the attributes of a foreign key available both in the list_display and in the admin editor. However, even using the list_select_related (I have also tried modifying the queryset with the select_related method) the foreign key attributes do not appear in any of the mentioned admin screens. Toy example: class BookAdmin (admin.ModelAdmin): list_select_related = ('author',) Where the book model has a OneToOne relationship with author, and author has some attributes (first_name, last_name, etc.) that I want to display in the admin site. Am I forgetting something? I know I could do lookups to list and inlines to edit, but it doesn't seem like a very optimal solution ... Thank you very much! -
Render PHP through Django
Is there any way to render PHP files through Django for code Reusability. I have tried through django_php module and it was 10 year old module, so it does not support latest python versions (3.9) Any help is appreciated .Thanks -
Django servers not starting after installing live server
reloading the site every time was very frustrating to me so i thought to look for a live server for djanglo Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 11, in main from django.core.management import execute_from_command_line File "C:\Users\piyush\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\__init__.py", line 52 except ImportError,e: ^ SyntaxError: invalid syntax and this is the error popping now when i used python manage.py runserver command https://pypi.org/project/django-liveserver/ the server i installed -
Django User Login Error -login() missing 1 required positional argument: 'user'
views.py def loginUser (request): if request.method=="POST": username=request.POST.get('username') password=request.POST.get('password') user = authenticate(username=username, password=password) if user is not None: login(request, user) return redirect("/") else: return render(request,'login.html') -urls.py urlpatterns = [path('',views.index,name='home'), `path('login',views.login,name='login')] -
Order of returned django records changed after upgrading to postgrers12?
Our Django project has been running on Postgres 10.15 for a while and now we need to upgrade to Postgres12. While running the unit tests, one of them broke. Turns out, the reason for this is that after fetching objects using xyz.abc_list.all(), (abc references xyz with the related name abc_list) the order of the returned objects have changed (PS. the model class abc does not have any ordering in meta). I have been trying to go through the changelog of postgres but have not been able to find anything that gives a solid reason for the change in this behavior. AFAIK, the django does not ensure any ordering if not mentioned.. Can there be proper reasoning established for this change in behavior?