Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do you resolve unique field clashes in django?
I have a model that looks like this: class Foo(models.Model): unique_field = models.URLField(unique=True) another_field = models.TextField() # etc... and its corresponding ViewSet looks like this (bound to /foo/): class FooViewSet( viewsets.GenericViewSet, mixins.ListModelMixin, mixins.CreateModelMixin, mixins.DestroyModelMixin, ): queryset = Foo.objects.all() serializer_class = FooSerializer When I make a POST request to /foo/, if there's no clash I just want the default behaviour (create a new row in the database and return its serialized form as a json blob). The problem is that when there is a clash the server just throws an error. What I'd rather have it do is return the json blob for the existing data, rather than crashing. Or at the very least return some kind of descriptive error. Is there a way to get this behaviour without manually overriding create()? -
python in each row take one hidden fields when popup data saved then get primary id and save in this hidden id
I have (A) table have model table. and now I do popup window for (B) table with FK of the (A) table. when I check the checkbox of one row of (A) table and press the button for the popup in each row will take one hidden field when popup data is saved then get primary id and save in this hidden id and when you will save the page then it will also save all the tables. Note: each row of the table (A ) has a specific id showing different popup data of table(B). -
Django Redis Caching how can i set cache timeout to none (never expiring cache) in class base view
I'm using redis server for caching. Using django-redis package. Below is my setting file : CACHES = { 'default': { 'BACKEND': 'django_redis.cache.RedisCache', 'LOCATION': 'redis://127.0.0.1:6379/1', 'OPTIONS': { 'CLIENT_CLASS': 'django_redis.client.DefaultClient', }, } } My view : from django.utils.decorators import method_decorator from django.views.decorators.cache import cache_page @method_decorator(cache_page(timeout=None,key_prefix="site1"), name='dispatch') class ProfileView(APIView): # With auth: cache requested url for each user for 2 hours def get(self, request, format=None): content = { 'user_feed': request.user.get_user_feed() } return Response(content) When set timeout=60 it's working. But when i add timeout=None i'm getting 600 seconds timeout. -
Django ForeignKey: using in reverse order. What form element is shown
I have a student project relationship. One student can be assigned to only one project. A project can have multiple students The following is my student and Project model class Student(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) def __str__(self): return self.first_name class Project(models.Model): name = models.CharField(max_length=30) def __str__(self): return self.name How to get create the relationship in this case -
Django How to give 2 field names in filters.py date filter
In filters.py Here i want to give 2 field names in start date class enquiryFilter(django_filters.FilterSet): start_date = DateFilter(field_name="updated_at", lookup_expr='gte',label='From',widget=DateInput(attrs={'type': 'date','id':'start_date'})) -
How to increase number of allowed symbols in line with flake8? [duplicate]
Default number of symbols is 79 according to PEP8. I use django and whant a little bit more. How and where set it? -
How to create a view of a template with 3 forms, two of them load multiple images?
I made 3 forms in one template, in the first model the fields are text inputs (it works and saves the data), in the second model it is an input to upload multiple images (it does not work and does not save data) and in the third is also to upload multiple images (does not work and does not save data). When I create the view I divided the three forms on the same view, but only the first saves data, the others don't. Even if I go into /admin there is no input button to save images. It makes me think I'm doing something wrong with my views, but I don't know what it is. can you help me review the code? Thank you models.py class Carro(models.Model): placas=models.CharField(max_length=255) tipo=models.CharField(max_length=255) cliente= models.ForeignKey(Clientes, on_delete=models.SET_NULL, null=True) fecha_registros = models.DateTimeField(default=datetime.now, null=True) def __str__(self): return f'{self.placas} {self.tipo}{self.cliente}' \ f'{self.fecha_registros}' class CarroImagenes(models.Model): carro = models.ForeignKey(Carro, on_delete=models.SET_NULL, null=True) fotosCarro=models.ImageField(null=True, blank=True, upload_to="images/") def __str__(self): return f'{self.fotosCarro}' class GarantiaImagenes(models.Model): carro = models.ForeignKey(Carro, on_delete=models.SET_NULL, null=True) garantia=models.ImageField(null=True, blank=True, upload_to="images/") def __str__(self): return f'{self.garantia}' forms.py class CarroForm(forms.ModelForm): class Meta: model=Carro fields = ['placas','tipo','cliente'] exclude = ['fecha_registros'] widgets = { 'placas': forms.TextInput( attrs={ 'class': 'form-control', } ), 'tipo': forms.TextInput( attrs={ 'class': 'form-control' … -
python django get_object_or_404 inside form_valid doesn't work
I hope you can help me, I am learning django, particularly class-based views, I have the following code. I think the get_object_or_404 inside form_valid is not working as it should. class AgregarEntrada(CreateView): model = Entrada template_name = 'EntradaCrear.html' form_class = FormularioEntrada success_url = reverse_lazy('UltimasEntradas') def get_context_data(self, **kwargs): obj = get_object_or_404(Empresa, pk = self.kwargs["pk"], slug = self.kwargs["slug"], FechaCreacion = self.kwargs["FechaCreacion"]) contexto = super().get_context_data(**kwargs) return contexto def form_valid(self, form): obj = get_object_or_404(Empresa, pk = self.kwargs["pk"], slug = self.kwargs["slug"], FechaCreacion = self.kwargs["FechaCreacion"]) form.instance.empresa_id = self.kwargs["pk"] form.instance.UsuarioCreo = self.request.user.username self.object = form.save() form.instance.Entrada = form.instance.pk return super().form_valid(form) everything works perfect, this view saves the data correctly, even if I go to /pk/slug everything works fine, likewise if I change the slug or the pk in the url it immediately sends me a 404 error, which is so well, the problem lies when someone changes the url once the form has been rendered, for example the pk or the slug, instead of sending me an error, it saves the data as if the pk or the slug were correct. I want to explain myself better. If I go to url/pk/slug everything works fine, but when someone goes to url/pk/slug and changes it to url/fake-pk/fake-slug the … -
Server Error (500) when generating a token on Django Admin page on Heroku what gives?
I'm in the final stage of wrapping up my API. The last thing I did was create a token via the Django admin page that would authorize my script to upload to the database. Basic example.py snippet: headers = {'Authorization': 'Token e4fxxxxx000000xxxxx00000xxxxxxxxxx00000'} r = requests.post(UPDATE_URL_ENDPOINT, json=json_details, headers=headers) Works swimmingly on my local machine. But when I deploy my project to heroku, it doesn't recognize my token so it doesn't accept my post requests. Fine, I say. I'll create a new token on Heroku's servers. So I create a new superuser on their command line, access the admin page, check the Create token page and go click to create a new token. And guess what I see. Server Error (500) WHAT THE HECK IS GOING ON? I'm supposed to be done with this bloody thing! This is the final block before I can finally say au revoir to this bloody project. Please, stackoverflow, fix it! -
handling many to many relation in djangon models
I am working on a project named "Super Market Inventory Management System". There are some models requiring many-to-many relation among them. I tried to add ManyToManyField(to=model, on_delete=models.CASCADE). However, it works but I need to add some values to extra fields to the bridge table between to many to many tables. How can I do It? Given below is my models.py class Purchase(models.Model): pay_status = models.CharField(max_length=50, choices=PAYSTATUS_CHOICES, default="Pending") date_of_purchase = models.DateTimeField(auto_now_add=True) last_payment = models.DateTimeField(auto_now=True) class Product(models.Model): name = models.CharField(max_length=200) barcode = models.IntegerField(blank=True, null=True) description = models.TextField(blank=True, null=True) # image = weight = models.TextField(blank=True, null=True) status = models.BooleanField(default=True) price = models.FloatField() created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class PurchaseProduct(models.Model): purchase_id = models.ForeignKey(to=Purchase, on_delete=models.CASCADE) product_id = models.ForeignKey(to=Product, on_delete=models.CASCADE) unit_price = models.FloatField() quantity = models.IntegerField() price = models.FloatField() -
CodeCov is ignoring certain files. No settings for ignore in YAML. Python/Django
I have a Python Django project on GitHub and I'm using CodeCov with this project. I have two apps in this Django project, a general app, and a general_api app. For some reason, all of the changes made in the general_api app files are being ignored. I had YAML settings like this to ignore my test cases: codecov: require_ci_to_pass: false ignore: - (?s:test_[^\/]+\.py.*)\Z - (?s:tests_[^\/]+\.py.*)\Z - ^test.py.* - ^tests.py.* However, I've removed them with the same issue. Is there some other way to ignore, or set the ignore parameters in CodeCov other than the YAML settings? OR any idea why this may be happening? -
forloop.counter0 in my django template is not working under original for loop
I have a for loop that goes through a list of inspections. I'd like to manipulate the things inside the tag depending on different situations. For test, I tried to using jquery to print out the id of the element as it iterates, but the forloop seems to be stuck at 0. when I put inside the html it will iterate, but when I put inside the attribute 'id', it will not iterate. based on the code below, it should iterate as many times as there is i in inspections. but it wont. <div class="tab-pane fade" id="nav-inspection" role="tabpanel" aria-labelledby="nav-inspection-tab"> <div class="container"></br></br> {% for i in inspections %} <div class="card - mb-3" style="width: 40 rem;"> <div class="card-body"> <h3 class="card-title">{{i.Title}} - <span title="" id="s{{forloop.counter0}}">{{i.Condition}}</span> </h3> <script type="text/javascript"> console.log(document.querySelector('[title]').innerHTML); $(document).ready(function(){ alert($('[title]').attr("id")); }); </script> <p>{{i.Desc}}</p> <h4><span class="badge badge-primary">{{i.Cost}}</span></h4> </div> </div> {% endfor %} </div> </div> -
how to run pytest conftest before everything is imported
This is a simplified version of my problem. I have a python application with the structure as below: my_project my_app __init__.py settings.py tests __init__.py conftest.py my_test.py venv # settings.py from dotenv import load_dotenv load_dotenv() MY_VALUE = os.environ["MY_KEY"] I dont want to add a .env file in here for some reasons. I also dont want to use get method on os.environ I want to run this test # my_test.py from my_app import settings def test_something(): assert True However, I get a KeyError because once I import settings.py, MY_VALUE = os.environ["MY_KEY"] is run and because MY_KEY is not in env, I get KeyError. What I thought is that I could have conftest as below import os from unittest import mock import pytest @pytest.fixture(autouse=True) def set_env(config): with mock.patch.dict(os.environ, {'MY_KEY': 'MY_VALUE'}): yield But it is still the same problem. How can I enforce this conftest before everything else. -
Auto populating database with text file django automate()
I am wanting to automatically populate my database with text files. When I try to run the file with the server on I receive the error: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/app1/automate Using the URLconf defined in demo.urls, Django tried these URL patterns, in this order: admin/ The current path, app1/automate, didn’t match any of these. You’re seeing this error because you have DEBUG = True in your Django I saw a friend do it this way and he entered this url (http://127.0.0.1:8000/app1/automate) and then the database populated. What am I missing? Thanks model.py from email.policy import default from unicodedata import name from unittest import result from django.db import models # Create your models here. class Datepick(models.Model): date = models.DateField() class PracticeGamesL(models.Model): GAMETYPECHOICES = [('PB', 'PowerBall'), ('LA', 'Lotto America'), ('TNC', 'TN Cash'), ('MM', 'Mega Millions'), ('C4L', 'Cash 4 Life')] game_type = models.CharField(max_length=10, choices=GAMETYPECHOICES) num1 = models.SmallIntegerField(null=True, blank=True) num2 = models.SmallIntegerField(null=True, blank=True) num3 = models.SmallIntegerField(null=True, blank=True) num4 = models.SmallIntegerField(null=True, blank=True) num5 = models.SmallIntegerField(null=True, blank=True) num6 = models.SmallIntegerField(null=True, blank=True) # special reveal_date = models.DateField() automation.py from datetime import datetime from django.http import HttpResponse from app1.models import PracticeGamesL import os def automate(request): texts = os.listdir('past_lotteries') for text in texts: … -
How can I use django-notifications to realize personal message notification and system notice?
How can I use django-notifications or another tool to realize personal message notification and system notice? We have many apps that need this function(more than 10 tables are involved), so I really need an easy way to solve it, thanks so much for any advice Our system(wrote in Django-rest-framework) has a function, that needs to push information when the relevant users' information is added or updated, the system will send relevant users information, such as "Your order is waiting for review (to the auditor)" "Your order is passed (to the auditee)" and also need some system notice, that every user can see that message: "Outage notice, this system will restart at XXXXX, please ......" -
/app/.heroku/python/bin/python: /app/.heroku/python/bin/python: cannot execute binary file
When I tried running "heroku run bash python manage.py migrate --app appName" from my terminal using the Heroku CLI, I get below error/response; "/app/.heroku/python/bin/python: /app/.heroku/python/bin/python: cannot execute binary file". -
How to show the links to the category with Django
I'm coding a bookmark project to learn django. I want to show the links belonging to the category. but when I run the for loop, the categories are shown twice and the card design is sorted one under the other instead of side by side. I think the problem is with the index.html file. I think I need to use if command but I don't know how. index.html <!-- component --> <div class="bg-gray-100"> <div class="container mx-auto"> <div role="article" class="bg-gray-100 py-12 md:px-8"> <div class="px-4 xl:px-0 py-10"> <div class="flex flex-col lg:flex-row flex-wrap"> <div class="mt-4 lg:mt-0 lg:w-3/5"> <div> <h1 class="text-3xl ml-2 lg:ml-0 lg:text-4xl font-bold text-gray-900 tracking-normal lg:w-11/12">Lorem ipsum</h1> </div> </div> <div class="lg:w-2/5 flex mt-10 ml-2 lg:ml-0 lg:mt-0 lg:justify-end"> <div class="pt-2 relative text-gray-600"> <input class="focus:ring-2 focus:ring-offset-2 focus:ring-gray-400 bg-white h-10 px-5 pr-16 rounded-lg text-sm focus:outline-none" type="search" name="search" placeholder="Search" /> <button type="submit" class="focus:ring-2 focus:ring-offset-2 text-gray-600 focus:text-indigo-700 focus:rounded-full focus:bg-gray-100 focus:ring-indigo-700 bg-white focus:outline-none absolute right-0 top-0 mt-5 mr-4"> <svg class="h-4 w-4 fill-current" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" id="Capa_1" x="0px" y="0px" viewBox="0 0 56.966 56.966" style="enable-background: new 0 0 56.966 56.966" xml:space="preserve" width="512px" height="512px"> <path d="M55.146,51.887L41.588,37.786c3.486-4.144,5.396-9.358,5.396-14.786c0-12.682-10.318-23-23-23s-23,10.318-23,23 s10.318,23,23,23c4.761,0,9.298-1.436,13.177-4.162l13.661,14.208c0.571,0.593,1.339,0.92,2.162,0.92 c0.779,0,1.518-0.297,2.079-0.837C56.255,54.982,56.293,53.08,55.146,51.887z M23.984,6c9.374,0,17,7.626,17,17s-7.626,17-17,17 s-17-7.626-17-17S14.61,6,23.984,6z" /> </svg> </button> </div> </div> </div> </div> {% for bookmark in bookmark_list %} <div class="px-6 xl:px-0"> <div class="grid sm:grid-cols-1 md:grid-cols-2 lg:grid-cols-3 … -
I keep getting an error when trying to create a database in my Django Project
I deleted my database and migration files with the exception of init on purpose, I wanted to start fresh. Using these commands: find . -path "*/migrations/*.py" -not -name "__init__.py" -delete find . -path "*/migrations/*.pyc" -delete I then dropped the database. Commands did their job, deleted all the migrations files necessary I then went on to create the table again: python3 manage.py makemigrations I get this error: return Database.Cursor.execute(self, query, params) django.db.utils.OperationalError: no such table: auctions_category Things I've tried: python3 manage.py migrate --run-syncdb (same error) -
502 Error on Production Deployment Django & Nginx using a docker compose file
I am using docker-compose to build containers and to serve the frontend of my website at https:// example.com and the backend at a subdomain, https:// api.example.com. The SSL certificates for both the root and subdomain are working properly, and I can access the live site (static files served by Nginx) at https:// example.com so at least half of the configuration is working properly. The problem occurs when the frontend tries to communicate with the backend. All calls are met with a "No 'Access-Control-Allow-Origin'" 502 Error in the console logs. In the logs of the docker container, this is the error response. Docker Container Error 2022/03/09 19:01:21 [error] 30#30: *7 connect() failed (111: Connection refused) while connecting to upstream, client: xxx.xx.xxx.xxx, server: api.example.com, request: "GET /api/services/images/ HTTP/1.1", upstream: "http://127.0.0.1:8000/api/services/images/", host: "api.example.com", referrer: "https://example.com/" I think it's likely that something is wrong with my Nginx or docker-compose configuration. When setting the SECURE_SSL_REDIRECT, SECURE_HSTS_INCLUDE_SUBDOMAINS, and the SECURE_HSTS_SECONDS to False or None (in the Django settings) I am able to hit http:// api.example.com:8000/api/services/images/ and get the data I am looking for. So it is running and hooked up, just not taking requests from where I want it to be. I've attached the Nginx configuration … -
use multi database in django class based view
Im using django for a project with many database(about 500). So I can't write route for my databases, then I use "using", but the question is how can I use class based view like update or create view? what function shuld I override to change database query? -
Python Django IMG upload function based
I do not want to use class based forms. (function based) I need to be able to created my own form with a few fields and give the option to add either a photo or word doc. Any help would be awesome. def addmessage(request): if request.POST: Message.objects.create( name_of_msg = request.POST['name_of_msg'], message = request.POST['message'], photo = request.POST['photo'], file = request.POST['file'] ) return redirect('/home') def addmessage(request): if request.POST: Message.objects.create( name_of_msg = request.POST['name_of_msg'], message = request.POST['message'], photo = request.FILES['photo'], file = request.FILES['file'] ) return redirect('/home') def home(request): context={ 'photos' : Message.objects.all() } return render(request, 'home.html', context) #to access it on the front end {% for photo in photos %} {{photo.photo}} {% endfor %} <h3>Add a Message:</h3> <form action="/addmessage" method="POST"> {% csrf_token %} <input class="type=" text" name="name_of_msg" placeholder="Message Name"> <br> <input class="type=" text" name="message" placeholder="Message"> <br> <input type="file" name="photo" placeholder="Add Photo"> <br> <input type="file" name="file" placeholder="Add a Doc"> <br> <input type="submit" value="Add It!"> </form> </div> -
Create a reverse relationship to two models
I have a model User. For performance and other reasons I have to split this Model and its table into two, UserA and UserB. I decided to use materialized views (with the help of django-pgviews). Now what IS easy is to query the data of UserA which is already in the table, like the username or password. What doesn't work are reverse relationships. Let's say I have a Checkout model and in this: user = models.ForeignKey(User, on_delete=models.SET_NULL, related_name='checkouts') When I try to access user.checkouts, it of course throws an error: Cannot resolve keyword 'checkouts' into field. So how can I create a reverse relationship which is accessible from multiple models? I thought about using contenttypes but this seems a bit much for this use case, especially because UserA and UserB are just views and have the same columns. -
Django Admin Select2 failing to search with TypeError: Cannot read properties of undefined (reading 'slice') at o.e.removePlaceholder
I am using django 3.2 and trying to use the Select2 autocomplete field option in my admin page. I am a full administrator with all rights to all objects. I have followed the document and have the Select2 field showing up on my related field and i have the search_field setup on the parent model. When I click into the select2 field i can see all the options and select them. They also display fine when selected. However, if i try to type in the search box it fails with a javascript error: Query.Deferred exception: Cannot read properties of undefined (reading 'slice') TypeError: Cannot read properties of undefined (reading 'slice') at o.e.removePlaceholder (https://example.com/static/admin/js/vendor/select2/select2.full.min.fcd7500d8e13.js:2:45012) at o.removePlaceholder (https://example.com/static/admin/js/vendor/select2/select2.full.min.fcd7500d8e13.js:2:4435) at o.e.append (https://example.com/static/admin/js/vendor/select2/select2.full.min.fcd7500d8e13.js:2:44816) at o.append (https://example.com/static/admin/js/vendor/select2/select2.full.min.fcd7500d8e13.js:2:4435) at d.<anonymous> (https://example.com/static/admin/js/vendor/select2/select2.full.min.fcd7500d8e13.js:2:10117) at d.e.invoke (https://example.com/static/admin/js/vendor/select2/select2.full.min.fcd7500d8e13.js:2:5066) at d.e.trigger (https://example.com/static/admin/js/vendor/select2/select2.full.min.fcd7500d8e13.js:2:4885) at d.trigger (https://example.com/static/admin/js/vendor/select2/select2.full.min.fcd7500d8e13.js:2:65478) at https://example.com/static/admin/js/vendor/select2/select2.full.min.fcd7500d8e13.js:2:63778 at Object.<anonymous> (https://example.com/static/admin/js/vendor/select2/select2.full.min.fcd7500d8e13.js:2:38274) undefined To me it looks like its not able to search the string i am entering but im using a default install of django admin. So i am not sure what i am doing wrong. My autocomplete model looks like this class TeamMember(models.Model): .... exclude_case_type = models.ManyToManyField(CaseType, blank=True, related_name="case_types", help_text="Individually Exclude a Case Type") .... class CaseType(models.Model): """Model definition for CaseType.""" … -
how to Implement add to basket in django?
Im developing an ecomerce website with django! Django+ vue js. For add to basket/cart. Shoud i use django session in backend? Vue js also have session storage ! Which one is the proper way? Whats the diffrence? -
Keep track of follow/unfollow events django
I am building a sort of social media app, where users can follow certain pages. I want the page managers to be able to visualize their followers in a chart for each day/week or so. So I am thinking about how to implement the following system. For now, I have this model: class FollowHistory(models.Model): user = models.ForeignKey('User', on_delete=models.CASCADE, related_name="follow_history") page = models.ForeignKey('Page', on_delete=models.CASCADE, related_name="follower_history") timestamp = models.DateTimeField(auto_now_add=True) followed = models.BooleanField() When a user clicks Follow, I create an instance with followed = True, and the timestamp of the event. When a user clicks Unfollow, I do the same, but with followed = False. I am struggling to figure out how to query the data in a way for a page to see how many users they had each day. So far I have tried this: FollowHistory.objects.filter(page=page, followed=True)\ .annotate(ts_day=Trunc('timestamp', 'day'))\ .values('ts_day')\ .annotate(followers=Count('id')) But that just gives me the count of events that happened in a day, so if I follow and unfollow a company 10 times, then it will count 10 times. I only need to know by the end of the day, did I follow or not? Maybe there is a better implementation of the model that you could recommend, …