Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django loaddata fails with ElephantSQL-based Postgres
I've worked with Django for a few years, but always used sqlite (I only use it for small personal sites). I want to try to migrate one of my projects to Postgres, using a free ElephantSQL plan, and I need to transfer the existing data. I've used dumpdata for the first time, and it worked fine, a JSON file was generated. The command used was dumpdata --indent 2 -o db-dump.json Then I reconfigured the project to use Postgres and tried loaddata db-dump.json, which resulted in psycopg2.OperationalError: FATAL: no pg_hba.conf entry for host "xx.xxx.xx.xxx", user "xxxxx", database "postgres", SSL off I have no clue where this pg_hba.conf is and how to configure it. I installed pgAdmin 4, but not sure where to find that. -
Get list of users when it is midnight in their timezone
I need to send an email to my users when it is midnight in their timezone. I think my approach is fine, but I am having an issue with the Django F() function in my query. Here is the query: target_offset = 0 - timezone.now().hour users_to_email = User.objects.exclude( timezone__isnull=True ).annotate( tz_offset=Value( int (datetime.now(F('timezone')).strftime('%z')) / 100, models.IntegerField() ) ).filter( tz_offset=target_offset ) I get this error: int (datetime.now(F('timezone')).strftime('%z')) / 100, File "/Users/leeloftiss/Desktop/daisy_coder/website/djangoEnv/lib/python3.8/site-packages/freezegun/api.py", line 386, in now result = tz.fromutc(now.replace(tzinfo=tz)) + cls._tz_offset() AttributeError: 'F' object has no attribute 'fromutc' If I just call F('timezone') outside of the datetime.now() function, I get the actual value from the users TIMEZONE column. So I guess I just need to know how I can get that value in this case where I need it in the datetime.now() function. Note: I am using SQL, not Postgres -
DjangoQ is Triggering Twice For Each Task, also on Startup
I have a lot of recurring tasks and am suddenly having the issue that my tasks are being triggered Twice, as well as on startup even though the task was successfully triggered the first time. I'm wondering if I need to set a flag to ensure that DjangoQ knows the Task was completed successfully or there is some other reason this might happen? Here are my DjangoQ Settings in Testing: Q_CLUSTER = { "name": "DjangORM", "workers": 4, "timeout": 90, "retry": 91, "queue_limit": 50, "bulk": 10, "orm": "default", "sync": False, "save_limit": 0, "ack_failures": True, "max_attempts": 1, "attempt_count": 1, } -
Python/Docker - No matching distribution found for Django==3.1.3
I have a project that I am trying to run named Veganettest inside of my visual studio code editor, however, when I run docker-compose up I receive an error that says ERROR: No matching distribution found for Django==3.1.3 even though such a distribution does indeed exist. I have tried using pip to install the distribution itself both inside and outside of my docker container but when I run the program again it just gives me the same error. On top of that, I have tried various other solutions on here, but they are irrelevant to my problem specifically dealing with this library. The error seems to come from my requirements.txt file. Here is the full error that I am getting along with a few warnings initially: WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.HTTPSConnection object at 0x000001B4E55BC430>: Failed to establish a new connection: [Errno 11002] getaddrinfo failed')': /simple/django/ WARNING: Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.HTTPSConnection object at 0x000001B4E55DE070>: Failed to establish a new connection: [Errno 11002] getaddrinfo failed')': /simple/django/ WARNING: Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.HTTPSConnection object at 0x000001B4E55DE220>: Failed to establish a new connection: [Errno … -
how to get date input from users in django models
I am working on api and testing it by postman so I want date from users as input in %d-%m-%y format also date field is not mandatory here is how my model.py looks like from django.db import models # Create your models here. class Vication(models.Model): travelDate = models.DateField(null=True) # Here I want date as input from users destination= models.CharField(max_length=50,blank=True) status = models.CharField(max_length=8,default='BOOKED') timestamp = models.DateTimeField(auto_now_add=True,editable=False) def __str__(self): return self.title -
How to retrieve data from a model of an App in the views of another application?
Hello django python developers. Indeed, I developed a django project composed of 2 applications. MyApp and Blog I want to retrieve the data from the MyApp App models from the database on the App Blog views without rewriting the same functions How do I do it -
OR operator in Django filter creates duplicates
when I print Brand.objects.filter(Q(name__icontains=keyword)|Q(tag__name__icontains=keyword)), it yields two objects as opposed to my expectation. It should be only one. My models.py is like class Brand(models.Model): name = models.CharField(max_length=20) tag = models.ManyToManyField('Tag', blank=True) class Tag(models.Model): name = models.CharField(max_length=20) When I print Brand.objects.filter(name__icontains=keyword) and Brand.objects.filter(tag__name__icontains=keyword) seperately, each one yields only one same object. But when I merge these two queries, it yields duplicates. I found out .distinct() solves this problem but I wanna know why. Looking forward to help! -
Reset field in Django Admin page
Imagine, that I have model and in the Django admin form I can update my fields. I want to implement something like: update one field and the second one will be reset in admin form in real time (I'll hope it can help real admin in the future do not forget redefine this second field, because it's very important in my situation). Is that possible to implement something like that without custom admin form? -
AttributeError: 'NoneType' object has no attribute 'build_absolute_uri' Django Rest Framework
I've got this Serializer translating path to url, and it works on its own, but when i try to nest this serializer inside another serializer, i get this error. Do you have any idea why? I need to have this function, because otherwise it just shows the paths to the image in this main SpecialistSerializer. class EntityPhotosSerializer(serializers.ModelSerializer): image = serializers.SerializerMethodField('get_file_abs_url') class Meta: model = EntityPhoto fields = ('user', 'entity', 'image',) def get_file_abs_url(self, obj): request = self.context.get('request') return request.build_absolute_uri(obj.image.url) class SpecialistSerializer(serializers.ModelSerializer): reviews_quantity = serializers.IntegerField(source="get_reviews_quantity") class Meta: model = Entity fields = '__all__' def to_representation(self, instance): data = super().to_representation(instance) data['photos'] = EntityPhotosSerializer(many=True, instance=instance.entityphoto_set.all()).data return data Traceback: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/handlers/base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/views/generic/base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/rest_framework/views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/rest_framework/generics.py", line 282, in get return self.retrieve(request, *args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/rest_framework/mixins.py", line 56, in retrieve return … -
How can i deploy my django projects on heroku?
I tried to deploy my simple django project on heroku, but i couldn't understand how to solve this problem This is the git push heroku master remote: Traceback (most recent call last): remote: File "/tmp/codon/tmp/buildpacks/0f40890b54a617ec2334fac0439a123c6a0c1136/vendor/runtime-fixer", line 8, in <module> remote: r = f.read().strip() remote: File "/usr/lib/python3.8/codecs.py", line 322, in decode remote: (result, consumed) = self._buffer_decode(data, self.errors, final) remote: UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte remote: /tmp/codon/tmp/buildpacks/0f40890b54a617ec2334fac0439a123c6a0c1136/bin/steps/python: line 5: warning: command substitution: ignored null byte in input remote: ) is not available for this stack (heroku-20). remote: ! Aborting. More info: https://devcenter.heroku.com/articles/python-support remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push failed remote: ! remote: ! ## Warning - The same version of this code has already been built: 898dd95ff261fc77ac4dcd00edd162d7b7c054f2 remote: ! remote: ! We have detected that you have triggered a build from source code with version 898dd95ff261fc77ac4dcd00edd162d7b7c054f2 remote: ! at least twice. One common cause of this behavior is attempting to deploy code from a different branch. remote: ! remote: ! If you are developing on a branch and deploying via git you must run: remote: ! remote: ! git push heroku <branchname>:main remote: ! remote: ! This … -
Invalid block tag on line 24: 'form.as_p', expected 'endblock'. Did you forget to register or load this tag?
I'm a new in Django and trying to do a app but now I'm having this error: "Invalid block tag on line 24: 'form.as_p', expected 'endblock'." TEMPLATE {% extends "base.html" %} {% block title %} <title>Tarefas</title> {% endblock title %} {% block content %} <div class="content"> {% if messages %} <div class="container"> <br> {% for message in messages %} <div class="alert alert-info" role="alert"> {{message}} </div> {% endfor %} </div> {% endif %} <div class="container tasks-box"> <table class="table table-striped"> <form method='POST'> {% csrf_token %} {% form.as_p %} <button type="submit" class="btn btn-secondary btn-sec">Adicionar</button> </form> [...] forms.py from django.forms import ModelForm from todolist.models import Tasks class TaskForm(ModelForm): class Meta: model = Tasks fields = ['task','responsible'] views.py from django.shortcuts import render, redirect from django.http import HttpResponse from todolist.models import Tasks from todolist.forms import TaskForm from django.contrib import messages from django.contrib.auth.decorators import login_required @login_required def todolist(request): if request.method == 'POST': form = TaskForm(request.POST or None) if form.is_valid(): instance = form.save(commit=False) instance.manager = request.user instance.save() messages.success(request,("Tarefa adicionada")) return redirect('todolist') else: form = TaskForm all_tasks = Tasks.objects.filter(manager=request.user) all_users = Tasks.objects.all() return render(request,'todolist.html',{ 'form':form, 'all_tasks':all_tasks, 'all_users':all_users}) models.py from django.db import models from django.contrib.auth.models import User from django.contrib.auth import get_user_model # Create your models here. User = get_user_model() class … -
How do you start this project?
When I use the code django-admin.exe startproject mysite it gives me a blank. I don't know whats happening. Does anyone know the answer to this? -
How can i solve Foreign key mismatch error in django?
I am trying to connect the two tables in django but i am getting the error django.db.utils.OperationalError: foreign key mismatch - "website_doctor" referencing "website_field" please suggest a way to solve it -
Django - How to only allow staff users to see their own posts in admin panel
I have a model called listings and I want staff users to only be able to view, edit, delete listings in the admin panel that they created. Currently staff users can view edit and delete all of the listings here is my listings/admin.py from django.contrib import admin from .models import Listing class ListingAdmin(admin.ModelAdmin): list_display =('id','Full_Name','Is_Published','Town_Or_City','District','Region','List_Date') list_display_links = ('id','Full_Name') list_editable = ('Is_Published',) search_fields = ('Full_Name','Town_Or_City','District','Region',) admin.site.register(Listing, ListingAdmin) here is my listings/models.py from django.db import models from datetime import datetime from FuneralHomes.models import FuneralHome class Listing(models.Model): index = models.ForeignKey(index, on_delete=models.DO_NOTHING,blank=True) Full_Name = models.CharField(max_length=200) First_Name = models.CharField(max_length=200) Last_Name = models.CharField(max_length=200) Nee = models.CharField(max_length=200, blank=True) Town_Or_City = models.CharField(max_length=200) District = models.CharField(max_length=200, blank=True) Region = models.CharField(max_length=200) List_Date = models.DateField(max_length=200) Photo = models.ImageField(upload_to='photos/%Y/%m/%d', blank=True) Is_Published = models.BooleanField(default=True) List_Date = models.DateTimeField(default=datetime.now, blank=True) def __str__(self): return self.Full_Name -
How to test if an instance of a django model was created?
I am testing an api for a game and have some issues with a model. This is my model: models.py class Gamesession(models.Model): gamemode = models.ForeignKey(Gamemode, on_delete=models.CASCADE, null=True) user = models.ForeignKey(CustomUser, on_delete=models.SET_NULL, null=True) gametype = models.ForeignKey(Gametype, on_delete=models.CASCADE) created = models.DateTimeField(editable=False) objects = models.Manager() This is the test suite: test_models.py def setUp(self): self.user = CustomUser.objects.create(id=1, username="carina") self.gametype = Gametype.objects.create(id=1, name="NewGame", rounds=5, round_duration=60, enabled=True) self.gamesession_user = self.user self.gamesession_gametype = self.gametype self.gamesession_created = datetime.utcnow().replace(tzinfo=pytz.UTC) self.gamesession = Gamesession.objects.create(id=1, user=self.gamesession_user, gametype=self.gamesession_gametype, created=self.gamesession_created) def test_create_gamesession(self): gamesession = Gamesession.objects.create(gametype=self.gametype) assert gamesession.gametype == self.gamesession_gametype Running my tests keeps retrieving the error: GamesessionTests::test_create_gamesession - django.db.utils.IntegrityError: null value in column "created" of relation "frontend_games How can I solve this? Is there a better way to test if an instance of the model is created? -
Add more fields to auth User model and then use it for authentication in Django
I want to add more fields to auth User model and then use it for registration,login and logout . For example i need an image field to store profile picture and an interger/date field to store date of birth . I having hard time understanding the custom authentication . I want to register normal user using html template and then login . -
Where to find a single understandable instructions for the method of ModelAdmin in Django
A question from a silly noob about Django I read a tutorial that described the ModelAdmin method changelist_view It looks next: class SaleSummaryAdmin(ModelAdmin): # ... def changelist_view(self, request, extra_context=None): response = super().changelist_view( request, extra_context=extra_context, ) try: qs = response.context_data['cl'].queryset except (AttributeError, KeyError): return response metrics = { 'total': Count('id'), 'total_sales': Sum('price'), } response.context_data['summary'] = list( qs .values('sale__category__name') .annotate(**metrics) .order_by('-total_sales') ) return response This is different from what is in the documentation. Additionally, in other tutorials I have seen other versions of writing this method, like this: def changelist_view(self, request, extra_context=None): extra_context = extra_context or {} gradeScalesSettings = gradeScalesSetting.objects.all() configurations = configuration.objects.all() rounding = gradeScalesSetting.objects.all().values_list('Rounding', flat=True).distinct() extra_context.update({ "rounding": rounding, "gradeScalesSetting": gradeScalesSettings, "configurations": configurations, }) return super().changelist_view(request, extra_context=extra_context) How does it work? I don't understand how correctly to use this method, because I can't find a single instruction. I probably just don't understand the principle by which it works. Tell me in which direction I should look -
How to execute Nested loop in Django Template on single Queryset
I want to render my query set data on template with a slider. Each slider will contain 3 product query like this But I am unable to to this dynamically with for loop in Django template language. My Template code is <h4>Latest Products</h4> <div class="latest-product__slider owl-carousel"> {% for product in recent_products %} <div class="latest-prdouct__slider__item"> <a href="#" class="latest-product__item"> <div class="latest-product__item__pic"> <img src="{{product.images.url}}" alt=""> </div> <div class="latest-product__item__text"> <h6>{{product.name}}</h6> <span>{{product.price}} Tk</span> </div> </a> </div> {% endfor %} </div> here is my view function: def index(request): products = Product.objects.all() categorys = ProductCategory.objects.all() today = timezone.now().date() last_day = today - timezone.timedelta(days=7) today = datetime.strftime(today, "%Y-%m-%d") last_day = datetime.strftime(last_day, "%Y-%m-%d") print(last_day) recent_products = Product.objects.filter(added_time__range=[last_day, today]).order_by("-added_time") context = { 'products': products, 'categorys': categorys, 'recent_products': recent_products } return render(request, 'index.html', context) and my model class is: class ProductCategory(models.Model): name = models.CharField(max_length=100) image = models.ImageField(blank=True, null=True) added_time = models.DateTimeField(auto_now_add=True) updated_time = models.DateTimeField(auto_now=True) def __str__(self): return self.name class Product(models.Model): name = models.CharField(max_length=200) price = models.FloatField(blank=True, null=True) ratings = models.FloatField(blank=True, null=True) number_of_ratings = models.IntegerField(blank=True, null=True) images = models.ImageField(blank=True, null=True) description = models.TextField(blank=True, null=True) # user_review need to be added discount_rate = models.IntegerField(default=0) available_stock = models.IntegerField(default=0) added_time = models.DateTimeField(auto_now_add=True) updated_time = models.DateTimeField(auto_now=True) category = models.ForeignKey(ProductCategory, on_delete=models.SET_NULL, null=True, blank=True) @property def discount(self): if … -
How do I reverse the sign in a django database query on matching rows?
I have a Django model that looks like this: direction_choices = ( ("up", "Up"), ("down", "Down"), ("left", "Left"), ("right", "Right"), ) class Movement: direction = models.CharField(max_length=5, choices=direction_choices) distance = models.PositiveSmallIntegerField() Lets say the data in my database looks like this: Movement(direction="up", 4) Movement(direction="up", 6) Movement(direction="down", 3) Movement(direction="down", 1) Movement(direction="left", 7) Movement(direction="right", 4) Movement(direction="left", 1) Movement(direction="right", 8) I want to do a database query that will calculate the total distance moved in the Y axis. In our example, it would be: 4+6-3-1 = 6 I can do something like: Movement.objects.all().filter( direction__in=("up", "down") ).aggregate( total=Sum('distance') ) which gives me: {'total': 16} I'm not sure how to tell the database that "down" fields should be multiplied by -1 to have their signs reversed before adding up the total. I know this is easy to do with Python with a for loop, or list comprehension. How would one have the database do this? -
Is there a way of using FPDF to generate a PDF file from forms in Django?
I am trying to generate a PDF file and give it a custom name using Django 4.0.2 I have 2 inputs, one for the name and one for the photos, I want to be able to generate the PDF without saving it in my database. I am using no models for this, plain html and python. I have the inputs: <input type="text" id="inputPassword6" class="form-control" aria-describedby="passwordHelpInline" name="name" /> <input class="form-control" type="file" id="formFileMultiple" multiple accept=".png, .jpeg, .jpg" name="photos" /> <div class="d-grid gap-2 mt-3"> <button class="btn btn-success" type="submit">Save PDF</button> </div> And I am trying to merge and return the PDF file like this: if request.method == "POST" or "FILES": name = request.POST["name"] photos = request.FILES["photos"] # Convert photos to PDF pdf = FPDF() # imagelist is the list with all image filenames for image in photos: pdf.add_page() pdf.image(image, 0,0,210,297) pdf.output(f"{name} AIA 114.pdf", "F") Current error: Exception Type: TypeError Exception Value: argument should be integer or bytes-like object, not 'str' It looks like FPDF can not look into the image I provided. I tried to decode the image, but I hit another error: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte Can someone help me solve this problem or propose … -
AttributeError: 'Model' object has no attribute '....' Django Rest Framework
I have this model class EntityPhoto(models.Model): user = models.ForeignKey('users.CustomUser', on_delete=models.CASCADE, null=True, related_name='entity_photo_user') entity = models.ForeignKey('Entity', on_delete=models.CASCADE) image = models.FileField(upload_to='entities/') created_at = models.DateTimeField(editable=False, default=timezone.now) updated_at = models.DateTimeField(default=timezone.now) class Entity(models.Model): .... class EntityPhotosSerializer(serializers.ModelSerializer): image = serializers.SerializerMethodField('get_img') def get_img(self, entity_photo): if not entity_photo.image: raise NotFound request = self.context.get('request') return request.build_absolute_uri(entity_photo.image.url) class Meta: model = EntityPhoto fields = ('user', 'entity', 'image',) class SpecialistSerializer(serializers.ModelSerializer): reviews_quantity = serializers.IntegerField(source="get_reviews_quantity") class Meta: model = Entity fields = '__all__' def to_representation(self, instance): data = super().to_representation(instance) data['photos'] = EntityPhotosSerializer(many=True, instance=instance.image_set.all()).data return data and after making get request I get an error: AttributeError: 'Entity' object has no attribute 'image_set' Which is weird because a few days ago i did the same thing with a model that was connected via reverse relationship the same way, i even copied the code and it worked. Do you think it might be because of the image file? I wanna show the list of Photos(that the serializer changed to url) for every Entity Instance. -
Barcodes are not scannable after html-to-pdf conversion (using weasyprint package)
I am using weasyprint package for html to pdf conversion with Django. my problem is that i can't scan barcodes in the pdf printed. !!! the only scannable format is ean13 but it can't cover my need because it can encode only 8, 12, 13, 15, and 18 digits of numbers! I used code128, code39 of libre barrcode google fonts links but i had the same problem Please, if there is somone here who did this task and it worked for him, heeelp me -
Input a CSV file from HTML and parse it to database using Django
I have a CSV file with some data, I want to create a web-page that takes the CSV file and converts it into table using django. I'm new to django and I don't know whether it is possible to automate everything... Any suggestions to approach this problem or even solutions Thank you -
500 Server Error after saving the data in django admin
My website is deployed on apache server. When I am adding image field in model. I am trying to save the object in Django admin but it is showing server error 500. But if I am removing image field in model. It is not showing any error. What should I do. -
how to set default selected value in ModelChoiceField while working with ModelForm?
I am creating a simple form through ModelForm,i have made 4 tables which consists of one main table, and 3 sub tables which is the foreign keys of main tables,everything is working perfect. But I want that there must be selected value in form which will show in the frontend by default. by default it is showing -------- in select tag of html but i want that it will show some label like in my case: it will be better if it shows Select Job Description by default rather than ------ so how can i implement that? My forms.py from django import forms from django.utils.translation import gettext_lazy as _ from numpy import empty from .models import SignUpModel class SignUpForm(forms.ModelForm): first_name = forms.CharField(widget=forms.TextInput( attrs={'placeholder': 'First Name'}), required=True, error_messages={'required': 'First Name is required'}) last_name = forms.CharField(widget=forms.TextInput( attrs={'placeholder': 'Last Name'}), required=True, error_messages={'required': 'Last Name is required'}) email = forms.EmailField(widget=forms.EmailInput( attrs={'placeholder': 'Email Address'}), required=True, error_messages={'required': 'Email Address is required'}) class Meta: model = SignUpModel fields = ['first_name', 'last_name', 'email', 'password', 'company_name', 'job', 'mobile_no', 'country', 'state'] widgets = { 'password': forms.PasswordInput(attrs={'placeholder': 'Password'}), 'company_name': forms.TextInput(attrs={'placeholder': 'Company Name'}), 'mobile_no': forms.NumberInput(attrs={'placeholder': 'Mobile Number'}), } error_messages = { 'password': { 'required': _('password is required') }, 'mobile_no': { 'required': _('Mobile …