Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Variables on HTML and Javascript with Serializers
The following code work fine for display Django variable on HTML. objectA is model objectBs is queryset VIEW context = { 'objectA': objectA, 'objectBs': objectBs, } HTML <table id="table1"> <thead> <tr> <th>Field1</th> <th>Field2</th> </tr> </thead> <tbody> {% for objectB in objectBs%} <tr> <td> {{ objectA.field1 }} </td> <td> {{ objectB.sub.field2 }} </td> </tr> {% endfor %} </tbody> I want to use the data on javascript then I change the code to following. VIEW context = { 'objectA': json.dumps(model_to_dict(objectA), 'objectBs': serializers.serialize('json', objectBs), } JAVASCRIPT var objectA_ = JSON.parse("{{objectA|escapejs}}") var objectBs_ = JSON.parse("{{objectBs|escapejs}}") After changed, the javascript variable work fine but the html not able to display using original django variable. Please advise the solution. Thanks. -
Show month name instead of month number in django model choice field
Column acct in table Adjustment contains month number. The following code gives a dropdown with month number (1,2,3) but I want month name (January, February, March) instead. month = forms.ModelChoiceField(queryset=Adjustment.objects.values_list('acct',flat=True).distinct(), empty_label=None) -
How to make SELECT from subquiry and JOIN with other table in Django ORM?
I'm trying to use the Django ORM for a task that need SELECT from subquiry and JOIN with other table. Models and SQL-query see below. Models class MonWork(models.Model): name = models.TextField('Monwork', null=True, blank=True) app_version = models.ForeignKey(AppVersion, verbose_name='Application version', on_delete=models.CASCADE, null=False, blank=False) class MonWorkCheck(models.Model): monwork = models.ForeignKey(MonWork, verbose_name='Monwork', on_delete=models.CASCADE) class MonWorkCheckProvider(models.Model): monworkcheck = models.ForeignKey(MonWorkCheck, verbose_name='Monwork check', on_delete=models.CASCADE) provider = models.ForeignKey(Provider, verbose_name='Provider', on_delete=models.CASCADE) status = models.SmallIntegerField('Work capacity', choices=STATUS_CHOICES, blank=True, default=STATUSES['up']) error_text = models.TextField('Error text', null=True, blank=True) SQL query SELECT monworks.id AS monwork_id, monworks.app_version_id, monworkcheck_id_latest, arm_monworkcheckprovider.provider_id, arm_monworkcheckprovider.status, arm_monworkcheckprovider.error_text FROM (SELECT arm_monwork.id, arm_monwork.app_version_id, MAX(arm_monworkcheck.id) AS monworkcheck_id_latest FROM arm_monwork LEFT JOIN arm_monworkcheck ON (arm_monwork.id = arm_monworkcheck.monwork_id) GROUP BY arm_monwork.id, arm_monwork.app_version_id) AS monworks LEFT JOIN arm_monworkcheckprovider ON (monworks.monworkcheck_id_latest = arm_monworkcheckprovider.monworkcheck_id) How to make this SQL in Django ORM? Interesting only one query to database without lists, chain() and etc. -
Django rest serializer last
this is my rest response: "srf": "1010-000-0275", "letturesrf": [ { "reading_date": "2019-12-13T17:27:53Z", "reading_value": "829621" }, { "reading_date": "2019-12-13T17:33:01Z", "reading_value": "829621" }, ] }, i want to have only the last reading and for srf and not all readings. my serializer: class LettureSerializer(serializers.ModelSerializer): class Meta: model = Letture fields = ('reading_date','reading_value') class LettureTabelle(serializers.ModelSerializer): letturesrf = LettureSerializer(many=True, read_only=True) class Meta: model = Contatore fields = ['srf','letturesrf'] view: class DateLettureViewSet(viewsets.ModelViewSet): serializer_class = LettureTabelle queryset = Contatore.objects.all() -
Flutter and django nested object problem in http post method
I follow below link to send nested object to django https://django.cowhite.com/blog/create-and-update-django-rest-framework-nested-serializers/ My classes are given: ''' class Chef(models.Model): address = models.CharField(max_length=200,default='SOME STRING') name = models.CharField(max_length=100,default='SOME STRING') email = models.CharField(max_length=100,default='SOME STRING') phoneNo = models.IntegerField(default=0) password = models.CharField(max_length=100,default='SOME STRING') class Package(models.Model): price = models.IntegerField(default=0) chef = models.ForeignKey(Chef, on_delete=models.CASCADE,related_name='package_set', null=True, blank=True) package_no=models.IntegerField(default=0) ''' The serializers are: ''' class Package_Serializer(serializers.ModelSerializer): class Meta: depth = 1 model = Package fields = '__all__' class chef_package_Serializer(serializers.ModelSerializer): package_set = Package_Serializer(many=True) class Meta: model = Chef fields = ('address', 'name', 'email', 'phoneNo', 'password', 'package_set') def create(self, validated_data): package_data = validated_data.pop('package_set') musician = Chef.objects.create(**validated_data) for album_data in package_data: Package.objects.create(chef=musician, **album_data) return musician ''' I use "Postman" to send data . { "address": "gg", "name": "dff", "email": "ggg", "phoneNo": 234, "password": "234", "package_set": [ { "price": 1500, "package_no": 1, "chef": { "address": "gg", "name": "dff", "email": "ggg", "phoneNo": 234, "password": "234" } } ] } The data saved but when I use flutter application ,the following error occurs E/flutter (21201): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: type 'List' is not a subtype of type 'String' in type cast The json serializable classes of flutter are @JsonSerializable() class Chef{ Chef( this.address, this.name, this.email, this.phoneNo, this.password, this.package_set ); final String address ; final String name ; … -
What is the cause of duplicate for forloop
I implemented a queryset that outputed friends of friend, in my template I used forloop to display the friends of friend of a user. My else tag "No friends" duplicate if there are two friends of friend of a user. I attached an image for a better understanding. class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL) friends = models.ManyToManyField('Profile', related_name='my_friends') all_friends = request.user.profile.friends.values_list('pk', flat=True) friends_of_friend = Profile.objects.filter(pk__in=all_friends) {% for data in profile_and_button_status %} #other codes here #Result of first template image {% for friend in data.0.friends.all %} {% if friend in friends_of_friend %} {{ friend }} {% else %} No friend {% endif %} {% endfor %} #Result of second template image {% for friend in friends_of_friend %} {% if friend in data.0.friends.all %} {{ friend }} {% else %} No friend {% endif %} {% endfor %} {% endfor %} -
RadioButton in django
I don't understand how to implement django interaction with RadioButton. In the file models.py I have the "room_status" object attribute. I want the browser page to display the rooms that will be selected in RadioButton. html <div class="btn-group btn-group-toggle" data-toggle="buttons"> <label class="btn btn-secondary "> <input type="radio" name="options" id="option1" autocomplete="off" checked> All rooms! </label> <label class="btn btn-secondary"> <input type="radio" name="options" id="option2" autocomplete="off"> Men's rooms! </label> </div> How do I link my html to django? -
Django link table row to view
new to coding. I'm creating an inventory table'with the django framework. I'd like to be able to click on a table row (which is a part) that will then parse that row/part information to a detail view. from what I understand table rows are inline elements and inline elements are psuedo code which current HTML does not allow for an anchor tag to be thrown in (bad practice?) so I need to use some javascript. Currently, the inventory view shows when I use runserver (http://127.0.0.1:8000/inventory/) but clicking on any row does nothing. Here is what I have so far; inventory.html {% extends "base.html" %} {% block body %} <br> <table class="table table-hover"> <thead> <tr> <th>Part Number</th> <th>Description</th> <th>Location</th> <th>Supplier</th> <th>S.O.H</th> </tr> </thead> <tbody> {% for part in parts %} <!-- need to make these table rows link to their respective parts class="table_row" href="{{ selected_part.partnumber }}/detail">{{ selected_part.partnumber }}--> <tr data-href="{% url 'detail' part.pk %}"> <td>{{ part.pk }}</td> <td>{{ part.partnumber }}</td> <td>{{ part.description }}</td> <td>{{ part.location }}</td> <td>{{ part.supplier }}</td> <td>{{ part.stockonhand }}</td> </tr> {% endfor %} </tbody> </table> {% endblock %} urls.py from django.urls import path from .views import * urlpatterns = [ path('inventory/', inventory_list, name='inventory'), # URL path for inventory_list … -
ProgrammingError django postgresql on hosting
I installed postgresql on hosting and it gives an error although everything works fine on the local server -
Django unittest cases
I am trying to run all the management commands for test_db for static details. Have to run just before the test cases. Have to be run only once for all test cases. I've used setUpTestData but did not help me. Basically I wanna reduce the running time of all test cases. Thanks -
Calculating the 'most recently used' of a django ManyToMany relation
I have a simple Tag model that many other models have a ManyToMany relationship to. The requirement has come up to be able to query/show the most recently used Tags in the system, across all entities that have Tags. I can add a used_at attribute to the Tag model, and I could order on that. But obviously, the Tag model doesn't get modified when something else just references it, so an auto_now on that attribute won't help me. Without the use of a through model (which could have an auto_now_add on it), and without performing any invisible (non-django) magic directly in the DB with triggers, is there a sensible way to update the Tag's timestamp whenever a model is saved that references it? -
Django checkout form not valid, Page not found (404)
Hi I'm trying to develop an e-commerce site with Django. So I'm at this point where, users can add items to their cart, but when I try to proceed to checkout, for some reason, my checkout form is not displayed rather, it says: Page not found (404), i.e my form is not valid. I made sure that I have registered my models, and ran migrations. I printed out form.errors and it says: Not Found: /checkout/. What is the problem? Can anyone please help me out? My views.py: @login_required def checkout(request): address_form = UserAddressForm(request.POST or None) if address_form.is_valid(): new_address = address_form.save(commit= False) new_address.user = request.user new_address.save() return HttpResponseRedirect('/') else: raise Http404 print(form.errors) context = {"address_form": address_form} template = "orders/checkout.html" return render(request, template, context) My checkout.html: <form method="POST" action=''> {% csrf_token %} <fieldset class="form-group"> {{ address_form|crispy }} </fieldset> <div class="form-group"> <input type="submit" class="btn btn-outline-dark" value="Place Order"/> </div> </form> My ursl.py: from orders import views as orders_views path('checkout/', orders_views.checkout, name='checkout'), -
How can i call a an API from POST request in Django?
I am using Djangorestframework. Ny views.py: class SchemaViewSet(mixins.CreateModelMixin, mixins.ListModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet): """Handles creating, reading schema""" serializer_class = serializers.SchemaSerializer queryset = models.Schema.objects.all() my Serialziers.py: class SchemaSerializer(serializers.ModelSerializer): """Serializes Schema""" class Meta: model = models.Schema fields = ( 'id', 'name', 'version','attributes',) my models.py: class Schema(models.Model): """Database model for Schema """ #id = models.IntegerField() idid = models.TextField() name= models.TextField() version = models.TextField() attributes = models.TextField() num = models.IntegerField( null=True, blank=True) def __str__(self): return self.idid This is what my api page looks: When i click on POST, it should call a different Post api with parameter i have entered here. How do i do that? -
Multiple Authentication classes Django doesn't try all the classes, fails at first
'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.TokenAuthentication', 'rest_framework.authentication.BasicAuthentication', 'michan_api.utils.validators.ExampleAuthentication' ), So I have this configured in my REST_FRAMEWORK setting in DRF. But it doesn't try all the classes.If the first one throws an exception it fails. for authenticator in self.authenticators: try: user_auth_tuple = authenticator.authenticate(self) except exceptions.APIException: self._not_authenticated() raise This piece of code is responsible for this. (https://github.com/encode/django-rest-framework/blob/master/rest_framework/request.py#L373) How do I make it try all the classes? -
how to securely publish my django website (security of backend code from being read by visitors)
I have written the backend code of a website by Django. I must publish this project for my other classmates to see the website. I want to rent a windows based host and put my code there and then give the link of my domain to them. But I really need to be sure that nobody even my classmates or others can access to download or read my backend codes. I want they have just access to work with the web site (for example they just be able to see home page, login page, and be able to register to my website and...). This is really important for me. How can I protect my backend code (or even just the most important part of that) from reading? I have heard that there is a solution which needs I put my backend codes in a folder and set a password for it. Is it correct? If so, I don't know how to do that. This is the first time I am publishing a website. Any help would be greatly appreciated. -
Write serializer for a model having multiple foreign key in django rest framework
I am building an api for CRUD operations on a user table which has association with country and state tables as given model definitions: class Country(models.Model): """ Model for Country""" country_abbreviation = models.CharField(max_length=80) country_name = models.CharField(max_length=80) is_active = models.SmallIntegerField() def __str__(self): return self.country_name class State(models.Model): """ model for saving state""" state_name = models.CharField(max_length=32) state_abbreviation = models.CharField(max_length=8) country = models.ForeignKey(Country, related_name='states', on_delete=models.CASCADE) is_active = models.SmallIntegerField(default=1, blank=True) def __str__(self): return self.state_name class Meta: """ meta class""" ordering = ('state_name', ) class User(models.Model): """ model for saving user information """ first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) country = models.ForeignKey(Country, related_name='user_country', on_delete=models.CASCADE) state = models.ForeignKey(State, related_name='user_state', on_delete=models.CASCADE) address = models.CharField(max_length=150) def __str__(self): return '%d: %s %s' % (self.id, self.first_name, self.last_name) class Meta: """ meta class """ ordering = ('first_name', ) I am writing serializers in a way that while I am getting records from user table, for every row in the table there must be available all the country and state info associated with that particular row instead of just their ids respectively: class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['id', 'first_name', 'last_name', 'country', 'state', 'address'] Expected response : { "count": 1, "next": null, "previous": null, "results": [ { "id": 1, "first_name": … -
Create alias for filtering ChoiceField in django-filters
I have following filterset for some model: class MyModel(models.Model): STATUS_ACTIVE = 0 STATUS_DONE = 1 STATUSES = ( (STATUS_ACTIVE, 'Active'), (STATUS_DONE, 'Done'), ) status = models.IntegerField(choices=STATUSES, default=STATUS_ACTIVE) class ModelFilter(FilterSet): status = ChoiceFilter(choices=MyModel.STATUSES) class Meta: model = MyModel fields = ( 'status', ) When I make request to some API, i should use status as number - /app/model?status=0. How to make alias for it, so that i can use /app/model?status=running instead of number, without changing model? -
Django not connected to the database?
I deployed an app to Heroku and it was successful,however, the data from the SQLite3 database was not loaded online. So I tried to dump data locally and then load it but when I checked my project locally. The database is not connected to the project and because of that, it's not showing any data even locally. It gives me no error but now how can I now reconnect my sqlite3 database to my project so I can dump it and then load to Heroku. Here are my settings for the database which seems correct DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } -
How can i call an different API from Post request in Django?
I am new to Django and django restframework. I am using Django Rest framework to create API. What i am trying to do is call a diffrent api when post request is made.Ex: I have name, attribute, version in my serializer class. So when post is called, it should call the api on swagger with parameter name,attribute and version. I can do that by doing something like that in my create function of viewset. But how do i edit that. response = requests.post( f"{AGENT_URL}/schemas", json=request_body, return HttpResponse() my view.py: class SchemaViewSet(mixins.CreateModelMixin, mixins.ListModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet): """Handles creating, reading schema""" serializer_class = serializers.SchemaSerializer queryset = models.Schema.objects.all() My model.py file: class Schema(models.Model): """Database model for Schema """ #id = models.IntegerField() idid = models.TextField() name= models.TextField() version = models.TextField() attributes = models.TextField() num = models.IntegerField( null=True, blank=True) def __str__(self): return self.idid my serializers.py: class SchemaSerializer(serializers.ModelSerializer): """Serializes Schema""" class Meta: model = models.Schema fields = ( 'id', 'name', 'version','attributes',) -
Downloading new language texts from server in i18n system in React App
I want to create a React App with localization and supporting several languages that switches between languages via /?lng=en and things like this. I use i18n and this tutorial: https://react.i18next.com/legacy-v9/step-by-step-guide But this system works at client side and browser must download entire languages inside JS file. I don't want this. I need speedy and light App and need to download new languages texts from the server, Each time user selects new language. I need to render new UI each time user selects new language. What I have to do? My backend is Python(Django) -
How do I remove all labels in my crispy form layout?
so I've seen some similar questions regarding the labels of crispy forms, such as: self.helper.form_show_labels = False I put this in the class in my forms.py. However I keep on getting this error message: self.helper.form_show_labels = False NameError: name 'self' is not defined What have I done wrong? This is my forms.py BTW. from crispy_forms.helper import FormHelper class MyInputForm(forms.ModelForm): self.helper.form_show_labels = False -
Module is not imported after sys.path.append()
I am trying to deploy my django application. Like many others I faced the problem of "missing" django, no module named django, though it exists. I had to install Django of version 2, not the newest and it was installed into '/home/ivan/.local/lib/python3.5/site-packages/'. I have my apache configured and wsgi module looks like this: """ WSGI config for mysite project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/2.2/howto/deployment/wsgi/ """ import os import sys sys.path.append('/home/ivan/.local/lib/python3.5/site-packages/') print(sys.path) # import /home/ivan/.local/lib/python3.5/site-packages/django from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings') application = get_wsgi_application() When I type python3 in terminal and do this: >>> import django >>> django.__path__ ['/home/ivan/.local/lib/python3.5/site-packages/django'] So I got my path of django module and I append it, I also tried: sys.path.insert(0, '/home/ivan/.local/lib/python3.5/site-packages/django') and still I got 500 error with annoying: [Tue Apr 21 13:12:41.861348 2020] [wsgi:error] [pid 29470] [remote 185.201.90.67:1131] Traceback (most recent call last): [Tue Apr 21 13:12:41.861379 2020] [wsgi:error] [pid 29470] [remote 185.201.90.67:1131] File "/var/www/mysite/mysite/wsgi.py", line 15, in <module> [Tue Apr 21 13:12:41.861384 2020] [wsgi:error] [pid 29470] [remote 185.201.90.67:1131] from django.core.wsgi import get_wsgi_application [Tue Apr 21 13:12:41.861397 2020] [wsgi:error] [pid 29470] [remote 185.201.90.67:1131] ImportError: No module named 'django' Why wsgi cannot … -
How to check whether birthday is tomorrow in django?
I am checking whether students birthday is today or tomorrow in Python. In every loop it is getting birthday is not today even I changed DOB column to today date. How can I solve this? Below is the code. Views.py def Birthday_alert(): students= Students.objects.all() tmr= dt.date.today()+ dt.timedelta(days=1) tmr_bdays=[] to_bays=[] # verifying if date of today is working or not for m in students: if m.dob == dt.date.today(): print(m.name) # putting into dictionary for s in students: if s.dob == dt.date.today(): to_bays.append({ 'name': 's.name', 'course': 's.course.class_name', 'dob' : 's.dob', 'contact': 's.parent_contact', }) elif s.dob + dt.timedelta(days=1) == tmr: tmr_bdays.append({ 'name': 's.name', 'course': 's.course.class_name', 'dob' : 's.dob', 'contact': 's.parent_contact', }) else: for m in students: print("else:",m.name) return (tmr_bdays,to_bays) models.py class Students(models.Model): created_by = models.ForeignKey( User, on_delete=models.SET_NULL, default=1, null=True) name = models.CharField(max_length=200, null=True) dob = models.DateField(null=True, verbose_name='Date of Birth') age = models.IntegerField() grade_choice = ( ('G1', 'Grade-1'), ('G2', 'Grade-2'), ('G3', 'Grade-3'), ('G4', 'Grade-4'), ('G5', 'Grade-5'), ('G6', 'Grade-6'), ('G7', 'Grade-7'), ('G8', 'Grade-8'), ('G9', 'Grade-9'), ('G10', 'Grade-10'), ('G11', 'Grade-11'), ('G12', 'Grade-12'), ) gender_choice=( ('M', 'Male'), ('F', 'Female'), ('N', 'None'), ) blood_choice=( ('O', 'O'), ('A-', 'A-'), ('B+', 'B+'), ('B-', 'B-'), ('A+', 'A+'), ('AB', 'AB'), ) relation_choice=( ('Uncle', 'Uncle'), ('Aunty', 'Aunty'), ('Father', 'Father'), ('Mother', 'Mother'), ('Grandpa', 'Grandpa'), … -
Django ProgrammingError relation does not exist
I am having this problem ProgrammingError at /admin/telegram/phonenumber/ relation "telegram_phonenumber" does not exist LINE 1: SELECT COUNT(*) AS "__count" FROM "telegram_phonenumber" I have already tried all solutions, nothing helped. So I pulled new models then did make migrations and migrate , and one of my models was giving column does not exist on table , I checked it in database , indeed it does not. So I did all the solutions from stackOverflow I could, and now I am in 'relations does not exist ' with just 0001initmigration.py it has my columns and tables but they are not being applied after python manage.py migrate -
Django custom UserCreationForm doesn't use CustomUserManager to create object
I wrote a SchoolMember model that inherits from AbstractUser and which adds the fields is_teacher and is_student. I also added SchoolMemberManager that implements a create function requiring few arguments. I then wrote a SchoolMemberCreationForm that is set to be the add_form variable in SchoolMemberAdmin. My problem is that when I create a SchoolMember from the admin interface, the create function of the SchoolMemberManager is never called because the SchoolMemberCreationForm inherits from UserCreationForm which calls save instead of create. That means that even if I can create the SchoolMember user, some settings are not correctly defined... I'm new to Django and I don't know where I should act...