Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
drf-yasg provides wrong paths to URIs
I need to display multiple Swagger pages with grouped endpoints. One of my paths supplies mobile app, another supplies web client. URL patterns are kept in 2 different urls.py accordingly. To generate swagger specification for those I'm initializing 2 separate schema_views for each urls.py file like this: from api_mobile.urls import urlpatterns as mobile_patterns from api_web.urls import urlpatterns as web_patterns mobile_schema_view = get_schema_view( openapi.Info( title="Mobile API", default_version='v3', ), public=True, permission_classes=(permissions.AllowAny,), patterns=mobile_patterns, ) web_schema_view = get_schema_view( openapi.Info( title="Web API", default_version='v1', ), public=True, permission_classes=(permissions.AllowAny,), patterns=web_patterns, ) urlpatterns = [ path( 'api/mobile/docs', mobile_schema_view.with_ui('swagger', cache_timeout=0), name='mobile-schema-ui' ), path( 'api/web/docs', web_schema_view.with_ui('swagger', cache_timeout=0), name='web-schema-ui' ), path('api/mobile/v3/', include('api_mobile.urls'), name='mobile_urls'), path('api/web/v1/', include('api_web.urls'), name='web_urls'), ... ] Where mobile_patterns and web_patterns are just a list of url patterns. If I open http://localhost:8000/api/mobile/docs or http://localhost:8000/api/web/docs I do see correctly generated schema for both lists of patterns, yet if I try to do a request directly from swagger specification page all endpoints return 404 error – they all try to do a request without providing full path to endpoint. So if I do a request to any view from mobile endpoints swagger tries to do a request at http://localhost:8000/some_mobile_url/ instead of http://localhost:8000/api/mobile/v3/some_mobile_url/ And situation is the same for another schema: Swagger wrongly requests … -
Filter and get VS Q()
Is there any performance differences between using: Transaction.objects.filter(profile=request.user).get(id=transaction_id) VS Transaction.objects.filter(Q(profile=request.user) & Q(id=transaction_id)).first() And which one should be used over the other? -
OperationalError at /admin/login/ no such table: django_site
When I try go to the admin/login I get error. OperationalError at /admin/login/ no such table: django_site settings INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', ] SITE_ID = 1 migrations account [X] 0001_initial ... admin [X] 0001_initial ... auth [X] 0001_initial ... contenttypes [X] 0001_initial [X] 0002_remove_content_type_name sessions [X] 0001_initial sites [X] 0001_initial [X] 0002_alter_domain_unique console ./manage.py makemigrations No changes detected Traceback How to fix it? Thanks. -
How can I convert a dataframe to csv and save it to return it?
I'm reading a .xlsx file and converting it to .csv but I need to return it as a .csv on a because I don't have access to the path where it should be storage. I'm only have been able to return it as a data frame. Any help will be really appreciated. Thanks. import pandas as pd def excel_to_csv(myfile): print(myfile) data_xls = pd.read_excel(myfile, index_col=None) data_xls.to_csv(encoding='utf-8', index=False) return(myfile) -
Character encoding issue when using Python3/mysqlclient to retreive data encoded in latin1
I'm running into a character encoding issue when retrieving data from an older database that is using latin1 encoding. The problem is occurring when I try to retrieve characters from the database that fall in the \x80 to \x9f range, which is the range that is different between MySQL's latin1 (aka windows-1252 in Python) and the official latin1 (ISO-8859-1). This is the stack that I'm using: MySQL database server version 5.1 with latin1 encoding at the column level and latin1-swedish-ci collation at the table level. Django version 2.2 using Python3 and mysqlclient version 1.4.4. As an example, I'm trying to retrieve the word "Isn't" from the database where the apostrophe is encoded as \x92. If I don't pass a charset to the mysqlclient connection through Django settings, I get the error "'utf-8' codec can't decode byte 0x92 in position 5: invalid start byte". If I pass latin1 as the codec to the connection, there is no error but the word renders to the page as "Isn t", with blank space where the apostrophe should be. When I open up a separate python shell session and try the connection from the python command line, the result is "Isn\x92t". >>> import MySQLdb … -
Trouble extracting multiple HTML DOM elements for AJAX with Django
I'm trying to implement a feature on a web app where I have a menu of pizzas, and the price listed on each card (feature taken from Bootstrap) dynamically updates depending on the style (regular/sicilian), size (small/large) and name (cheese/special) of pizza selected. I'm using a loop to create all the cards by querying the database using ORM in the backend, which takes all existing pizzas the restaurant owner adds, and makes a menu item for each one. Then, I'm aiming to extract the name, style, and size selections for each, and give a dynamic render of the price of that specific type of pizza in the price area of the card, using AJAX, before implementing the checkout functionality whereby a user buys that pizza. The problem is mainly that I'm unsure how to extract the name, style, and size selections given that the cards are implemented using a templating loop, and also I think there are a few small errors littered through my AJAX/backend. But I suspect the solution would be something to do with Javascript's ForEach() after I extract an array of the styles from the cards? I really don't know how I'd go about proceeding. My code … -
Avoid nested objects when using nested serializers
I have two models, one contains the other in a foreignKey relationship, I wanted to make an API that would return the combine of these two models, so I attempted to use nested Serializers to add the related model as well, but the data are not all on the same level, the related models is a object inside the first. Here are the Models class ModelOne(models.Model): last_counter = models.IntegerField() class ModelTwo(models.Model): model_one = models.ForeignKey(ModelOne, on_delete=models.CASCADE) category = models.CharField(max_length=64) counter_type = models.CharField(max_length=32) Here are the serializers class ModelOneSerializer(serializers.ModelSerializer): class Meta: model = ModelOne fields = "__all__" class ModelTwoSerializer(serializers.ModelSerializer): model_one= ModelOneSerializer(read_only=True) class Meta: model = ModelTwo fields = "__all__" This would return from the API in the form of { "category" : ..., "counter_type" : ..., "model_one" : { "last_counter" : ... } } But I don't want the response to be like that, I want it more like this { "category" : ..., "counter_type" : ..., "last_counter" : ..., } Is there a way to achieve this through serializers? -
Nested serializers: Could not resolve URL for hyperlinked relationship using view name
I've looked up this error but the answers posted earlier aren't working for me. I'm trying to set up nested serializers/views with HyperLinkedIdentityFields in Django Rest Framework but I'm getting the following error: Could not resolve URL for hyperlinked relationship using view name "customers-report-detail". You may have failed to include the related model in your API, or incorrectly configured the lookup_field attribute on this field. I have the following setup: urls.py urlpatterns = [ path('<pk>/reports/<report_nr>/', ReportApiDetail.as_view(), name='customers-report-detail'), path('<pk>/reports/', ReportApiList.as_view(), name='customers-report-list'), path('<pk>/', CustomerApiDetail.as_view(), name='customer-detail'), path('', CustomerApiList.as_view(), name='customer-list'), ] views.py class CustomerApiList(generics.ListAPIView): queryset = Customer.objects.all() serializer_class = CustomerListSerializer class CustomerApiDetail(generics.RetrieveAPIView): queryset = Customer.objects.all() serializer_class = CustomerDetailSerializer class ReportApiList(generics.ListAPIView): serializer_class = ReportListSerializer queryset = Report.objects.all() def get_queryset(self, *args, **kwargs): pk = self.kwargs['pk'] report_nr = self.kwargs['report_nr'] return self.queryset.filter(customer_id=pk, report_nr=report_nr) serializers.py class ReportDetailSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Report fields = ['id', 'customer_id', 'report_nr', 'title', 'date_created', ] class ReportListSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Report fields = ['url',] class CustomerDetailSerializer(serializers.ModelSerializer): reports = serializers.HyperlinkedRelatedField( many=True, read_only=True, view_name='customers_report_detail' ) class Meta: model = Customer fields = ['pk', 'name', 'reports',] class CustomerListSerializer(serializers.HyperlinkedModelSerializer): # reports = serializers.SerializerMethodField('get_customer_orders') class Meta: model = Customer fields = ['url', 'pk', 'name', ] -
This code is returning the error 'local variable 'name' referenced before assignment'.I am trying to keep a form and formset together
I am trying to make a form and formset work together which are not related to each other.Any suggestions if there are easy solutions to this? def resume(request): form=ResumeForm(request.POST) ExperienceFormSet=formset_factory(Experience) formset=ExperienceFormSet(request.POST,request.FILES) print(form.is_valid) if request.method=='POST': if form.is_valid() and formset.is_valid(): name=request.POST.get('name') email=request.POST.get('email') phone=form.cleaned_data['phone'] objective=request.POST.get('objective') branch=request.POST.get('branch') course=request.POST.get('course') course_total=course+' in '+branch department=request.POST.get('department') other_link=request.POST.get('other_link') for f in formset: cd=f.cleaned_data companyName=cd.get('companyName') print(companyName) else: form=ResumeForm() ExperienceFormSet=formset_factory(Experience) formset=ExperienceFormSet() return render(request,'resume.html',{'name':name,'email':email,'phone':phone,'objective':objective,'course_total':course_total,'department':department,'other_link':other_link}) -
How to add custom css to Bootstrap/Django files
I am trying to add a custom css snippet into my code for my homepage(index.html)but am new to bootstrap/css and not sure which file to add the code to. So far, I've tried adding the snippet to a custom.css file within the same directory as my html files but nothing is changing. Would I instead add this to index.html file? Can you even add css to an html file? Example of code snippet im trying to add: body { background: url('https://source.unsplash.com/twukN12EN7c/1920x1080') no-repeat center center fixed; -webkit-background-size: cover; -moz-background-size: cover; background-size: cover; -o-background-size: cover; } -
Django: how to specify `include_blank=False` in `modelform_factory` using `formfield_callback`?
I am using the django.forms.modelform_factory() function. Some of the database fields are IntegerFields with choices, so Django defaults to using a django.forms.TypedChoiceField that has a blank choice ("--------------"). I'm using the RadioSelect widget, so it's redundant to have a blank choice. How do I get rid of the blank choice? (I'm answering my own question, but of course if you have a better answer, feel free to share!) -
Unable to add two foreign keys to the user model in django
I have a user model which I have extended to store extra information. Now I have a department table which has two keys(foreign) which will be related to the columns in the user table. But I am getting an error. This is what I have tried models.py from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver # Create your models here. class Profile(models.Model): STATUS_CHOICES = ( (1, ("Permanent")), (2, ("Temporary")), ) GENDER_CHOICES = ( (1, ("Male")), (2, ("Female")), (3, ("Not Specified")) ) user = models.OneToOneField(User, on_delete=models.CASCADE) emp_type = models.IntegerField(choices=STATUS_CHOICES, default=1) contact = models.CharField(max_length=13, blank=True) whatsapp = models.CharField(max_length=13, blank=True) gender = models.IntegerField(choices=GENDER_CHOICES, default=3) avatar = models.ImageField(upload_to='users/images', default='users/images/default.jpg') manager_username = models.ForeignKey(User, blank=True, null=True, related_name='usernames', on_delete=models.DO_NOTHING) def __str__(self): return self.user.username @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() class Department(models.Model): id = models.IntegerField(primary_key=True) name = models.CharField(max_length=20, unique=True) manager = models.ForeignKey(User, blank=True, null=True, related_name='manager_usernames', on_delete=models.DO_NOTHING) tech_lead = models.ForeignKey(User, blank=True, null=True, related_name='usernames', on_delete=models.DO_NOTHING) Error message ERRORS: users.Department.tech_lead: (fields.E304) Reverse accessor for 'Department.tech_lead' clashes with reverse accessor for 'Profile.manager_username'. HINT: Add or change a related_name argument to the definition for 'Department.tech_lead' or 'Profile.manager_username'. users.Department.tech_lead: (fields.E305) Reverse query name for 'Department.tech_lead' … -
Android device can not connect Django websocket
I built an app with a chat function using Django channels, everything works fine, I can connect to it from iOS simulator, iOs Device, even with an Android simulator, but when I launch it on an actual android device (Huawei Pro) It seems it does not want to connect. What can cause an issue like this? Should I implement something in my Android code or is it a specific problem with Huawei? I use JavaScript's WebSocket to connect to it. -
Django Rest Framework AttributeError when trying to serializering table that acts many to many relation
i am facing an error that says : Got AttributeError when attempting to get a value for field name on serializer productsserializer. The serializer field might be named incorrectly and not match any attribute or key on the branch_products instance. Original exception text was: 'branch_products' object has no attribute 'name'. my models: class products(models.Model): name=models.CharField(max_length=50) Barcode=models.IntegerField() price=models.FloatField(null=True) prev_price=models.FloatField(blank=True,null=True) category=models.ForeignKey(category,on_delete=models.CASCADE) description=models.TextField() image=models.ImageField(upload_to='pics',default='') def __str__(self): return self.name class branch(models.Model): QR_code=models.CharField(max_length=30) def __str__(self): return self.QR_code class branch_products(models.Model): product=models.ForeignKey(products,on_delete=models.CASCADE) branch=models.ForeignKey(branch,on_delete=models.CASCADE) quantity=models.IntegerField() and this is my serializers: class branchserializer(serializers.ModelSerializer): class Meta: model=branch fields=['QR_code','id'] class productsserializer(serializers.ModelSerializer): category=serializers.SerializerMethodField() class Meta: model=products fields=['id','name','Barcode','price','prev_price','description','image','category'] def get_category(self,obj): return categoryserializer(obj).data class productbranchserializer(serializers.ModelSerializer): branch=serializers.SerializerMethodField() product=serializers.SerializerMethodField() class Meta: model=branch_products fields=('product','branch','quantity','id') def get_branch(self,obj): return branchserializer(obj).data def get_product(self,obj): return productsserializer(obj).data it seems that it takes a value from wrong place or wrong Serializer -
django_graphene looking for package "six" in the wrong place?
I'm trying to use graphene-django, and a having some issues with the "six" package. It's installed, but it's installed as its own package, and graphene-django seems to be expecting it under django.utils File "C:\Users\mjnic\.virtualenvs\phoenix-demo-C42C_PgQ\lib\site-packages\graphene_django\settings.py", line 18, in <module> from django.utils import six ImportError: cannot import name 'six' from 'django.utils' (C:\Users\mjnic\.virtualenvs\phoenix-demo-C42C_PgQ\lib\site-packages\django\utils\__init__.py) I've checked the source for graphene_django and in the settings.py it seems to be looking specifically at the django path. This module provides the `graphene_settings` object, that is used to access Graphene settings, checking for user settings first, then falling back to the defaults. """ from __future__ import unicode_literals from django.conf import settings from django.test.signals import setting_changed from django.utils import six I'm using pipenv to manage my environment, and I've uninstalled and reinstalled six, and the various graphene packages several times now trying to sort this out, to no avail. So how can I either move the installation of six so that it's located at django.utils.six, alternatively change the setup so that graphene-django is looking at the currently installed location instead (doesn't seem possible looking at the source)? -
Django test ignore a part of the response
doctest has ellipsis (three dots) which can be used to ignore a part of the string while running a test, for example in this case for a JSON string the value of the field id will be ignored: { id: ..., name: "John" } Is there something convenient like that when writing an application using Django + Django Rest Framework without using explicit regular expressions? -
PythonAnywhere: django.db.utils.OperationalError: no such table:
I am deploying a project on PythonAnywhere. I am using sqlite database. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'mydatabase.db', } } When makemigrations starts, the file mydatabase.db is created (its size is 0 bytes) in root of the project, but I get an error - django.db.utils.OperationalError: no such table: ... -
Is there a way to iterate throw annotate sum query in django
Is there a way to make that for loop in query emp_id = 1 qs= Employee.objects.get(id = emp_id ) InitialSalary =qs.Salary qs1 = AnnualIncrease.objects.filter(employee_name_id = emp_id, startDate__range =(qs.Emp_date,timezone.now()) ).exclude(approveDate=None, submitDate =None).order_by('employee_name_id', 'startDate' ) ActualSalary = InitialSalary for x in qs1: ActualSalary = float(ActualSalary) + (float(ActualSalary)* float(x.AnnualIncreasePercent)/100) + float(x.AnnualIncreaseDecimal) I already try the below and it work but this don't get the needed result of course qss1 = AnnualIncrease.objects.filter( startDate__lte= timezone.now() ).order_by('employee_name_id', 'startDate' ).values( 'employee_name_id', 'employee_name__Salary' ).exclude( approveDate=None, submitDate =None).annotate( ActualSlary = Sum(ExpressionWrapper( F('employee_name__Salary')+ (F('employee_name__Salary')*Coalesce(F('AnnualIncreasePercent'),Value(0))/Value(100))+ Coalesce(F('AnnualIncreaseDecimal'),Value(0)) ,output_field = FloatField()) )) -
python logic for getting output from different variables
id subid num cd val o/p 123 333 2546 1 3 123 222 6545 1 2 123 545 Z3245 1 5 456 784 5423 1 6 456 478 Z3245 1 2 456 470 5623 1 8 I have defined the above table as a class and the columns as an object in Django Models.py file. I'm passing all the above variables/columns as a one by one value by 'id' column into a function for each 'id' specific. I will define a list x = [6545, 5423] before, which comes from num column. For eg: id = 123 (It is associated with three subid) subid = I have three values which i need to iterate it and get its specific num column values. num = if 'num' value is exists in 'x' list as mentioned above from specific id then, 'val' column value which is 5 for 'Z3245' should be printed as o/p value. so o/p value should come as 5. Rest of the o/p values can be ignored. similarly for 456 id the z3245 value should be 2 as o/p, 5423 existed in x list above for specific id. cd = All these should be happened under the condition if … -
Moved legacy classic asp web site to django app but having trouble with django URL redirect app - old URLs with parameters get 500 error
I moved a 20 year old classic asp web site to a django app recently. Google Search Console is showing 500 errors for tons of very old URLS with parameters like /somefile.asp?ID=1234&name=some-name. Most of these URLS I don't even care about - they are really old but would rather they result in 404 than 500. Some do relate to newer content and in theory I could redirect to new django pages but when I try to redirect them using the django redirect app, the site shows 500 errors - like the ? either stops the pages from ever getting to the redirect middleware or the redirect app doesn't like the "?". How can I redirect these urls so I don't get 500 errors? Is there a way in a view to say: if the full url path is x redirect to full url path y I have looked all over stack overflow and elsewhere and can't find this exact problem or a way to write a view like this. I did try the solution here (exactly) because it seems closest to my issue, but it did not work for me for this exact problem: Django's redirects app doesn't work with … -
How to implement direct messaging in Django?
I'm trying to figure out how to allow my users to direct message each other. The only caveat is that messaging is only allowed while a transaction between the two users is in progress, so there will be one thread of messages for each Transaction. I have a Transaction model, and at first I was thinking I could add a field to the Transaction model that would be an array of message objects, but there does not seem to be a model field for that (but perhaps I'm wrong). Instead, should I create a separate model, i.e. Thread, for the thread of messages related to the transaction? Thanks for any advice. -
Django-forms: Raise forms.ValidationError not working
I am beginner in Django and recently studied form-validation. I implemented the code but was unable to raise ValidationError for some constraints. Here are my subsequent file content. forms.py from django import forms from django.core import validators class formClass(forms.Form): name = forms.CharField(max_length=128) email = forms.EmailField(max_length=256) text = forms.CharField(widget=forms.Textarea) catchBot = forms.CharField(required=False, widget=forms.HiddenInput, validators=[validators.MaxLengthValidator(0)]) def clean(self): cleaned_data = super(formClass, self).clean() t = self.cleaned_data.get('name') if t[0].lower() != 'd': raise forms.ValidationError('Name must start from d.') return cleaned_data views.py from django.shortcuts import render from formApp import forms from django.http import HttpResponseRedirect def formNameView(request): formObj = forms.formClass() formDict = {'form': formObj} if request.method == 'POST': formObj = forms.formClass(request.POST) if formObj.is_valid(): # SOME CODE print("NAME: " + formObj.cleaned_data['name']) print("EMAIL: " + formObj.cleaned_data['email']) return HttpResponseRedirect('/users') return render(request, 'formApp/forms.html', context=formDict) My valid input works great, but it doesn't happen with my invalid input. for example: if name = 'Alex', it should raise an error. But it doesn't. Could someone please help me in it? -
Set up connection between azure redis cache and azure kubernetes service
Please help me in setting up the connection between azure redis cache and aks. I am building an application where I would like to deploy it in aks and add redis as a service. -
django-elasticsearch-dsl with AWS elasticsearch
I'm trying to use AWS ElasticBeanStalk to deploy a Django app using django-elasticsearch-dsl and I need to run ./manage.py search_index --rebuild the first time I load it. So within my container commands I've got: 03_elasticsearch: command: "source /opt/python/run/venv/bin/activate && ./src/manage.py search_index --rebuild" The problem is it is waiting for a n/Y to the question Are you sure you want to delete the 'hjsm-local' indexes? [n/Y]: How do I rebuild my indecies? -
How to get the a value related in a Foreign key Django
Im trying to get the value from an attribute related when I select something in a foreing key, and then I want to put that value in a new field, this is the table when I want to do this: table I know I need to implement javascript but im new in django and I dont know how to get the values and then set it in the new field. My Models: class Producto(models.Model): producto = models.CharField(max_length=100) descripcion = models.CharField(max_length=200) precio = models.DecimalField(max_digits=10, decimal_places=2, default=0) LOAN_CATEGORIA = ( ('p', 'Platillo'), ('b', 'Bebida'), ) categoria = models.CharField(max_length=1, choices=LOAN_CATEGORIA, blank=False, default='p', help_text='Categoria del Producto') imagen = models.ImageField(upload_to='photos') def get_absolute_url(self): return reverse('control:producto-detail', args=[str(self.id)]) def __str__(self): return self.producto class Pedido(models.Model): total = models.DecimalField(max_digits=10, decimal_places=2, default=0) fecha = models.DateField(default=datetime.now, null=True, blank=True) estado = models.CharField(max_length=20, default='Pendiente') def get_absolute_url(self): return reverse('control:pedido-detail', args=[str(self.id)]) def __str__(self): return "[" + str(self.id) + "][" + str(self.fecha) + "] " class DetallePedido(models.Model): pedido = models.ForeignKey(Pedido, db_column='pedido_id', on_delete=models.SET_NULL, null=True) producto = models.ForeignKey(Producto, db_column='producto_id', on_delete=models.SET_NULL, null=True, verbose_name='Productos') cantidad = models.DecimalField(max_digits=10, decimal_places=0, default=1) precio = models.DecimalField(max_digits=10, decimal_places=0, default=1) Here in "DetallePedido" is where I want to store the price value based in the selected "Producto"