Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to pass an id of specific item
I am trying to pass an id to page where I would be able to change the data of that item. I have a page, where I am displaying all instances of specific item: {% for copy in bikeloan.bikeinstance_set.all %} <hr> <p class="{% if copy.status == 'a' %}text-success{% elif copy.status == 'm' %}text-danger{% else %}text-warning{% endif %}"> {{ copy.get_status_display }} </p> {% if copy.status != 'a' %} <p><strong>Due to be returned:</strong> {{ copy.due_back }}</p> {% endif %} <p><strong>Frame number:</strong> {{ copy.imprint }}</p> <p class="text-muted"><strong>Id:</strong> {{ copy.id }}</p> <a href="{{ copy.get_absolute_url }}">Loan</a> {% endfor %} I get a couple of results and I wanna be able to click on button loan and pass the id of that particular instance to new page. I have that in my models: class BikeInstance(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, help_text='Unique ID for this particular bike across whole stock') bike = models.ForeignKey('BikeLoan', on_delete=models.SET_NULL, null=True) frame_number = models.CharField(max_length=200) due_back = models.DateField(null=True, blank=True) borrower = models.ForeignKey( User, on_delete=models.SET_NULL, null=True, blank=True) def get_absolute_url(self): return reverse("core:loan-user", args=[str(self.pk)]) and my urls: path('loan-user/<int:pk>', loan_bike, name='loan-user'), views.py: def loan_bike(request, pk): bikeloan = get_object_or_404(BikeInstance, pk=pk) return render(request, 'loan_user.html', context={'bikeloan': bikeloan}) When I enter a page, where all the instances are displayed I get that error: … -
Why isn't the related_name working for models?
There are question and answer tables related to each other. Each question has one answer. I need to check the answer field in the CompanyGeneralInfoAnswers model. class CompanyGeneralInfoQuestion(models.Model): rfi = models.ForeignKey(Rfis, models.DO_NOTHING) question = models.CharField(max_length=512) class Meta: db_table = 'company_info__questions' class CompanyGeneralInfoAnswers(models.Model): question = models.OneToOneField('CompanyGeneralInfoQuestion', models.DO_NOTHING, related_name='answer_to_question') answer = models.CharField(max_length=4096, blank=True, null=True) class Meta: db_table = 'company_info_answers' To do this, I make this request. round = kwargs.get('rfiid') exist_company_question = CompanyGeneralInfoQuestion.objects.filter(rfi=round) if exist_company_question: for q in exist_company_question: print(q.answer_to_question.answer) But got an error RelatedObjectDoesNotExist: CompanyGeneralInfoQuestion has no answer_to_question. -
Return can close Loop for? (python/django)
Does return on python close the Loop for? I'm asking that because I wrote a code that will search for me someone in a list and if know that person it will return me his age if not it will tell me "Person not found". If the person is in the first place of the Array if find it but if it is in the second he doesn't why? def lerDoBanco(name): lista_names = [ {'name': 'Joaquim', 'age': 20}, {'name': 'João', 'age': 25}, {'name': 'Ana', 'age': 27} ] for person in lista_names: if person['name'] == name: return person else: return {'name': 'Person not found', 'age': 0} def fname(request, name): result = lerDoBanco(name) if result['age'] > 0: return HttpResponse('The person was found, has ' + str(result['age']) + ' years old') else: return HttpResponse('Person not found') I ask that because if I comment the else statement it shows me all the people in the Array correctly. -
Pycharm Can't retrieve image ID from build stream
Want to connect pycharm docker interpreter. Here is my windows docker status and here is pycharm status how can I fix the issue -
How can i remove the name's field on the screen?
I have 2 question on the same subject if someone can help me please: 1.I display a form with django and i wanted to to remove the name of my field: Here is what the screen display : display and i want to remove "Columns:". Here is my form: class Features(forms.Form): columns = MultipleChoiceField(choices=FEATURES_CHOICES, widget=forms.CheckboxSelectMultiple) and here is my template: <form method="POST"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="save"> </form> and here my view: def ChoiceView(request): context = {'form': forms.Features()} return render(request, 'data/home.html', context) Where I recover my result of selections or where go the results ? In which variable of which file (models, views,..) will go the results ? -
Token authentication for django channels
im trying to integrate React , django and django channels together , however im facing some trouble trying to authenticate the socket connection. There are some posts over here: first link enter link description here But they do not talk about how to utilize it over the front end portion. There are some posts which recommends to put the token within the URL , for example : WebSocket('wss://example.com/my-ws-endpoint/?token=' + token, ...) But there seems to be lots of security red flags in doing so. Therefore is there a simple easy way to resolve the token authentication issue for channel websockets here? -
Css not loading in Django
My css file is not getting loaded in the webpage. I have css and image file in the same location. The image is getting loaded but not the css.Also I have included the directory in staticfile_dirs. Setting.py import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '(9szxe#x0q67)^wc6us01*i$=1)!&f7)530%73=pvzzhwp23gp' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'technicalCourse.apps.TechnicalcourseConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'website.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ r'C:\Users\Kesavan\PycharmProjects\Django web development\website\technicalCourse\template' ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'website.wsgi.application' # Database # https://docs.djangoproject.com/en/3.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/3.0/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE … -
Router not displaying correct URL in Django RestFramework?
This is how I defined urls.py file of my app router = DefaultRouter() router.register('hello-viewset', views.HelloViewSet, base_name='hello-viewset') router.register('profiles', views.UserProfileViewSet) router.register('schema', views.SchemaViewSet) router.register('creddefination', views.CredDefViewSet) router.register('overalltable', views.OverallViewSet) urlpatterns = [ path('', include(router.urls)), ] urls.py of Project: urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('DIAPI.urls')), ] I am not getting correct address for creddefination. But when i manually go to http://127.0.0.1:7000/api/creddefination/ it is working. It is just not displaying correctly. What might be reason for this -
Get overview of SQL query count for every test in a test suite
I have a large Django application with tons of tests that need SQL query optimizations. I don't want to add assertNumQueries or django-assert-num-queries for each test individually, but instead produce an overview about how many SQL queries each one of all of the tests are triggering, to know which code needs the most optimization, like this: test | number of queries ------------------------------------------------ test_a.py::test_my_function1 | 5 test_a.py::test_my_function3 | 2 test_a.py::test_my_function5 | 7 Is it possible to configure a pytest hook in conftest.py which counts the number of SQL queries for each (DB) test and shows them in result - without the need to modify the source of my tests (like adding decorators)? -
Django : How to convert pdf file object to image using pdf2image?
I am trying to create a epaper web app, in which admin can upload file in pdf format and which is converted to image while rendering the page from client side. I have tried pdf2image but getting error something like this : PDFPageCountError at /city_list Unable to get page count. I/O Error: Couldn't open file '['/media/pdf/Akola/2020/04/24/page01.pdf']': No such file or directory. here is my code: models.py class City(models.Model): cityid =models.AutoField(primary_key=True) name = models.CharField( max_length=50) def user_directory_path(instance, filename): # file will be uploaded to MEDIA_ROOT/user_<id>/<filename> ab = instance.date.strftime("%Y/%m/%d") return 'pdf/{0}/{1}/{2}'.format(instance.city.name,ab, filename) class DailyFeed(models.Model): city = models.ForeignKey(City, on_delete=models.CASCADE) date =models.DateField(auto_now=False, auto_now_add=False) page1 = models.FileField(upload_to=user_directory_path) page2 = models.FileField(upload_to=user_directory_path) page3 = models.FileField(upload_to=user_directory_path) views.py: def city(request): city_list = City.objects.all() daily = DailyFeed.objects.filter(date=timezone.now().date()).filter(city__name = "Akola") ab = [pdfurl.page1.url for pdfurl in daily ] path = r'{}'.format(ab) a = str(path) pages = convert_from_path('{}'.format(a), 200) for pdf in pages: pdf.save('{}.jpg'.format(a.name[:-4]), 'JPEG') return render (request,'main.html',{'city_list':city_list,'page':pdf}) urls.py re_path(r'^city_list',views.city,name='city'), I am have not getting where I am going wrong? -
How to change main folder name permamently in django
I want to change main folder name in django(folder with manage.py), because I think current title makes some issues while i try run it on Heroku ("app crashed"). Current title: ShoppingList 2.0 But when i change it to for example ShoppingList2, in PyCharm it looks like this: I want to have only "ShoppingList2" without old name in brackets. -
DJANGO 3.0.5 AUTH_USER_MODEL refers to model 'auth.UserManager' that has not been installed
I know that this question may be a duplicate, but not a single answer on comment on other questions like this has not worked for me. So I am developing django app for online learning, like online school. At first I used Django built in Users (for test), ant the I switch to custom users.When I try to python manage.py makemigrations, it fails with the following error: https://pastebin.com/AMcjgY0y. So my auth/models.py: from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin from django.utils import timezone class UserManager(BaseUserManager): def _create_user(self, email, password, is_admin, is_staff, **extras): if not email: raise ValueError('Potrebno je unijeti email adresu') email = self.normalize_email(email) user = self.model( email = email, is_staff = is_staf, is_active = True, is_admin = is_admin, last_login = timezone.now(), date_joined = timezone.now() **extras ) user.set_password(password) user.save(using=self._db) return user def create_user(self, email = None, password = None, **extras): return self._create_user(email, password, False, False, **extras) def create_admin(self, email, password, **extras): return self._create_user(email, password, True, True, **extras) user.save(using=self._db) return user class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length = 200, unique = True) name = models.CharField(max_length = 200, null = True, blank = True) is_staff = models.BooleanField(default = False) is_admin = models.BooleanField(default = False) last_login = models.DateTimeField(null = True, blank … -
How can I change the value of a Django model field when a particular choice is selected?
I created a model on django for blog posts. Each post has two status choices: Publish or Draft. How can i change Publish to Published after the post is saved? This is my code: from django.db import models from django.contrib.auth.models import User Create your models here. STATUS = [ (0,"Draft"), (1,"Publish"), ] class Post(models.Model): title = models.CharField(max_length=200) slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts') updated_on = models.DateTimeField(auto_now=True) content = models.TextField() created_on = models.DateTimeField(auto_now_add=True) status = models.CharField(max_length=1,choices=STATUS) class Meta: ordering = ['-created_on'] def __str__(self): return self.title from django.contrib import admin from .models import * Register your models here class PostAdmin(admin.ModelAdmin): list_display = ('title','slug','status','created_on',) list_filter = ("status",) search_fields = ('title', 'content') prepopulated_fields = {'slug': ('title',)} admin.site.register(Post,PostAdmin) -
Django Celery High Memory Usage
I have a fairly simple Django app that checks an API, the API basically runs a task, some of these tasks can last from a few seconds to a whole day. my Django app checks this API for the status of the task every 30 seconds using celery if the status is pending it checks again until the status == completed, the issue I am having right now is Celery uses about 300MiB/1.94GB of memory for this, and I end up having other tasks blocked, I am also trying to scale up as I have multiple of this app running on my Docker container, adding more workers won't solve my problem as this will increase the memory footprint as I deploy more instances of my app. How can I reduce the memory footprint of celery -
Django, is it possible to create hierarchical status choice with a model?
I have created a form that give the possiblity to the users to select a choice from a multiple choices and based on your choice can select the second form. The latter changes based on the first choice. The structure of my dataset is the following: -ProductA: -->sub_product_a_1 -->sub_product_a_2 -->sub_product_a_3 -ProductB: -->sub_product_b_1 -->sub_product_b_2 -->sub_product_b_3 So if the client choose in the first box form Product A, in the second box can choose only sub_product_a_1, sub_product_a_2 sub_product_a_3. I only just managed to create the two different levels of choice, but I haven't been able to create a new model that summarize all product and sub product created in a single table like this: Product | Sub_Product Product A | sub_product_a_1 Product A | sub_product_a_3 Product B | sub_product_b_1 Product A | sub_product_a_2 here my code models.py class Product(models.Model): slug = models.SlugField() product_category = models.CharField() class Subproduct(models.Model): product_category = models.ForeignKey() sub_product_category = models.CharField() Class Inventory(models.Model): category= models.ForeignKey(Product) sub_category= models.ForeignKey(Subproduct) -
My questions disappeared in my index page (Django polls project)
I followed a tutorial on YouTube and my website showed the questions below as bullet point links on the index page: "What's your name?" "what's your age?" I think I may have deleted some part of the code by accident, as the header and footer still appear. Should it be in the index page? attached below: {% extends 'polls/base.html' %} {% block main_content %} <h1 class="display-3">Choose a question</h1> {% if latest_questions %} <ul> {% for question in latest_question %} <li><a href= '/polls/{{question.id}}'><b>{{question.question_text}}</b></a></li> {% endfor %} </ul> {% else %} <p>You don't have any questions. Please add some. </p> {% endif %}[enter image description here][1] {% endblock %} Thank you! -
Query a manytomany relationship
I have two models in my app like this: class Foo(models.Model): name = models.CharField(max_length=50) age = models.IntegerField() def __str__(self): return self.name class Bar(models.Model): bar_name = models.CharField(max_length=100) bar= models.ManyToManyField(Foo) def __str__(self): return self.bar_name and there is a Bar pk (let's say 1) How can I get all the related objects of Foo with Bar id 1 ? -
Getting the homepage data refresh every time user refresh or login in django
How can I change the data of my homepage while refreshing every time or login into Django using machine learning? I have made the model that can recommend using movie_datasets which recommend the movie but I don't know how can I implement it in Django how and to make it dynamic every time while a refreshing or new user is logged in and showing the title of the movie using bootstrap. -
CSRF_Token in POST method using Vue.js and Django Rest Framework
I'm trying to send a POST request from a Vue.js template to my API created with Django. When sending I get a 403 CSRF token missing or incorrect error. Since I separated the front and the back, I don't have a view with {csrf_token} on the Django side. How do I send my form? I tried some exemples on the web using cookies but i'm beginners and need more explaination about the POST subject and CSRF -
Django:What is best way to import my Custom-User in views.py?
Actually i have created my own custom-user (MyUser) in models.py from django.db import models from django.contrib.auth.models import AbstractUser class MyUser(AbstractUser): country=models.CharField(max_length=20) settings.py AUTH_USER_MODEL = 'new_user.MyUser' I created a simple function in views.py to create new users. from django.shortcuts import render,redirect from django.http import HttpResponse from django.contrib.auth import get_user_model from django.conf import settings def save_account(request): MyUser=get_user_model() if request.method == "POST": name=request.POST.get("name") email=request.POST.get("email") password1=request.POST.get("password1") password2=request.POST.get("confirm-password") country=request.POST.get("country") new_user=MyUser.objects.create_user(username=name,email=email,password=password1,country=country) new_user.save() return redirect('/') else: return HttpResponse("404 Not Found") 1. Here i use get_user_model() function to get my currently custom-user. 2. I have second option to get my custom user just by importing MyUser model from models.py and then use it. from .models import MyUser 3. I have third option to get custom-user just by importing AUTH_USER_MODEL directly from settings.py and use it like in this way. from django.conf import settings MyUser=settings.AUTH_USER_MODEL but third option returning a string instead of returning my custom-user.but why? I just want to know that which option is best to import custom-user in views.py and why? -
How to change title for the tab of change list page of django admin
I'm working on Django and wanted to change the default title for the tab of change list page of Django admin as marked in the pic : my admin.py file is : from django.contrib import admin from django.contrib.auth.admin import UserAdmin from .models import CustomUser class CustomUserAdmin(UserAdmin): change_list_template='change_list_form.html' change_form_template = 'change_form.html' add_form_template='add_form.html' list_display = ('first_name','last_name','email','is_staff', 'is_active',) list_filter = ('first_name','email', 'is_staff', 'is_active',) search_fields = ('email','first_name','last_name','a1','a2','city','state','pincode') ordering = ('first_name',) add_fieldsets = ( ('Personal Information', { # To create a section with name 'Personal Information' with mentioned fields 'description': "", 'classes': ('wide',), # To make char fields and text fields of a specific size 'fields': (('first_name','last_name'),'email','a1','a2','city','state','pincode','check', 'password1', 'password2',)} ), ('Permissions',{ 'description': "", 'classes': ('wide', 'collapse'), 'fields':( 'is_staff', 'is_active','date_joined')}), ) So is there any way so that it can be changed?? Thanks in advance!! -
one to many or many to many relationship in DJANGO
I wanna try to build a relationship between an employee and an area. Each employee has to visit more than one area and the area depends on the city. I built a relationship between city and area with a foreignkey(many-to-one). I have to add more than one areas to single employee however, I used manytomany relationship between employee and area. At the time of employee registration when I select city from "City" dropdown the list of the area is not altered. All the areas are shown. This is my Employee form class EmployeeForm(forms.ModelForm): class Meta(): model =Employee fields = ('code','first_name','last_name','designation','report_to','join_date','leave_date','city','area','username','password','status','address') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['area'].queryset = Area.objects.none() if 'city' in self.data: try: city_id = int(self.data.get('city')) self.fields['area'].queryset = Area.objects.filter(city_id=city_id).order_by('name') except (ValueError, TypeError): pass # invalid input from the client; ignore and fallback to empty City queryset elif self.instance.pk: self.fields['area'].queryset = self.instance.city.area_set.order_by('name') and models are class Employee(models.Model): code = models.CharField(max_length = 256) # name = models.CharField(max_length = 256) designation =models.ForeignKey(Designation,on_delete=models.CASCADE) report_to = models.ForeignKey('self', null=True, blank=True, on_delete=models.CASCADE) area = models.ManyToManyField(Area, through ='EmployeeArea',) city = models.ForeignKey(City, on_delete=models.CASCADE, null=True, blank=True,) status = models.BooleanField(default = True) join_date = models.DateField(default=datetime.datetime.now) leave_date = models.DateField(blank = True, null=True) username = models.CharField(max_length = 256) password = models.CharField(max_length = … -
Ngnix redirect for Mouseflow to remove Django staticfiles MD5 hash
Mouseflow recordings issue I have an issue with Mouseflow and the way that it displays "recordings". Mouseflow recordings capture and store the mouse movement of users at a particular time, and also the HTML of the page that they were interacting with. However, Mouseflow does not store the associated static assets that the site uses, such as CSS, JavaScript, or image files such as logos, icons etc. - these are loaded again at the time the recording is played back via the Mouseflow admin panel. Django static assets Apart from CMS-generated media (such as uploaded images and documents), Django's static file assets are collected each time there is a new code deployment, and processed to add MD5 hashes to the end of the filename, preceding the file extension. Example static file URL before processing: https://example.com/assets/css/screen.min.css Example static file URL after processing: https://example.com/assets/css/screen.min.87f74c1e97de.css When Mouseflow generates a recording, the HTML refers to the static asset filenames at the time of the interaction. If a recording is viewed at a later date and the static assets have been changed and re-deployed, the filenames will no longer exist. This issue is documented here on the Mouseflow support site. As suggested in the support … -
How filter queryset by multiple ID
My objective is to get the id and make a queryset filtered by id, as in the following code: view.py class CustomViewSet(viewsets.ModelViewSet): serializer_class = ProductSerializer queryset = product.objects.all() def list(self, request, *args, **kwargs): products = self.queryset orders = order.objects.all() order_serializer = OrderSerializer(orders, many=True) product_serializer = self.get_serializer(products, many=True) custom_response = [order_serializer.data, product_serializer.data] return Response(custom_response, status=status.HTTP_200_OK) urls.py from django.urls import path, include from list import views from rest_framework.routers import DefaultRouter router = DefaultRouter() router.register(r'all', views.CustomViewSet, basename='product') urlpatterns = [ path('', include(router.urls)) ] in this code there are two mode and two serializer class in one one viewset my task is how to get all data by id using one api hit -
Automatic publication of a post
In my blog I've a filter that put online only the posts that aren't draft and that aren't published in the future. models.py class BlogPost(models.Model): title =.... .... publishing_date = models.DateTimeField( default=timezone.now, ) draft = models.BooleanField( default=False, ) views.py @api_view(["GET"]) def blogPost_apiview(request): if request.method == "GET": objects = BlogPost.objects.filter(Q(draft=False) & Q(publishing_date__lte=datetime.now())) serializer = BlogPostSerializer(objects, many=True) return Response(serializer.data) I've seen that when the post goes from future to past it is not put online. I can see the post online only if I change manually the publishing date and time and save it. How can I make it happen automatically?