Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to add same variable in different files and folders?
I am working on a Django project that has lots of different files and folders. For processing there is a queue that has different queue names depending on the usage. For changing the name of the queue one must go through every single files in every single folder and change the name 1 by 1 manually. How can i use a global variable that can be assessed from anywhere in the program even directories that are beyond and below the current file? So that i need to change only the variable name and every queue name in the project will get changed -
Convert data of type time inside array to int or float. Error: unsupported operand type(s) for +: 'int' and 'numpy.str_'
def ProdGrafico(request): ## Dados Media Duracao do Forno mediaForno = Relatorioresumido.objects.all() divideForno = len(mediaForno) listMediaForno = [] for x in range(int(divideForno)): y = mediaForno[x].duracaoforno y = datetime.strptime(y, '%H:%M:%S') listMediaForno.append(y) try: mediaForno = listMediaForno[0] + sum((listMediaForno_i - listMediaForno[0] for listMediaForno_i in listMediaForno), timedelta(0)) / len(listMediaForno) print(mediaForno) except ZeroDivisionError: mediaForno = 00 -
how do i serve media files when going through a url? django
i have a django project where i need to serve media files. i have one url that serving media files works on and one the doesn't. the one that doesn't has a search/ placed in front of it and i assume thats the reason it can't find the media files. i use the search url in other parts of my program and don't want to break the other parts my changing it. is there anyway i could stop the search/ from appearing without changing the url pattern? blue is when the media files are collected and yellow is when its not working -
NameError at /post/category/
I catch an error, where exactly I found it, but I don’t understand what to do. models.py 'from django.contrib.auth.models import User from django.db import models class Post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True) title = models.CharField(max_length=255) text = models.TextField() created_date = models.DateTimeField(auto_now_add=True) views = models.PositiveIntegerField(default=0) like = models.PositiveIntegerField(default=0) enabled = models.BooleanField(default=False) category = models.ForeignKey( "Category", on_delete=models.CASCADE, blank=True, null=True) def __str__(self): return f'{self.title}' class Comment(models.Model): post = models.ForeignKey( Post, on_delete=models.PROTECT, blank=True, null=True) author = models.ForeignKey( User, on_delete=models.CASCADE, blank=True, null=True) text = models.TextField() created_date = models.DateTimeField(auto_now_add=True) def __str__(self): return f'{self.text}' class Category(models.Model): title = models.TextField() enabled = models.BooleanField(default=False) def __str__(self): return f'{self.title}' veiws.py 'from blog.forms import PostForm from blog.models import Post from django.http import Http404 from django.shortcuts import get_object_or_404, redirect, render # Create your views here. def post_list(request): posts = Post.objects.filter(enabled=True) return render(request, "blog/post_list.html", {"posts": posts}) def post_detail(request, post_pk): post = get_object_or_404(Post, pk=post_pk) post.views += 1 post.save() return render(request, "blog/post_detail.html", {"post": post}) def post_new(request): if request.method == "GET": form = PostForm() return render(request, "blog/new_post.html", {"form": form}) if request.method == "POST": form = PostForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.author = request.user post.save() return redirect('post_detail', post_pk=post.pk) def post_edit(request, post_pk): post = Post.objects.filter(pk=post_pk).first() if not post: raise Http404("Post not found") if request.method == "GET": … -
How to save multipart / formdata turned into a QueryDict using Django REST Framework (DRF) and ModelSerializer
I am sending multipart/formdata from a Next.js API and I can format the data whichever way I want but I am struggling to get the right format. For now, I have the following formdata: <QueryDict: { 'name': ['Test Product'], 'brands[0]': ['1'], 'brands[1]': ['2'], 'option_types[0]': ['1'], 'product_variants[0]option_values[0]': ['1'], 'product_variants[0]option_values[1]': ['2'], > My ModelSerializer is not accepting the way I am specifying the lists/arrays. For instance, if I try to do: def validate_option_types(self, data): print(data) return data I get an empty list meaning the format for option_types list is wrong and the same applies for the product_variants and option_values. I am simply passing the QueryDict obtained from request.data as follows: def create(self, request, *args, **kwargs): serializer = ProductDetailAdminSerializer(data=request.data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data) return JsonResponse(serializer.errors, status=400) The serializer and everything else are working fine if I use a JSON version of the QueryDict above and the JSON content-type. So to summarise my question, what is the correct QueryDict format (specifically for fields which represent lists) for the DRF ModelSerializer? Or is there an extra step that I am missing in getting the QueryDict to the format expected by the model serializer. -
Can graphene resolver return Float instead of String for django Decimal field?
Graphene's resolver returns my django model Decimal field as a string (e.g. "8.33" instead of 8.33). I want to receive it as a float. Is there some way to do this? My code is as follows: models.py class Toy(models.Model): name = models.CharField(max_length=50) price = models.DecimalField() queries.py class ToyType(DjangoObjectType): class Meta: model = Toy fields = ('name', 'price') class ToyQuery(graphene.ObjectType): first_toy = graphene.Field(ToyType) def resolve_first_toy(self, info): return Toy.objects.first() And my query and result are: query { firstToy{ name price } } result { "data": { "name": "BuzzLighYear", "price": "19.95" } } Instead, I would like to receive: { "data": { "name": "BuzzLighYear", "price": 19.95 } } Do I have to write a custom resolver for the price field, or is there a more elegant way to do this with a setting? -
NameError at / name 'RequiredDocument' is not defined
All the code works perfectly fine on the localhost and the same code gives the above error on a hosted website with the same code. I reran migrations also but still got the same error. -
How can I use Linkify with Django_tables2
I have read a few similar questions and all the docs I can find on this but I am still not able to understand the solution. I have built my model to have a player, the text description of a keyboard and a url to it. I want to show in a table the player, the keyboard and i want to have the keyboard text have the url column embedded within it. Any help would be appreciated. Models.py: class player_hardware(models.Model): Player = models.TextField(blank = False, primary_key = True) keyboard = models.TextField(blank = True, max_length = 200) keyboard_url = models.TextField(blank = True, max_length = 200) Views.py: class PlayerListView(SingleTableView): model = player_hardware table_class = PersonTable template_name = 'application/playerlist.html' Tables.py class PersonTable(tables.Table): class Meta: model = player_hardware template_name = "django_tables2/bootstrap4.html" fields = ("Player", "keyboard") -
Django exclude one object cause more to be excluded
that's the weirdest bug I've ever faced since I started using Django I've a queryset with some corrupt data that needs to be excluded, when printing the queryset length it prints 97 and when prints the corruptdata queryset it's 2 so the result must be 95, but what I get is only 70!! here's my code qs = model.objects.filter( query, **sku_filter ).values( 'sku', 'sku__asin', 'sku__title', ).order_by( '-report_date', 'sku', ).annotate( in_inbound=Coalesce( LedgerQuery.in_inbound_subquery, Value(0) ) ).annotate( fnsku=F('fnsku'), action=F('sku__reconciliation_activity__action'), case_number=F('sku__reconciliation_activity__case_number'), is_being_manually_reconciled=F('sku__reconciliation_activity__is_being_manually_reconciled'), missing_subquery_count = Count(missing_subquery_count), missing=Subquery( queryset=missing_subquery ), available=Sum( 'ending_warehouse_balance', filter=Q(disposition='SELLABLE') ), total_units=Sum( F('ending_warehouse_balance') + # Available + Unsellable units in all the countries warehouses Abs('in_transit_between_warehouses') + # Reserved Component 1 Abs('customer_shipments') # Reserved Component 2 ) + F('missing') + F('in_inbound'), # it's important to put out the missing from the Sum, otherwise # the result will be missing * grouped by rows main_image_link=Subquery( queryset=main_image_link_subquery ) ) ##prints 97 print(qs.count()) ##prints 70 print("c1", qs.filter( ~Q( action=ReconciliationActivity.ActionChoices.NO_ACTION, missing__gte=1 ) ).count() ) ##prints 2 print( qs.filter( action=ReconciliationActivity.ActionChoices.NO_ACTION, missing__gte=1 ).count() ) I tried to convert it to sql to be easier for debug but it was more then 45k of words and eventually I couldn't find anything wrong with it -
POST with button in django - How I get the objects id to my project views?
I'm working on the messaging system, in template: {%for i in message%} <table> <tr> <td colspan="3" style="width: 80%"><b>{{i.subject}}</b></td> </tr> <tr> <td colspan="3" style="width: 80%">{{i.message}}</td> </tr> </table> <div> <div style="padding-top:5px; padding-right:5px; text-align:right"> <div>{{i.messagedate}} - {{i.messagehour}} - <a type="submit" name="delete" value="{{i.id}}">Delete message!</a>{%endfor%} in my views: if request.method == "POST"and 'delete' in request.POST: messageid= request.POST['delete'] message.objects.filter(id=messageid).update(delete=1) I want to delete that message by getting the message id from the form. How can I do it? I'm deleting it using a button, but it happens when the message id is instead of delete the text of the button. I tried type="hidden" but then it takes the id of the latest message in the database to the views, not the id of that message. -
as_crispy_field got passed an invalid or inexistent field
im getting this error as_crispy_field got passed an invalid or inexistent field every time im trying to use as_crispy_field with forms here is my code models.py class Customer_Email(models.Model): subject=models.CharField(max_length=50,null=True,blank=True) message=models.TextField(max_length=1000,null=True,blank=True) file_upload=models.FileField(null=True,blank=True) sender=models.ForeignKey(User,on_delete=models.CASCADE ,null=True,blank=True) company=models.ForeignKey(Customer,on_delete=models.CASCADE ,null=True,blank=True) date=models.DateTimeField(auto_now=True) views.py def send_email(request,id): customer=get_object_or_404(Customer,pk=id) form=Customer_Email_Form(request.POST) customers=Customer.objects.all() context={"customer":customer,"email_form":form,"customers":customers} if request.method == 'GET': return render(request,'crm/email_form.html',context) if request.method=='POST': if form.is_valid(): form.save() messages.success(request,"Email Sent") return render(request,'crm/listing.html',context) return render(request,'crm/email_form.html',context) html {% load crispy_forms_tags %} <form class="" method="POST"> {% csrf_token %} <div class="form-group m-2"> <label>Subject</label> {{email_form.subject|as_crispy_field}} </div> <div class="form-group m-2"> <label>Message</label> {{email_form.message|as_crispy_field}} </div> <div class="form-group m-2"> <label>Uplaod</label> {{email_form.file_upload|as_crispy_field}} <span class="color-secondary">you can attach 2M files (pdf,doc)</span> </div> {{email_form.company|as_crispy_field}} {{email_form.sender|as_crispy_field}} <button class="btn btn-primary btn-lg mt-5" type="submit" hx-post="email_form/p={{customer.id}}" hx-target="#crm-list" data-dismiss="modal" >Send Email <i class='bx bx-mail-send bx-xl'></i></button> </form> forms.py class Customer_Email_Form(forms.ModelForm): class Meta: model=Customer_Email fields=['subject','file_upload','message','sender','company'] i have tried to change it to forms.Form but it gives me the same error i dont know what excactly i should do and im new to it -
"Database 'docker-db' does not exist"
so I have this problem building django/postgre app with docker. it keeps saying "database does not exist" and quite few time googling doesnt bring any results. I already scrapped the volumes and rebuilt my app few times, followed different guides on how people do the postgres, still no luck making it work for me. Dockerfile FROM python:3.9.6-alpine WORKDIR /blog-master # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # install psycopg2 dependencies RUN apk update \ && apk add postgresql-dev gcc python3-dev musl-dev RUN pip install --upgrade pip RUN apk update \ && apk add postgresql-dev gcc python3-dev musl-dev COPY requirements.txt . RUN pip install -r requirements.txt COPY . . compose.yml services: back: image: python:3.9 build: ./blog-master command: sh -c "python manage.py runserver 0.0.0.0:8000 && /usr/local/bin/gunicorn blog.wsgi:application -w 2 -b :8000" expose: - "8000" volumes: - blog-master-django:/usr/src/app - blog-master-static:/usr/src/app/static env_file: .env depends_on: db: condition: service_healthy db: image: postgres:14 restart: always expose: - "5432" environment: - POSTGRES_DB=docker_dev - POSTGRES_USER=docker - POSTGRES_PASSWORD=docker ports: - "5432:5432" volumes: - pgdata:/var/lib/postgresql/data/ healthcheck: test: ["CMD-SHELL", "pg_isready -U docker"] interval: 5s timeout: 5s retries: 5 volumes: blog-master-django: blog-master-static: pgdata: .env DEBUG=1 SECRET_KEY='**key-here**' DJANGO_ALLOWED_HOSTS=localhost 127.0.0.1 [::1] SQL_ENGINE=django.db.backends.postgresql SQL_DATABASE=docker_db SQL_USER=docker SQL_PASSWORD=docker SQL_HOST=db SQL_PORT=5432 -
How to configure urls for the main app in Django?
This is the project: myProject/ app1/ -urls.py -views.py myProject/ -urls.py -views.py website/ -urls.py -views.py Where do I configure the urls for the website? In myProject/urls.py or website/urls.py? Here is myProject/urls.py: urlpatterns = [ path('admin/', admin.site.urls), path('', views.home, name='home'), ] So I'm not using website/urls.py... Can I remove website/ app an use myProject/ as the main app? Thanks -
upgrade django admin panel white spaces [closed]
I recently upgraded my Django version from 2.2.14 to 3.2.13 LTS, everything seems to work fine but now I have a display bug in the admin panel where there is a big white space with all the text at the bottom instead of on top. I have to scroll down in order to see the fields. -
Add all the templates to urls.py url_patterns in django
I have a lot of templates in my project. I want to add them to urls.py without typing each one of them. I want to loop them in my url_patterns. Is there any way I can add all my templates in the urls.py? -
How to represent JSONField out as comma-seperated string in Django Admin list page?
Consider I have a Django model with a custom JSONField as below, # models.py class JSONCustomField(models.JSONField): ... class JSONFieldModel(models.Model): json_field = JSONCustomField(default=list) This model is connected via Django Admin # admin.py @admin.register(JSONFieldModel) class JSONFieldModelAdmin(admin.ModelAdmin): def expected_json(self: JSONFieldModel): return self.json_field list_display = ("id", "json_field", expected_json) This setup resulting an output like the below, How can I tell Django to parse and display my "list of strings" to "comma separated strings"? Notes Django version 3.2.X Assume that the json_field will only accept list inputs (Just like an ArrayField) -
How to map a request body in node js
I have this data that format like this router.post("/add", jsonParse, (req, res) => { console.log(req.body.data) //[{"id":"someid","order":1,"configuration":"Config"}]// }) I want to get the value of id the someid I tried using var deviceData = req.body.data.map(function (d) { return d.id; }); but is says that req.body.data.map is not a function -
why this command gives error pip install waitress
Fatal error in launcher: Unable to create process using '"E:\FinalDjango\miniblog\myenv\Scripts\python.exe" "E:\FinalDjango - Copy\miniblog\myenv\Scripts\pip.exe" install waitress': The system cannot find the file specified. -
can not add or update child row, foreign key constraint failed
subscriber_package_forms = subscriber.package.form # subscriber packages forms. a = subscriber_package_forms.replace('[', '') b = a.replace(']', '') c = b.replace("'", '') d = c.replace('''"''', '') e = d.replace("'", '') f = e.split(',') #search active columns of all the packages from main database. for frm in f: frm = int(frm) try: form_columns_object = form_columns.objects.using(main_db).filter(form_id = frm).first() except: pass if form_columns_object == None: pass else: form_columns_dict = model_to_dict(form_columns_object) form_instance = FormModel.objects.using(main_db).get(id = int(form_columns_dict['form'])) user_instance = User.objects.using(main_db).first() #get(username = form_columns_dict['user']) # id = form_columns_dict['id'] form_columns.objects.using(db_name).create(columns = str(form_columns_dict['columns']), form = form_instance, user=user_instance) This code is working fine in my local setup. But i am facing a problem after committing it on server. We have error in last line of the code i guess -
Django Filtering to Get Popular Posts
I have two different models. HitCount model stores IP addresses whose was viewed Post. And what i want is filtering popular 3 posts which viewed more. I've tried some queries but i couldn't. I am sharing my models with you. class Post(ModelMeta, models.Model): title = models.CharField(max_length=255, verbose_name='Başlık', unique=True) slug = models.SlugField(max_length=255, unique=True) author = models.ForeignKey(Author, on_delete=models.CASCADE, related_name='blog_posts', verbose_name="Yazarı") category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='blog_posts', verbose_name="Kategorisi", null=True) tags = models.ManyToManyField(Tag, related_name='blog_posts', verbose_name='Etiketler') image = models.ImageField(verbose_name='Fotoğraf (800x460)') content = RichTextField() description = models.TextField(null=True) status = models.IntegerField(choices=STATUS, default=0, verbose_name='Yayın Durumu') created_at = models.DateTimeField(auto_now_add=True, verbose_name='Oluşturulma Tarihi') updated_at = models.DateTimeField(auto_now=True, verbose_name='Güncellenme Tarihi') @property def get_hit_count(self): return HitCount.objects.filter(post=self).count() class HitCount(models.Model): ip_address = models.GenericIPAddressField() post = models.ForeignKey("Post", on_delete=models.CASCADE) def __str__(self): return f'{self.ip_address} => {self.post.title}' -
return render is not working in another python file - Djanjo
I'm working on registration page and for basic validation like if user already registered, password is complex or not etc .. for that I've created a separate file and and if all checks completed I am trying to redirect but from the secondary python file redirect and even render is not working it just simply return me the same registration page but when I use redirect on the same views.py file redirect is working. That is a weird behavior? Or I am doing something wrong? [views.py] from django.shortcuts import redirect, render from .utils.registration import Register # Create your views here. def register(request): if request.method == "POST": name = request.POST['name'] username = request.POST['username'] email = request.POST['email'] password = request.POST['password'] # return redirect("/verification/") Register(request=request, name=name, username=username, email=email, password=password) [registration.py] from django.contrib import messages from django.contrib.auth.models import User from django.shortcuts import redirect, render class Register: def __init__(self, request, name, username, email, password) : self.request = request self.name = name self.username = username self.email = email self.password = password self.error_message = None self.is_email = User.objects.filter(email=self.email) self.is_username = User.objects.filter(username=self.username) self.is_user() def is_user(self): if self.is_email and self.is_username: print(1, "######################################################") self.error_message = "Hmm.. Seems like your email and username already registered with us." self.show_error() elif self.is_email: print(2, … -
django.db.utils.OperationalError: could not translate host name "db" to address: Temporary failure in name resolution on highload
I have the django project which works with PostGresql db, both in docker containers. It works Ok, but on highload sometimes gives the django.db.utils.OperationalError: could not translate host name "db" to address: Temporary failure in name resolution error. Is there a way to tune the django db connector for more retries or more timeout to solve these case? -
Python Django imported settings are not visible to other imported files
i have an old project with Python 2.7 and Django 1.6. I am trying to get run under windows. I have the files structure like: myproj/ |-- myproj/ | |-- init.py | |-- manage.py | |-- settings.py | |-- settings_common.py | |-- settings_development.py | |-- settings_production.py | |-- urls.py My settings.py: """Code to import development/production settings.""" from platform import node try: from settings_common import * except ImportError: pass PRODUCTION_HOSTS = ['mydbproj'] try: from settings_definehost import PRODUCTION_HOSTS except ImportError: pass if node().split('.')[0] in PRODUCTION_HOSTS: from settings_production import * else: from settings_development import * try: from settings_local import * except ImportError: pass and settings_common.py is: """Common settings for the mabdb.""" import os from django.conf.global_settings import TEMPLATE_CONTEXT_PROCESSORS as TCP TEMPLATE_CONTEXT_PROCESSORS = TCP + ( 'django.core.context_processors.request', ) ROOT_URLCONF = 'urls' SITE_ROOT = os.path.dirname(os.path.realpath(__file__)) ... ... ... and settings_development.py is: """Setting for development systems.""" DEBUG = True # TEMPLATE_DEBUG = DEBUG ALLOWED_HOSTS = ['127.0.0.1', 'localhost'] # Absolute path to the directory static files should be collected to. # Don't put anything in this directory yourself; store your static files # in apps' "static/" subdirectories and in STATICFILES_DIRS. # Example: "/home/media/media.lawrence.com/static/" STATIC_ROOT = SITE_ROOT .. So when i call python manage.py runserver, i get this error … -
Connecting users in Django
I want a main user who can register multiple sub-users and can see the registered users. Please guide me to write sub users model and connect them to main user. -
How to remove a once-off value for a field from django models
I would like to know how can I remove this default value I set. While migrating, I was prompted to give a once off value for a field which could not be null, I assigned the value of 0 to it. Now I get this error: I have commented out that specific field, and what confuses me as well is that it's an image field not an autofield, though I do have a faint memory of having an autofield. I double check the other app's models for this field, but I haven't found another. I also deleted the tables from the database and migration files multiple times since I got this error, but I'm still sitting with this problem.