Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how can i redirect the user to the newly created post after creating a new post
I want the user to be redirected to the newly created post i tried adding return reverse("article-detail", args=(str(self.pk))) but it doest work. models.py Class Post(models.Model): title = models.CharField(max_length=255) header_image = models.ImageField(null=True, blank=True, upload_to='images/') title_tag = models.CharField(max_length=255) author = models.ForeignKey(User, on_delete=models.CASCADE) body = RichTextField(blank=True, null=True) # body = models.TextField() post_date = models.DateTimeField(auto_now_add=True) category = models.CharField(max_length=255, default='coding') snippet = models.CharField(max_length=255) likes = models.ManyToManyField(User, related_name='blog_post') def total_likes(self): return self.likes.count def __str__(self): return self.title + ' | ' + str(self.author) def get_absolute_url(self): return reverse("article-detail", args=(str(self.pk))) # return reverse("home") urls.py path('add_post/', AddPostView.as_view(), name="add_post"), views.py class AddPostView(CreateView): model = Post form_class = PostForm template_name = 'add_post.html' -
Django: different content based on language [closed]
How can I show different dynamic content based on language code? I have blog and the task is to post different posts on every language. -
Django form.save() does not return a pk value, when pk is UUID
I'm running my project on Python 3.7.5, Django >=2.2.8,<3.0.0 and Postgres 12.1 I have implemented 2 models: class CustomUser(AbstractUser): objects = CustomUserManager() person = models.ForeignKey( 'Person', on_delete=models.DO_NOTHING, null=True) class Person(models.Model): uuid = models.UUIDField(primary_key=True, db_column='person_uuid') first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) address1 = models.CharField(max_length=255, blank=True, null=True) address2 = models.CharField(max_length=255, blank=True, null=True) add_date = models.DateTimeField(auto_now_add=True) mod_date = models.DateTimeField(auto_now=True) The CreateUser view shown below is for registering new users. This view consists of 2 forms, a user creation form and a person form. Once the user enters their details I want to save the person_form and set the person field in CustomUser to the newly created person. But the value of pk after save is always None. To work around this, I query the Person model with the matching first_name and last_name and use the UUID from the response. But this is very brittle, as I have other models that use UUID and don't have unique values like first_name and last_name. I wonder if there is a more reliable way of getting the UUID of the form just saved. class CreateUserView(View): template_name = 'core/create_user.html' def get(self, request, *args, **kwargs): user_form = CustomUserCreationForm() person_form = PersonForm() context = {'person_form': person_form, 'user_form': user_form} return render(request, … -
Requirements.txt install ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output
I tried doing pip install -r requirements.txt in my Windows terminal for a git project which I cloned built with Django/Python. I am using Python 3.8.5 on Windows 10. Here are the contents of the requirements.txt file: django_annoying==0.10.3 channels==0.17.3 Django==1.10.3 gunicorn==19.4.5 daphne==0.14.1 django_imagekit==3.3 dj-database-url==0.4.0 dj-static==0.0.6 Unipath==1.0 python-decouple==3 Pillow==3.4.2 psycopg2==2.6.1 whitenoise==3.2 dj-database-url==0.4.0 asgi_redis==1.0.0 asgiref==0.13 Twisted==15.5.0 txaio==2.6.0 zope.interface==4.1.3 haikunator==1.0.1 six==1.10.0 msgpack-python==0.4.7 The following error message appears in red in the terminal: ERROR: Command errored out with exit status 1: """ several non-error lines which I have removed """ Writing manifest file 'C:\...\pip-pip-egg-info-zti391vx\psycopg2.egg-info\SOURCES.txt' Error: could not determine PostgreSQL version from '12.3' ---------------------------------------- ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output. I've thoroughly searched for this error message on Google and can't find a solution that works for me. Also I get a similar error when doing the same thing for some other git projects. Please can someone help me understand what the problem is and how to fix it? Please note I am new to coding. -
Django aggregate and keep fields
I would like to find the average test score for each user. Model: class Sitting(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) percent_correct = models.IntegerField(null=True) ... Query: values = Sitting.objects.filter( user__supervisor__exact=request.user, complete=True, end__gte=datetime.now( tz=timezone.get_current_timezone()) - timedelta(days=90)).exclude( percent_correct=None).order_by('-end').aggregate(avg_score=Avg('percent_correct')) print(values) For one user in the db this query returns the correct average across 3 tests but none of the other data is with it: {'avg_score': 33.333333333333336} But I would like it to return something like this so I can call the users and their average score in the template: {'user': 6, 'avg_score': 33.333333333333336} -
Parameters not being sent to a URL in Django redirect
I want to send a get parameter to a specific URL e.g. http://127.0.0.1:8000/foo?myid=99 However this code is not creating the get parameter: def BarView(request): return redirect(reverse('foo'), myid=99) But the resulting URL is just http://127.0.0.1:8000/foo/ def FooView(request): return HttpResponse('''<html lang="en"><body><p>myid: %s</p> </body>''' % request.GET.get('myid', '')) In "urls.py": urlpatterns = [ path('foo/', views.FooView, name='foo'), path('bar/', views.BarView, name='bar'), ] -
Django ListView: How can I create a conditional attribute that's accessible in my template?
I am using ListView to list some objects from a model. I want to highlight entries in the displayed list where the listed item was created by the current user, and I plan to do this with a small coloured dot (circle) created using CSS. Here's a test case. # models.py from django.db import models from django.contrib.auth.models import User class Foo(models.Model): created_by = models.ForeignKey( User, to_field='username', on_delete=models.PROTECT, related_name='foos_as_usernames', blank=False ) stuff = models.CharField(max_length=128, blank=True) #views.py from django.views.generic import ListView class FooListView(ListView): model = Foo def get_context_data(self, **kwargs): context = super(FooListView, self).get_context_data(**kwargs) # Here I want to conditionally set a dot_class attribute based on # comparing Foo.created_by with the current user, i.e. # if object.created_by == user: # object.dot_class = 'its-me' # What do I add here to create the dot_class attribute in the object_list? # Is there some other way I can pass a list to the foo_list.html template? return context # foo_list.html {% load static %} <!DOCTYPE html> <html> <head> <title>FooBar</title> <style> .its-me { height: 8px; width: 8px; background-color: dodgerblue; border-radius: 50%; display: inline-block; } </style> </head> <body> <table> <tr> <th>&nbsp;</th> <th>Stuff</th> </tr> {% for obj in object_list %} <tr> <td><span class="{{ obj.dot_class }}"></span></td> <td>{{ obj.stuff }}</td> </tr> {% … -
Ways to change dropdown choices in django-filter
I'm trying to change the dropdown values for the user field. I want to show the email addreses , instead of the nombre + apellido. Because in my models I have the str that returns nombre + apellido, those are the values displayed in the dropdown. How can I change those values without changing the str in the Tutor model? Tryed to do a CustomManager but didn't work. MODEL: class Tutor(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE, primary_key=True) nombre = models.CharField(max_length=50, blank=False, null=True) apellido = models.CharField(max_length=50, blank=False, null=True) biografia = models.TextField() curriculum = models.FileField(upload_to="curriculums/", blank=True, null=True) foto = models.ImageField(blank=True, null=True) carrera = models.ManyToManyField(Carrera, blank=True) linea_invest = models.ManyToManyField(Linea_Invest, blank=True) correo = models.EmailField(blank=True, null=True) numero_celular = models.CharField(max_length=20, blank=True, null=True) class Meta: verbose_name_plural = "Tutores" verbose_name = "Tutor" def __str__(self): return '%s %s' % (self.nombre, self.apellido) FILTER class TutorFilter(django_filters.FilterSet): nombre = CharFilter(field_name="nombre", label="Nombre",lookup_expr='icontains') apellido = CharFilter(field_name="apellido", label="Apellido",lookup_expr='icontains') carrera = ModelMultipleChoiceFilter(field_name= "carrera", queryset= Carrera.objects.all()) user = ModelChoiceFilter(field_name = "user", label = "correo", queryset = Tutor.objects.all()) class Meta: model = Tutor fields = ("nombre", "apellido", "carrera","user") -
Django models, pulling data from 3 models
I have the following models class IndexMaster(models.Model): index_id = models.IntegerField(primary_key=True) index_name = models.CharField(max_length=100) index_on = models.CharField(max_length=10) index_type = models.CharField(max_length=20) def __str__(self): return self.index_id class Meta: managed = True db_table = 'index_master' class StockMaster(models.Model): stock_id = models.CharField(primary_key=True, max_length=100) stock_name = models.CharField(max_length=100) class Meta: managed = True db_table = 'stock_master' class StockIndexMap(models.Model): index = models.ForeignKey(IndexMaster, on_delete=models.CASCADE, related_name= 'StockMaster_StockIndexMap_set') stock = models.ForeignKey(StockMaster, to_field ='stock_id', on_delete=models.CASCADE) class Meta: managed = True db_table = 'stock_index_map' # unique_together = (('index', 'stock'),) class StockData(models.Model): stock = models.ForeignKey(StockMaster, on_delete=models.CASCADE) day_high = models.FloatField() day_low = models.FloatField() lastvalue = models.FloatField() change = models.FloatField() percentchange = models.FloatField() class Meta: managed = True db_table = 'stock_data' serializer.py from rest_framework import serializers from .models import IndexMaster,StockIndexMap, StockMaster, StockData from indexdata.serializers import IndexMasterSerializer class StockMasterSerializer(serializers.ModelSerializer): # stock = StockIndexMapSerializer() class Meta: model = StockMaster # fields = ['index', 'stock_id', 'stock_name'] fields = [ 'stock_id', 'stock_name'] class StockIndexMapSerializer(serializers.ModelSerializer): # index = IndexMasterSerializer() stock = StockMasterSerializer() class Meta: model = StockIndexMap fields = [ 'stock'] class StockDataSerializer(serializers.ModelSerializer): stock = StockMasterSerializer() class Meta: model = StockData fields = ['stock','day_high', 'day_low', 'lastvalue', 'change', 'percentchange'] in views.py class StockMulti(generics.ListAPIView): queryset = StockIndexMap.objects.all() serializer_class = StockIndexMapSerializer pagination_class = CustomPagination permission_classes = [permissions.IsAuthenticatedOrReadOnly] def get_queryset(self): query_params = self.request.query_params indexID = query_params.get('id', … -
Saving apscheduler scheduler instance
I need to save apscheduler scheduler instance I'm worked with to remove it later or modify. I have django web app. I have notification model in django admin. After creating a new row - I schedule notification to send it later on my email. And that part work perfectly. But what if i need to change the notification or delete it? And there is problem.. with some "returns" I've got the schedule instance in my admin.py. But i can only print it to console and that's all. How and where I can save this instance to work with it later?(after delete row 4 example). -
Google Cloud run, Django and sqlite
I'm developing small single user applications in Django. Currently I do so with Heroku, which works just fine. I would like to deploy the application on Google Cloud run to have in the future a bit more flexibility. In order to keep the overhead as small as possible I was considering using Sqlite. To keep persistency all I would need is a persistent volume, which could be achived via Google Cloud storage that is mounted into the docker container via gcsfuse. But here is the issue. I can't find a small Image with python and gcsfuse. I'm not a docker pro. Just getting started... Any help is appreciated. -
DJANGO ORM equivalent of this query
what would be the django ORM equivalent of this query: select avg(julianday(strftime('%Y-%m-%d',app_casesumary.supreme_disposition_date)) - julianday(strftime('%Y-%m-%d',app_casesumary.supreme_start_date))) from app_casesumary where attorney_id='6fdf40a9d9f546803e74d31d40c9cd91'; -
Django - How to use multiple models as a Foreign Key?
In my Blank model there is a policy_type field, and I have policies folder where I've created seperated models for each policy type. For example: car.py, property.py, smartphone.py and so on. How can I use them as a QuerySet or smth else in Blank model ? Here are my codes: models.py: class Blank(models.Model): blank_series = models.CharField(max_length=3, blank=True,null=True) blank_number = models.IntegerField(blank=True, null=True) # here must be policy_type field... policies/car.py: class Car(models.Model): brand= models.CharField(max_length=3) price = models.DecimalField(decimal_places=2, max_digits=8) policies/smartphone.py: class Smartphone(models.Model): brand= models.CharField(max_length=3) price = models.DecimalField(decimal_places=2, max_digits=8) -
what is request body in Django rest framework?
create a Restful API, which works and returns the rows, satisfy the below scenarios The scenarios can be the request body Location is delhi and the planname consists of 365 Location is Hyderabad and the plan name doesnot contain the digits and the price > 1000 I created Rest API,but i want to fullfill scenarios,what is request body in Rest API -
Is select_related required when using output from bulk_create?
I have a model with a ForeignKey: class MyModel(models.Model): myfield = models.ForeignKey(AnotherModel) I have a list of MyModel objects that I create with bulk_create: obj_list = [ MyModel(**kwargs), MyModel(**kwargs), MyModel(**kwargs) ] created_list = MyModel.objects.bulk_create(obj_list) I subsequently use the foreign key in another statement: for obj in created_list: obj.myfield.attribute In such cases, Django recommends using select_related, however it's not clear to me: Is this required, as I have created the models and am not fetching them in a queryset? If it is required, how do I apply select_related in this case? -
Do I need to download file from django's database to use it?
I have django service with some .ipynb files, and I'm working on feature where user can run file in jupyter hub. My question is, do I have to download file to send it to jupyter hub, and manualy delete it when it is not needed, or is there some method to send file straight from database, without taking care of deleting it afterwards? -
How to create a UUIDField in Django that doesn't require the default func to be provided, instead returns UUID generated by the DB?
Currently the top answer for How does a Django UUIDField generate a UUID in Postgresql? says When you use UUIDField as a primary key in Django, it doesn't generate a UUID one for you, you generate it yourself before you save the object But I think it should be possible to hack a solution that allows for DB-based UUID generation. Once you have installed uuid-ossp extension in postgres CREATE EXTENSION IF NOT EXISTS "uuid-ossp"; I think it should work more or less like an AutoField. If a raw sql has been used for the table creation CREATE TABLE example( id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), ); Then raw insert will return a new random UUID as an id field. How would one go about creating a custom Field so this raw solution works with Django ORM? -
Intermittent 'NoAuthHandlerFound' boto error | django + kinesis client
Even after trying solution for: Boto3 intermittent NoAuthHandlerFound errors getting following error: [Tue Aug 04 12:55:09.460312 2020] [wsgi:error] [pid 24727:tid 140597795952384] creds = self._get_credentials_from_metadata(metadata) [Tue Aug 04 12:55:09.460342 2020] [wsgi:error] [pid 24727:tid 140597795952384] File "/usr/local/lib/python3.5/dist-packages/boto/provider.py", line 424, in _get_credentials_from_metadata [Tue Aug 04 12:55:09.460373 2020] [wsgi:error] [pid 24727:tid 140597795952384] "%s" % (msg)) [Tue Aug 04 12:55:09.460415 2020] [wsgi:error] [pid 24727:tid 140597795952384] boto.exception.InvalidInstanceMetadataError: Expected a dict type of credentials instead received an empty string [Tue Aug 04 12:55:09.460450 2020] [wsgi:error] [pid 24727:tid 140597795952384] You can set the 'metadata_service_num_attempts' in your boto config file to increase the number of times boto will attempt to retrieve credentials from the instance metadata service. I have set AWS_METADATA_SERVICE_NUM_ATTEMPTS to 4 in both on the machine & in django settings.py. When I try manual retry in code, it works but is taking too long to respond and requests get queued up throwing 502, 503 errors. Note: Authentication is via IAM role. -
Django: ValueError at /api/clients/shipping/ Cannot assign .. must be a "Purchaser" instance
I'm trying to create new object using the class model purchaserShippingDetail using the instance of Purchaser class model but my way does not work. I'm getting the error ValueError at /api/clients/shipping/ Cannot assign "<CustomUser: Admin>": "purchaserShippingDetail.owner" must be a "Purchaser" instance. Purchaser model file class Purchaser(models.Model): name = models.CharField(max_length=50) phone = models.CharField(max_length=20, unique=True) email = models.EmailField(max_length=255, unique=True, blank=True) image = models.ImageField(default='default.png', upload_to='customer_photos/%Y/%m/%d/') data_added = models.DateField(default=datetime.date.today) def __str__(self): return self.name purchaserShippingDetail model class purchaserShippingDetail(models.Model): frequent_customer = models.BooleanField(default=False) owner = models.OneToOneField(Purchaser, on_delete=models.CASCADE, related_name="purchaser_shipping") address = models.CharField(max_length=12, blank=True) zip_code = models.CharField(max_length=12, blank=True) description = models.TextField(blank=True) def __str__(self): return self.owner.name views.py file class purchaserShippingDetailsListCreateView(ListCreateAPIView): serializer_class = purchaserShippingDetailSerializer queryset = purchaserShippingDetail.objects.all() def perform_create(self, serializer): user = self.request.user serializer.save(owner=user) serializers.py class purchaserShippingDetailSerializer(serializers.ModelSerializer): owner = serializers.StringRelatedField(read_only=True) class Meta: model = purchaserShippingDetail fields = '__all__' -
Increased response time causing 502, 503 | django + apache2 + wsgi
I am continuously getting Resource temporarily unavailable: [client x.x.x.x:x] mod_wsgi (pid=x): Unable to connect to WSGI daemon process 'my-api' on '/var/run/apache2/wsgi.x.sock' and scoreboard is full, not at MaxRequestWorkers which results in lots of 502s and 503s, after my API response time changed from 150ms to 300ms after using kinesis put records API. I am guessing too many requests are queued up due to API response time increase, so going through https://modwsgi.readthedocs.io/en/develop/configuration-directives/WSGIDaemonProcess.html, listen-backlog=200 seemed like an appropriate option along with processes=4 threads=30 listen-backlog=200 I am not sure how to go about to fix the issue, can anyone help? -
Django annotate queryset by field from m2m through model
I have models BottleType and OrganisationBottleType. And i want to annotate BottleType queryset by fields 'is_accepted' and 'points' from OrganisationBottleType. OrganisationBottleType model: class OrganisationBottleType(models.Model): organisation = models.ForeignKey( 'Organisation', related_name='organisation_bottle_types', on_delete=models.CASCADE, ) bottle_type = models.ForeignKey( 'machines.BottleType', related_name='organisation_bottle_types', on_delete=models.CASCADE, ) is_accepted = models.BooleanField(...) points = models.FloatField(...) Supposed that i have organisation_id and BottleType queryset, so for each object from queryset need to find OrganisationBottleType filtered by bottle_type and organisation and annotate fields 'is_accepted' and 'points'. (When filtered OrganisationBottleType qs is found can just take first object from it, because it is assumed that the couple of fields: organisation - bottle_type is unique) My idea is to use Subquery in annotation but i can't do it right. I will be grateful for advice! -
Order by doesn't work on graphene django, what is worng with the code?
I have a user model which has filter fields and an order_by field but order_by doesn't work class UserFilter(django_filters.FilterSet): class Meta: model = User fields = {'username': ['exact', 'icontains', 'istartswith']} order_by = OrderingFilter( fields=( ('date_joined', 'username'), ) ) class UserNode(DjangoObjectType): class Meta: model = User interfaces = (graphene.relay.Node,) What is wrong with the code? class Query(object): users = DjangoFilterConnectionField(UserNode, filterset_class=UserFilter) def resolve_users(self, info, **kwargs) return User.objects.all() -
Failed to load resource: the server responded with a status of 403 (Forbidden) amazon s3
Im having issues connecting my django app to pull static files from aws s3 -
Admin Sidebar came "out of nowhere" and make the interface crash
I haven't add anything uncommon to my installed apps and didn't touch my admin.py file, here are the screens : ( it's normal looking on firefox and completly broken on chromium as you can see ) I remember downloading django-database-size but I immediately used pip-autoremove and haven't made any change to my settings.py/admin.py , do any of you know where it could possibly come from cause I'm still confused? Thanks in advance , here is my virtual environment pip list just in case : https://0bin.net/paste/e2UE4m3MF0EUaVhn#21bllXwBKbCpGrNVxX6jVBmBw1AB1yQu-po5zCI6WSh -
Django-Python : invalid literal for int() with base 10: 'None'
I am new to Django. I am trying to build a page which displays all the users who have registered on to my Website. The logic I tried to use is getting the id of a user in the built-in User Model. In views.py, I have created a class based view which is a DetailView like this from django.shortcuts import render from django.contrib.auth.models import User from django.views.generic import DetailView #I have not used a ListView class but I have used a function based View def home(request): context = { 'users': User.objects.all(), } return render(request, 'home_page/home.html', context) class UserDetailView(DetailView): model = User urls.py: from django.urls import path from .views import PostDetailView, UserDetailView urlpatterns = [ path('', views.home, name='home_page'), path('users/<pk>/', UserDetailView.as_view(), name='user-detail'), ] In home.html, I have added this: {% for user in users %} <h2><a class="article-title" href="{% url 'user-detail' user.id %}">{{ users.username }}</a></h2> {% endfor %} When I clicked on the username it redirects me to localhost:8000/users/None/ and I get this error: Exception Type: ValueError Exception Value: invalid literal for int() with base 10: 'None' Is this the right way to get the is of a user from the User Model?