Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What are the dependencies for django-allauth python:3.8.3-alpine Dockerfile
I have a Dockerfile, docker-compose.yml, requirements.txt defined below for a django project. The Dockerfile uses python:3.8.3-alpine and the docker-compose.yml have a db service that uses postgres:12.0-alpine image. I made sure that the dependencies are defined in the Dockerfile as required. However, it seems to me that django-allauth require extra dependencies. I have tried for days to fix this issue but get an error that says This package requires Rust >=1.41.0. ERROR: Failed building wheel for cryptography. I haved pasted the whole error for reference sake. Any help will be much appreciated. Thanks in advance. #requirements.txt Django>=3.1.5,<3.2.0 gunicorn>=20.0.4,<20.1.0 psycopg2-binary>=2.8,<2.9 Pillow>=8.1.0,<8.2.0 django-allauth>=0.44.0,<1.0.0 #Dockerfile # pull official base image FROM python:3.8.3-alpine # set work directory WORKDIR /usr/src/app # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # install psycopg2 dependencies RUN apk update \ && apk add postgresql-dev gcc python3-dev musl-dev \ && apk add libffi-dev libressl-dev \ && apk add --no-cache jpeg-dev zlib-dev libjpeg # install dependencies RUN pip install --upgrade pip COPY ./requirements.txt . RUN pip install -r requirements.txt # copy entrypoint.sh COPY ./entrypoint.sh . # copy project COPY . . # run entrypoint.sh ENTRYPOINT ["/usr/src/app/entrypoint.sh"] #docker-compose.yml version: '3.7' services: web: build: ./app command: python manage.py runserver 0.0.0.0:8000 volumes: - … -
Embed matplotlib bar graph in html page
I am trying to embed a matplotlib bar graph in html page. I have tried almost everything. here's my code- views.py- def result(request) plt.bar(x,h) plt.xlabel("Personality") plt.ylabel("course") plt.show() return render(request,'result.html') -
Django doesn't read JWT token
My django backend use JWT token for user auth. I store recieved token in 'Authtorization' header using axios. Everything works well. But I noticed problem when I open any link in new tab (ctrl+click), after this I get on to auth page but I still have the token in my header. Why does it happen? -
Empty space below navbar in header
I'm creating a web app using Python - Django. I'm currently working on the front-end part and below my navbar in the header section is a ton of free white-space that I can't seem to get rid off. Also I want my background image behind the whole page, can't seem to get my head around how to do that. It's always either above the body or below it. Any clues? My html with bootstrap: <!DOCTYPE html> {% load staticfiles %} <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> <meta name="author" content="Mark Otto, Jacob Thornton, and Bootstrap contributors"> <meta name="generator" content="Jekyll v3.8.5"> <link rel="stylesheet" type="text/css" href="{% static 'styles/stylesheet.css' %}"> <link rel="icon" href="{% static 'images/favicon.ico' %}"> <title> Milk - {% block title_block %}Milk Students{% endblock %} </title> <!-- Bootstrap core CSS --> <link href="https://getbootstrap.com/docs/4.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous"> <!-- Custom styles for this template --> <link href="https://getbootstrap.com/docs/4.2/examples/dashboard/dashboard.css" rel="stylesheet"> </head> <body> <header> <div class ="container"> <!-- Navbar --> <nav class="navbar navbar-expand-md navbar-dark fixed-top bg-dark py-1"> <a class="navbar-brand p-2" href="{% url 'milk_app:home' %}">MilkStudents</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarCollapse"> <ul class="navbar-nav ml-auto" > <li class="nav-item"><a class="nav-link" href="{% url 'milk_app:home' %}">Home</a></li> … -
Get All checkbox value selected , Table row wise using AJAX : DJANGO
I have code which should select all rows from a table whose checkbox is selected . So first i will describe my table structure . So here there will be many rows , so i should select which server i need and which operation i should perform . So if i have two server ABC and BCD , if i want to perform start operation for ABC and Stop for ABC , i should select respective servers from first checkbox and associated operations from the checkbox on same row as the server name . and i should pass all values row wise to views.py for performing other operations . so currently I wrote a code , which give me the value even if i didn't checked the checkbox . And am not able to figure out issue . Can any anyone help me. this is my AJAX call : $("[name=ButtonSubmit]").click(function(){ var myarrayServer = []; var myarrayStart = []; var myarrayRestart = []; var myarrayStop =[]; var message = " "; $(".form-check-input0:checked").each(function() { var row = $(this).closest("tr")[0]; message += row.cells[1].innerHTML; message += " " + row.cells[2].innerHTML; message += " " + row.cells[3].innerHTML; message += " " + row.cells[4].innerHTML; var checkedValue = … -
How to execute an if statement in ManyToMany Field in Django
I am trying to check if voter already exists in database and execute a different command id the voter exists or not but my if statement returns False if there is a match in the database. My views is: def vote(request, position_id, voting_id): voter = Voter.objects.filter(pk=voting_id) print(voter) position = get_object_or_404(Position, pk=position_id) try: selected_choice = position.candidate_set.get(pk=request.POST['choice']) except (KeyError, Candidate.DoesNotExist): return render(request, 'landing/detail.html', { 'position': position, 'error_message': "You didn't select a Choice." }) else: print(selected_choice.voted_by.all()) if voter in selected_choice.voted_by.all(): print("THIS DOES") else: print("THIS DOESN'T") # selected_choice.votes += 1 # selected_choice.save() return HttpResponseRedirect(reverse('results', args=(position.id,))) When I run this, I have some print statements and it prints; <QuerySet [<Voter: BIS/2019/12345>]> <QuerySet [<Voter: BIT/2020/54321>, <Voter: BIT/2019/12345>, <Voter: BIT/2018/12345>, <Voter: BIS/2020/54321>, <Voter: BIS/2019/12345>]> THIS DOESN'T I was hoping it will print 'THIS DOES' since the voter is in the selected_choice. What might I be doing wrong -
Django- ValueError: signal only works in main thread
is it at all possible to execute Django's call_command code within or alongside Django's signals? What I have tried so far is use a ModelForm to try and update a Model class using a function based views like so: # models.py class Foo(models.Model): ... many = models.ManyToManyField("FooMany") class FooMany(models.Model): ... many = models.CharField(choices=CHOICE, max_length=2) Now, every request to update this triggers a signal that's designed to run specific tests using Django's call_command # signals.py import ntpath from my_dir import execute @receiver(m2m_changed, sender=Executor.path.through) def run_test(sender, instance, action, **kwargs): files = instance.path.all() base = [ntpath.basename(str(f)) for f in files] for file in base: execute(file) # execute function comes next # my_dir.py def execute(file): with open("executor/results/output", "w") as FILE: call_command("test", f"executor.tests.{test}", verbosity=3, interactive=False, stdout=FILE) However, these all yield a server 500 error. Further investigation yielded a ValueError: signal only works in main thread, the reason I asked if it is possible to do it this way and if not could you suggest a different approach. Thank you. -
django model's inheritance
I want to have two registration type. for example : employee and employer type. i want two different form. i override AbstractUser and after i use this class (inheritance) class User(AbstractUser): age=models.BooleanField(default=True) class employee(User): is_employee=models.BooleanField(default=True) ser=models.BooleanField() sag=models.CharField(max_length=1) class Meta: verbose_name="employee" class employer(User): is_employer=models.BooleanField(default=True) address=models.CharField(max_length=100) but when i save employee or employer class also created User class. can i do when i save only employee save just that and not User -
django static png not found
when i go to localhost/static/images.png it shows image cannot be found i have added STATIC_URL = '/static/' staticfile_dir = [static_dir, ] please ignore .html and .css and .js file is polls folder already tried pycharms default path and base_dir then changed it to os.join also tried adding static file finder -
How to capture dropdown selection into a view for conversion to excel
Hello fellow learned friends. I'd like to add a filter to a model query from a dropdown selection before converting the results to excel for download. I can't get it right since I don't know how to capture the dropdown selected item into the view. How do I get it working?? def convert_to_excel(file_name, columns, values): response = HttpResponse(content_type='application/ms-excel') response['Content-Disposition'] = 'attachment; filename="{}.xls"'.format(file_name) wb = xlwt.Workbook(encoding='utf-8') ws = wb.add_sheet(file_name.capitalize()) # Sheet header, first row row_num = 0 font_style = xlwt.XFStyle() font_style.font.bold = True for col_num in range(len(columns)): ws.write(row_num, col_num, columns[col_num], font_style) # Sheet body, remaining rows font_style = xlwt.XFStyle() for row in values: row_num += 1 for col_num in range(len(row)): ws.write(row_num, col_num, row[col_num], font_style) wb.save(response) return response def archive_to_excel(request): mark_list = Marks.objects.filter(school=request.user.school).annotate(total = \ F("eng") + F("kis") + F("mat") + F("che") + F("phy") + F("bio") + F("cre")+ F("ire")+ \ F("hre") + F("geo") + F("his") + F("agr") + F("hsc") + F("bst")+ F("mus")+ F("ger")+ F("fre"))\ .order_by('-total').annotate(mean = F('total')/15).values_list('student__name',\ 'student__adm', 'student__form__name', 'student__stream__name', 'student__kcpe','eng','kis','mat','che','phy','bio','cre','ire','hre','geo',\ 'his','agr','total','mean').order_by('-id') columns = [('name'), ('adm'),('form'),('stream'), ('kcpe'), ('eng'), ('kis'), ('mat'), ('che'), ('phy'), ('bio'), ('cre'),\ ('ire'), ('hre'), ('geo'), ('his'), ('agr'),('total'),('mean') ] return convert_to_excel("Marks", columns, mark_list) -
How to filter objects according to the selected month in Django?
I have a Customer model. This model has a created_date field. I want to list all customers created in the selected month. I think I can use timedelta for that but I cannot figure out how can I applied that. How can I filtering the customers according to the selected month? views.py def log_records(request): .... form = MyForm() if request.method == 'POST': form = MyForm(request.POST) if form.is_valid(): cd = form.cleaned_data months = cd.get('months') selected_month = datetime.today() - timedelta(days=...somethin...) selected_month_customers = Customer.objects.filter(company=userP[0].company, created_date__gte=last_month.count() ... context = {'selected_month_customers': selected_month_customers,...} return render(request, 'logs.html', context) models.py class Customer(models.Model): ... created_date = models.DateTimeField(auto_now_add=True) ... forms.py class MyForm(forms.Form): MONTH_CHOICES = [ ('January', 'January'), ('February', 'February'), ('March', 'March'), ('April', 'April'), ('May', 'May'), ('June', 'June'), ('July', 'July'), ('August', 'August'), ('September', 'September'), ('October', 'October'), ('November', 'November'), ('December', 'December'), ] months = forms.CharField(widget=forms.Select(choices=MONTH_CHOICES), label="Select a month ") -
hardcoded url issue when drag & drop images with django-markdownx through S3
My website works perfectly fine with django-markdownx, unless I upload images. When I drag and drop image on markdownx form, auto generated image url is added in form like below: As you see, image is shown just fine. My storage is AWS s3, and I'm using private bucket. The problem occurs, however, an hour later. In the markdown url query parameter X-Amz-Expires=3600, which is an hour. So after that the url is no longer valid, saying request has expired. This is another expired url, but you get the idea. I use django-storages, boto3, AWS S3 for file storages. According to django-storages doc, AWS_QUERYSTRING_EXPIRE (optional; default is 3600 seconds) The number of seconds that a generated URL is valid for. I might extend expiry time like super long as suggested in other post in SO, but doesn't that mean I should update at least once every super long time period? That doesn't seem the right way. Some suggested making S3 bucket public, but I don't want allow anyone to download my image. I delved in django-markdownx doc and github, without making much progress. How can I get dynamically made presigned url when uploading image using djang-markdownx? Let me know if I'm … -
FieldDoesNotExist error with django-mongoengine?
I want to use mongoDB as my primary database in my new django (v 3.1.2) project. So far I have not created any models and only created a django project with one app and then installed pip install django-mongoengine. I then edited my settings.py file and included these custom codes. Mongodb is running as a service in my system. INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'home.apps.HomeConfig', 'django_mongoengine', 'django_mongoengine.mongo_auth', 'django_mongoengine.mongo_admin', ] # MongoDB settings MONGODB_DATABASES = { 'default': {'name': 'django_mongoengine'} } DATABASES = { 'default': {'ENGINE': 'django.db.backends.dummy'} } AUTH_USER_MODEL = 'mongo_auth.MongoUser' AUTHENTICATION_BACKENDS = ( 'django_mongoengine.mongo_auth.backends.MongoEngineBackend', ) SESSION_ENGINE = 'django_mongoengine.sessions' But when I started my server python manage.py runserver I am getting this error File "/home/Eka/.virtualenvs/Env/lib/python3.6/site-packages/django_mongoengine/forms/document_options.py", line 4, in <module> from django.db.models.fields import FieldDoesNotExist ImportError: cannot import name 'FieldDoesNotExist' I also tried to import django_mongoengine using a different terminal, which also yield the same error. How can we solve it? -
Django: How to retrieve a Queryset of the latest, uniquely named records with a MySQL database
I require a query that can search my model for the latest, unique records and return a queryset of the results. I need distinct on setup_name and latest on updated models.py class VehicleSetupModel(models.Model): inertia = models.IntegerField() tyre_pressure = models.IntegerField() class StandardVehicleSetupModel(VehicleSetupModel): setup_name = models.CharField(max_length=20) updated = models.DateTimeField(auto_now=True) vehicle = models.ForeignKey(VehicleModel, on_delete=models.CASCADE) What I've tried I tried the following: StandardVehicleSetupModel.objects.all().order_by('updated').distinct('updated') but MySQL does not support DISTINCT ON querys. Table Layout (DD-MM-YYYY) setup_name | updated | vehicle ---------------------------------------------------------- TEH 10-10-2020 1 TEH 11-10-2020 1 TEL 10-10-2020 1 TEL 08-10-2020 1 TEL 01-10-2020 1 TEP 01-10-2020 1 Expected Result (DD-MM-YYYY) setup_name | updated | vehicle ---------------------------------------------------------- TEH 11-10-2020 1 TEL 10-10-2020 1 TEP 01-10-2020 1 -
import models from another directory
I'm new in Django. i am following a tutorial and now i have a problem . my directory tree is like and in /pages/views i have this from django.http import HttpResponse from django.shortcuts import render def home_view(*args, **kwargs): return "<h1>Hello world</h1>" and in urls.py i have this from django.contrib import admin from django.urls import path from pages.views import home_view urlpatterns = [ path('', home_view, name='home'), path('admin/', admin.site.urls), ] ***but it can't recognize pages *** i also tried these solution but didn't work!what do i missing? even i added these codes to settings.py import os import sys BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.append(os.path.join(BASE_DIR, 'pages')) { django 3.1 } -
django- django admin Modify External Model Field Name
I added fields from existing models(ProUser), fields from external models(Point) to Admin. @admin.register(ProUser) class ProUserAdmin(admin.ModelAdmin): list_display = [ "id", "user_nm", "user_ty", "user_tel", "user_email", "point_amt", **One of the fields in the 'Point' model, not in the 'ProUser' model** "user_join_dts", ] In ProUser's model, [user_nm = models.CharField ("app user name", max_length=10)] As such, the field name "app user name" was specified. Therefore, the field name appears to be [app user name] instead of [user name] in Admin. As such, I would like to name the fields imported from the Point model. For now, [pointamt] is the name of the field. I want the field "point_amt" to be the field name "user point" in Admin. Is there a way? -
django_filters pass arguments (choices) to FilterSet
I am building an Electronics e-commerce website with Django. I am struggling with django_filters. I have models Category, Subcategory and Product. When user visits Category Page I would like to render Product brands filter depending on that Category. For example, if user visits Phone Category I would like to render brands filter: Apple, Samsung, Xiaomi etc. I achieved something similar like that but downside is it shows all brands (product brands not related to Category): Canon, Samsung, Apple, Bosch etc. So I am trying query Product brands related to that Category and pass them as choices to Filterset. How can I pass brand choices from view to FilterSet? #===models.py===== class Category(models.Model): title = models.CharField(max_length=30, verbose_name=_('Названия')) slug = models.SlugField(null=False, unique=True) image = models.ImageField(blank=True, upload_to='category_images/', verbose_name=_('Основное фото')) created_at = models.DateTimeField(auto_now_add=True, verbose_name=_('Добавлено в')) updated_at = models.DateTimeField(auto_now=True, verbose_name=_('Изменено в')) class Subcategory(models.Model): category = models.ForeignKey(Category, related_name='subcategories', null=True, blank=True, on_delete=models.SET_NULL, verbose_name=_('Категория')) title = models.CharField(max_length=150, blank=True, verbose_name=_('Названия')) image = models.ImageField(blank=True, upload_to='subcategory_images/', verbose_name=_('Основное фото')) slug = models.SlugField(max_length=150, unique=True) created_at = models.DateTimeField(auto_now_add=True, verbose_name=_('Добавлено в')) updated_at = models.DateTimeField(auto_now=True, verbose_name=_('Изменено в')) class Product(models.Model): recommended_choices = (('YES', 'ДА'), ('NO', 'НЕТ')) title = models.CharField(max_length=200, blank=True, verbose_name=_('Названия')) category = models.ForeignKey(Category, related_name='category_items', on_delete=models.SET_NULL, null=True, blank=True, verbose_name=_('Категория')) subcategory = models.ForeignKey(Subcategory, related_name='subcategory_items', on_delete=models.SET_NULL, blank=True, null=True, verbose_name=_('Подкатегория')) price … -
trying to get my views.py and urls.py to work properly
I am currently trying to get my database that I created to display on my Djnago server however I keep getting errors for my FruitModel saying that there are no objects however I have created objects for the FruitModel in my datbase using "record = FruitModel.objects.create(name='banana', price='4.00'). I am also getting an unable to display error for my urls when I loaded up my server. Here is my code for Views.py and for urls.py: (views.py code) from django.shortcuts import render, redirect from catalog.models import FruitModel from catalog.forms import FruitForm from django.http import HttpResponse # Create your views here. def FruitView(request): fruit = FruitModel.objects.all() html = '' for fruits in fruit: var = f'<li> {fruits.name} </li><br>' html = html + var return HttpResponse(html,status = 200) def FruitIDView(request,name): fruits = FruitModel.objects.get(name = f'{fruits.name}') html = f'<h2>{fruits.name}</h2><br>' return HttpResponse(html, status=200) (urls.py code) from django.contrib import admin from django.urls import path from django.conf.urls import url from catalog import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^FruitView/?$', views.FruitView), ] -
Django: best way to redirect empty results pages to root page
I have an app that paginates and show objects in a Django list view. I'm using paginate_by=20 in my list view. When I have 20+ objects and Google indexes the second results page /results/?page=2. Then when results go below 20 objects, this second page goes to 404. What is the best way to redirect page 2 to /results/ when page 2, 3 etc don't return any results. I thought about writing a custom 404 view to strip out the URL parameters, but I guess it's best to catch this in the list view itself? -
Iterating a Django Form over a FileField which accepts multiple file uploads
I have a list containing files (say images) uploaded by a user. I need a user input against each file (say if he likes the image or not). User input can be collected through Django Forms. How can I do this if I need to : In a single view and URL Saving user input relative the file in the database I am only struggling with looping through the files in a single view and saving user inputs. -
Automatically updating a model field when it is created
I would like to automatically update a model field when it is created. So this is my situation. I have a custom User model that my customer can use to login. After they login, they will go to the account/profile page, which has a link to a form. Currently, when the user submits the form, it creates an instance of the LevelTest model(which is something I just need for the website to work). Here is the view class for the form: class LevelTestView(generic.CreateView): template_name = "leads/leveltest.html" form_class = LevelTestModelForm def get_success_url(self): return reverse("profile-page") and here is the LevelTestModelForm: class LevelTestModelForm(forms.ModelForm): class Meta: model = LevelTest fields = ( 'first_name', 'last_name', 'age', 'username', ) What I want to fill in automatically is the username field. In fact, I wish it doesn't even show up on the form itself when the user types in. The username is a field in the User Model, so I just want the new LevelTest's username field filled in with the current user's username. Hence, I used a post_save signal like below(which doesn't work): def post_leveltest_created_signal(sender, instance, created, **kwargs): if created: instance.objects.update( username=instance.user.username, description='Add Description', phone_number=instance.user.cellphone, email=instance.user.username, ) post_save.connect(post_leveltest_created_signal, sender=LevelTest) I hope you guys could help me … -
how to send an alert message to other web page when any model field in changed
i have an model in django with name offer : class Offer(models.Model): Auction_id=models.CharField(max_length=20,verbose_name = "Auction ID",default=number) Offer_Name=models.CharField(max_length=200,verbose_name = "Auction Name") Auction_des=models.CharField(max_length=50,verbose_name = "Auction Description") Bid_Start_Time=models.TimeField(auto_now=False, auto_now_add=False) Bid_End_Time=models.TimeField(auto_now=False, auto_now_add=False) and I have a Bid web page displaying details related to offer. I want to display an alert message to Bid web page everytime Bid end time in offer is changed. Through init and save method in offer i can check whether Bid end time is modififed or not but i'm not able to display alert message in Bid web page. -
How to decide where to put a function in django fat model implemantation
I want to know where to put a function on models that related to multiple models. I have four models: 1- custom user 2- office 3- company 4- vehicle every vehicle, user and office has a foreign key to company. I want to have all vehicles from a company I have tried to put a staticmethod on vehicles to get appropriate vehicles but I am not sure this is the right way of doing things because I have to pass request to models. @staticmethod def get_current_company_vehicles(request): Vehicle.objects.filter( located_office__in=CompanyOffice.objects.filter(company=request.user.company).values_list('pk') ) Where would you guys put the function and how to decide where a functions should go? -
Spring password encoder for the default Django password format (pbkdf2_sha256)
I am working on a Spring Boot application using Spring Security connected to a database originally generated by Django, in which all of the user passwords are stored in Django's pbkdf2_sha256 format. <algorithm>$<iterations>$<salt>$<hash> Looking at Spring Security's Pbkdf2PasswordEncoder, I was able to mostly figure it out and create an encoder that is able to encode and match Django's format. After successfully unit testing it, I tried it on a sample value generated by Django... and it failed. Why is this encoder not matching Django-generated values? Is Django performing some ~magic~ under the hood? I have also tried multiple replacements for Java's SecurityFactory implementation. This line in Django's source code caught my attention as well, but writing the equivalent Kotlin did not fix the issue. class DjangoPbkdf2PasswordEncoder : PasswordEncoder { companion object { private const val PREFIX = "pbkdf2_sha256" private const val SEPARATOR = "\$" private const val ITERATIONS = 180000 private const val HASH_WIDTH = 256 private const val ALGORITHM = "PBKDF2WithHmacSHA256" } private val saltGenerator: BytesKeyGenerator = KeyGenerators.secureRandom() private fun base64Decode(string: String): ByteArray { return Base64.getDecoder().decode(string) } private fun base64Encode(bytes: ByteArray): String { return Base64.getEncoder().encodeToString(bytes) } override fun encode(rawPassword: CharSequence): String { val salt = saltGenerator.generateKey() val hash = … -
To add values to a django model while I add value to another model
Let's say I have a model 'Books' and another model 'Products'. When I add a Book from django admin, I want the Book name and Book Code to be added to the Model 'Products'.