Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Adding 2 foreign keys referencing the same table using related_name causing NameError - value given to related name is not defined
I'm creating a model in Django with 2 main classes - a match class and a player class. Each match needs to have 2 players taken from the database, so I've included foreign keys to the table, but these are clashing since I'm referencing the player class twice in the match class. I've tried using the related_name field to prevent these clashes, as seen in the code below. While this example seems to work for other users here, I'm getting a name error, stating that the name declared in related_name is not defined. Changing the value of related_name changes the error content. class Player(models.Model): p_pub_date = models.DateTimeField('date published') p_username = models.CharField(max_length=20) p_tag = models.CharField(max_length=20) p_league_id = models.ForeignKey(League, on_delete=models.CASCADE) p_elo_rating = models.IntegerField(default=1200) p_glicko_rating = models.IntegerField(default=1200) p_character = models.CharField(max_length=20) p_country = models.CharField(max_length=50) class Match(models.Model): m_pub_date = models.DateTimeField('date published') m_tournament_id = models.ForeignKey(Tournament, on_delete=models.CASCADE) m_player0_id = models.ForeignKey(Player, on_delete=models.CASCADE, related_name=m_player0_id) m_player1_id = models.ForeignKey(Player, on_delete=models.CASCADE, related_name=m_player1_id) m_result = models.IntegerField(default=0) When I run makemigrations I get an error in my models.py file: m_player0_id = models.ForeignKey(Player, on_delete=models.CASCADE, related_name=m_player0_id) NameError: name 'm_player0_id' is not defined Thanks in advance -
Show valid page numbers when the current page number is out of range
Have an issue with the default paginated ListView in Django is that when I access a list view with a page number that is out of range, which can typically happen when I refresh the last page while some objects are deleted so the total number of pages is decreased, Django will raise a 404 error. What I want to do in that case is to show a page with a warning message telling the user the page number is not valid any more, and pagination links which can lead the user the the valid page. So here is my code from django.views.generic import ListView from django.shortcuts import render from django.http import Http404 class MyListView(ListView): def get(self, request, *args, **kwargs): try: return super().get(request, *args, **kwargs) except Http404: return render(request, 'pagenum_out_of_range.html', status=404) and pagenum_out_of_range.html {% extends my_project_base_template %} {% block body %} <p>Invalid page number and there's no result here. Please try somewhere else.</p> {% for object in page_obj.paginator.page_range %} <a class="page-link" href="?page={{ forloop.counter }}">{{ forloop.counter }}</a> {% endfor %} {% endblock %} It doesn't work (no links are shown). I think it's because I didn't pass the context so I changed the last line above to return render(request, 'pagenum_out_of_range.html', status=404, … -
How can i keep previous image when i dont chosse any image to update model
class ProductSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Product fields = ('id', 'name','detail','image','price','product_type','brand','user') -
Revert from UUID Primary Key to Integer Primary Key
I used UUID as Primary Key and removed it. Now it's throwing an error after reverting to default. I tried using a CharField with primary_key=True, dropped the DB and migrations. But it's still throwing the following error: TRACEBACK: django.db.utils.ProgrammingError: cannot cast type uuid to integer LINE 1: ..._biodata" ALTER COLUMN "id" TYPE integer USING "id"::integer MODELS.PY class BioData(models.Model): status = models.CharField(max_length=200, choices=CANDIDATE_CHOICES, default='NOT ONBOARDED') first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) email = models.EmailField(max_length=70, blank=True) mobile = models.CharField(max_length=100, blank=False) contact_number = models.CharField(max_length=100, blank=True, null=True) gender = models.CharField(max_length=200, choices=GENDER_CHOICES) marital_status = models.CharField(max_length=200, choices=MARITAL_STATUS_CHOICES) date_of_birth = models.DateField(null=True, blank=True) next_of_kin = models.ForeignKey(NextOfKin, on_delete=models.CASCADE) address = models.ForeignKey(Address, on_delete=models.CASCADE) I would like to revert to the default incremental "integer" ID without explicitly declaring id -
How to sort a dictionary inside a dictionary based on the key(alphabetically) of the inner dictionary in python
Despite the fact that I have seen a lot of answers about sorting a dictionary of a dictionary I was not able to adjust the solution to my problem. Here is the structure of my dictionary: OrderedDict([('2018-11', {'NEOCATE JUNIOR WITHOUT FLAVOUR 400 gr.': 8}), ('2017-11', {'NEOCATE JUNIOR WITHOUT FLAVOUR 400 gr.': 804,'ALFAMINO 400 GR.': 4, 'Forticare Orange/Lemon 4 X125ml': 15})]) The outer dictionary has as key a date in format year-month The outer dictionary has as value a dictionary in format {'name of product: quantity} The inner dictionary has as key the name of the product The inner dictionary has as value the quantity(of the product) My aim is to sort my outer dictionary based on the latest date(the newest to be first) and my inner dictionary based on the name of the product alphabetically. In other words: OrderedDict([('2018-11', {'NEOCATE JUNIOR WITHOUT FLAVOUR 400 gr.': 8}),('2017-11',{'ALFAMINO 400 GR.': 4,'Forticare Orange/Lemon 4 X125ml': 15,'NEOCATE JUNIOR WITHOUT FLAVOUR 400 gr.': 804})]) First goes the date 2018-11, is "newest" than 2017-11 and in inner dictionaries if I have more than one records as the dictionary with key 2017-11, first goes the ALFAMINO (starts with A), then the Forticare (starts with F) and so … -
How can I pass primery key to url for editing information about objects?
I have a model called Porumbei and I want to make a view to edit those objects.According to my low knowledge of django, how can I write this view passing the primery key to url? The url I wish should look like /porumbei/editare/pk/ My view: def editareporumbei(request, pk): porumbel = get_object_or_404(Porumbei, pk=pk) if request.method == "POST": form = AdaugaPorumbel(request.POST, instance=porumbel) if form.is_valid(): form.save() return redirect("dashboard") else: form = AdaugaPorumbel(instance=porumbel) context = { 'form' : form, } template = loader.get_template("editare_porumbei.html") return HttpResponse(template.render(context, request)) #Link in the template. The template shows all Porumbei in the database <td> <a href="{% url 'editareporumbei' pk=porumbel.pk %}" class="mr-15" data-toggle="tooltip" data-original-title="Editează"> <i class="icon-pencil"></i> </a> </td> # My url path('porumbei/editare/(?P<pk>\d+)/', views.editareporumbei, name='editareporumbei'), Reverse for 'editareporumbei' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['porumbei/editare/(?P[0-9]+)/$'] If I directly access porumbei/editare/5 it shows me the form for editing data but I want to take me to the page when I click a button. The button is in the page where all Porumbei are listed. -
Can't able to insert file in database
when i try to insert file in Djago BinaryFile model i got error. The error is with the file name, if file name is in multiple of 4 then its insert successfully. otherwise it give error. why i get error with file name? please explain and if possible please give solution error binascii.Error: Invalid base64-encoded string: number of data characters (9) cannot be 1 more than a multiple of 4 or binascii.Error: Incorrect padding -
Issue with missing "request" in django function
I have a little question about request attribute in my function located in a python file (not my view): def my_function(model, request): instance = model.objects.filter(application=request.cur_app, display=True).order_by('order') return instance In this same file, I call my function like this: for element in my_function(my_model): ... do something ... But I get this issue: my_function() missing 1 required positional argument: 'request' I don't understand How I can solve this issue, because if I add 'request' in my loop, I get: name 'request' is not defined Thank you ! -
How to add script type="module" in django admin
If I want some javascript functionality in my Django admin, I usually go about it using the Media class like this: @admin.register(MyModel) class MyModelAdmin(admin.ModelAdmin): class Media: js = ('js/my_script.js',) But I now have a script that is a ES6 module so I would like Django to render it like: <script src="path/to/static/js/my_script" type="module"></script> and using the Media class doesn't render the type="module" attribute. Any help or tips to achieve this? Thanks -
Struggling to Create Django User and related Profile Model Object (multiple types depending on user) using Rest Framework
I am trying to enable user sign-up via the rest-framework. I require different groups of users with different information associated with their profiles. I am struggling to enable my UserSerializer to call different ProfileSerializers (depending on the group) without problem. I want a single API to create both the user and profile. I have tried including and discluding profile as a field in my user serializer. Having the profile refer to a DictField which is then changed to the appropriate serializer on init. I have tried to produce the minimum reproducible code below: models.py class User(AbstractUser): @property def group(self): groups = self.groups.all() return groups[0].name if groups else None class StoreProfile(models.Model): user = models.OneToOneField( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, related_name='store_profile' ) location = models.CharField(max_length=30, blank=True) class CustomerProfile(models.Model): user = models.OneToOneField( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, related_name='customer_profile' ) address = models.CharField(max_length=30) serializers.py class StoreProfileSerializer(serializers.ModelSerializer): class Meta: model = StoreProfile fields = ('location',) class CustomerProfileSerializer(serializers.ModelSerializer): class Meta: model = CustomerProfile fields = ('address',) class UserSerializer(serializers.ModelSerializer): password1 = serializers.CharField(write_only=True) password2 = serializers.CharField(write_only=True) group = serializers.CharField() profile = serializers.DictField() def __init__(self, *args, **kwargs): super(UserSerializer, self).__init__(*args, **kwargs) if self.instance and self.instance.group == 'store': self.profile = StoreProfileSerializer() elif self.instance and self.instance.group == 'customer': self.profile = CustomerProfileSerializer() def create(self, validated_data): group_data = … -
Is this the good way to handle multiple formsets in the same view?
First I'm using Python 3.7.3 and Django 2.2 I am encountering a problem for handling multiple formsets in the same view. In my view, I'm creating my formset in a for loop (check down below) and then I'm adding then in a list. In my template I do a for loop on that list and display the formset. I think that what I've done works well but something wrong happens when a formset is not valid (because I did some validation too). When a formset is not valid (because values are not accepted), the other formsets are initilized with those values too. Why ? models.py class Set(models.Model): timeSet = models.DecimalField(max_digits=5, decimal_places=2, blank=True, null=True) scoreTeam1 = models.IntegerField(null=True) scoreTeam2 = models.IntegerField(null=True) match = models.ForeignKey(Match, default=None, on_delete=models.CASCADE) class Match(models.Model): isFinished = models.BooleanField(default=False) team1Win = models.BooleanField(default=False) team2Win = models.BooleanField(default=False) phase = models.ForeignKey(Phase, default=None, on_delete=models.CASCADE) teams = models.ManyToManyField(Team, default=None, blank=True) forms.py class SetUpdateForm(forms.ModelForm): class Meta: model = Set fields = [ 'scoreTeam1', 'scoreTeam2', 'match', ] def clean(self): cleaned_data = super().clean() # print(cleaned_data) scoreTeam1 = cleaned_data.get("scoreTeam1") scoreTeam2 = cleaned_data.get("scoreTeam2") if scoreTeam1 and scoreTeam2: if scoreTeam1 > 25 or scoreTeam2 > 25 or (scoreTeam1 < 25 and scoreTeam2 < 25): raise forms.ValidationError("A set is played in " … -
"How to fix the 'csrf' error in 'Django'?"
I'm using Django with Atom engine and when I log in to the link http://127.0.0.1:8000 it gets me a csrf error. what should I do? -
Keyword can't be expression - View
I am trying to create database with Django and fill it ower URL but I am getting this error: File "C:\Final\vj_2\vj_2\app_1\views.py", line 12 'naslov'=naslov, ^ SyntaxError: keyword can't be an expression I don't know what am I missing here and why it doesn't work. This is my view: def dodajClanak(request, naslov, datumObjave, autor): clan = Clanak( 'naslov'=naslov, 'datum_objave'=datumObjave, 'autor'=autor ) clan.save()#ako podaci nisu dobri throwat ce error return render(request, 'allapp.html', {'data': naslov + ' ' + datumObjave + ' ' + autor}) And my model: class Clanak(models.Model): naslov = models.CharField(null=False, blank=True, max_length=120) #naslov = models.DecimalField(null=False, blank=False, decimal_places=1, max_digits=5) datumObjave = models.DateField(null=False, blank=False) autor = models.CharField(null=False, blank=True, max_length=50) def __str__(self): return str(self.naslov) + ', ' + str(self.datumObjave) + ', ' + str(self.autor) -
DJANGO : Hit an api multiple times simultaneously
Here is my project situation. I am using Django I am running a cron job every day at a particular time. What I do is I query a list of users whose payment needs to be requested. The payment api is collection of two api's each per user depending on the type of subscription. Question :: how should the api be hit. 1. Should be hit in order(i.e. one after the other. I think this is not a good way) 2. Should I hit it concurrently (all api hits are independent of each other). If the second way is better, what are the tools/libraries in django that I can use. Definitely the second way will be much faster since it is involving parallelism. But will it put a lot of pressure/load on the server. What is the standard way to go in such a scenario? -
how to Reverse Relation Serialize N times based on data in database
I want to construct a binary tree like structure(using reverse relation) an employee with report_to field null is top of the tree(A grade), using reverse serializer I can get their controlled employee list(B grade). but if the B grade employee is controlling some employees then I have to reverse relate that employee list(C grade). some B grade employee may or may not have employee reporting to them. then C grade employee may or may not have employee reporting to them and so on the tree grows till the last employee. I have an employee table and job_info table class employee(models.Model): first_name = models.CharField(max_length = 50) last_name = models.CharField(max_length = 50) class job_info(models.Model): employeeid = models.OneToOneField(employee, on_delete = models.CASCADE) report_to = models.ForeignKey(employee, on_delete = models.SET_NULL,related_name = "supervisor", null = True) if I need to find a limited amount of reverse serializer, I can write the required amount of reverse relation serializer. but in my case, the tree maybe (0 grade) to (N grade). so how do I write a serializer that can handle N number of reverse serializer -
How to filter by empty string in a Django Rest Framework request querysting?
As per title, given a model that has a string field like: class MyModel(models.Model): name = models.CharField(null=True, blank=True, max_length=50) I can configure a generic api with filters in Django Test Framework like this: class MyModelApi(ListAPIView): serializer_class = MyModelSerializer model = MyModel filterset_fields = ('name') filter_backends = (DjangoFilterBackend) querystring = MyModel.objects.all() This allows me to filter the api like this: http://localhost:5000/my_api?name=foo I also know how to configure such api so that it is possible to use filters different from the exact one like: http://localhost:5000/my_api?name__iconstains=bar What I cannot figure out is: how to get all the MyModel object whose name field is an empty list? I've tried the following with no results: http://localhost:5000/my_api?name__gt= http://localhost:5000/my_api?name= -
Django Validation Error raised but not displayed for shopping cart app
I am running Django 2.2 and have written a simple shopping cart. I wish to validate two fields at the same time in such a way that both cannot be empty at the same time. In my forms.py, from django import forms class CartAddProductForm(forms.Form): cc_handle = forms.CharField(required=False, label='CC Handle', empty_value='') lc_handle = forms.CharField(required=False, label='LC Handle', empty_value='') def clean(self): cleaned_data = super().clean() if cleaned_data.get('cc_handle') == '' and cleaned_data.get('lc_handle') == '': print("issue detected") raise forms.ValidationError('Either cc or lc handle is required.') return cleaned_data This is following the official Django docs on cleaning and validating fields that depend on each other. The print() statement above lets me know that the issue has been detected, i.e. both fields are empty. Running the Django server, I see that the issue was indeed detected but no validation error message was displayed on top of the originating page. The originating page is the product page that contains the product and a link to add the product to the shopping cart. Normally the validation error message is displayed at the top of the page. According to the docs, the validation is done when is_valid() is called. So I put a diagnostic print of my views.py from django.shortcuts import … -
Can I use pk from another model in RetrieveAPIView. Is this a bad practice?
I am working on an RetrieveAPIView api in which I want to pass the id of college and it will return all students who are currently studying there, but I am using Modelserializer of student model. code is in college app. I am in trouble is this a bad practice? my urls.py: path(studentdetails/<int:college_id>/, views.StudentView.as_view()) my serializer.py class StudentSerializer(serializers.ModelSerializer): class Meta: model = Student fields = ('id', 'name', 'rollno') my views.py from rest_framework.generics import RetrieveAPIView from rest_framework import serializers from student.serializer import StudentSerializer from student.models import Student from .models import College class StudentView(RetrieveAPIView): queryset = Stduent.objects.all() serializer_class = StudentSerializer def get(self, request, *args, **kwargs): try: college_id=College.objects.get(id=self.kwargs.get('college_id')) data=myfunction(id=college_id) response_data=self.get_serializer(data, many=True) return Response({"data": response_data.data}) except College.DoesNotExist: raise serializers.ValidationError(_("College Does Not exists")) -
Not able to insert file in Django BinaryField
I am trying to insert text file in Django BinaryField through Django-model-form but it give error binascii.Error: Invalid base64-encoded string: number of data characters (25) cannot be 1 more than a multiple of 4 can anyone help he with this error. how to solve it. i check lots of online stuff but can't get any solution. form.py class CertificateForm(forms.ModelForm): app_attributes = {'oninvalid': 'this.setCustomValidity("Application field is required")', 'oninput': 'this.setCustomValidity("")'} startdate = forms.DateField(widget = forms.SelectDateWidget(years=range(1995, 2100))) expiredate = forms.DateField(widget = forms.SelectDateWidget(years=range(1995, 2100))) application = forms.CharField(widget=forms.TextInput(attrs=app_attributes)) class Meta: model = certificateDb fields = ('application', 'startdate', 'expiredate', 'environment_type','bytes') error_messages = { 'application': { 'required': ("Application field is required"), }, } widgets = { 'bytes' : forms.FileInput() } def clean(self): cleaned_data = super().clean() startdate = cleaned_data.get("startdate") expiredate = cleaned_data.get("expiredate") if expiredate < startdate: msg = u"expiredate should be greater than startdate." raise forms.ValidationError(msg, code="invalid") model.py class certificateDb(models.Model): Dev = 1 QA = 2 UAT = 3 Production = 4 environment_TYPES = ( (Dev, 'Dev'), (QA, 'QA'), (UAT, 'UAT'), (Production, 'Production'), ) application = models.CharField(db_column='Application', max_length=255, blank=True, null=True) # Field name made lowercase. startdate = models.DateField(null=True) expiredate = models.DateField(null=True) environment_type = models.PositiveSmallIntegerField(choices=environment_TYPES) bytes = models.BinaryField(blank=True,editable = True) def __str__(self): return self.application view.py def save_all(Filename,request,form,template_name): data = … -
Change admin theme in a ongoing project
I have developed a project in django as core technology and i need to change the admin theme but cant change it can any one specify an experienced steps for this process -
Make an Rest API with connect multiple database get some input search on db and provide output
i want to write an api in django which get some input and search this input in DB and provide output -
Specify model ID when declaring attributes in Django
I'm trying to create a model representing the branches of a franchise in django. Here is how I'm declaring the model: class Branch(models.Model): """ Branch/Outlet of a franchise in a city """ city_id = models.ForeignKey(City, on_delete=models.CASCADE) name = models.CharField(max_length=40, null=False) address = models.CharField(max_length=220, null=False) postal_code = models.CharField(max_length=10, null=False) # An array of Ids of nearby branches sorted in order of distance nearby_branches = ArrayField(models.CharField(max_length=10, null=False)) Is it possible to specify nearby_branches as a list of Ids of the branch model instead of a charfield as I've done here. eg. something like nearby_branches = ArrayField(Branch.id) -
Vue CLI hotreloading with Django
I am using a combination of Django and Vue to build my website, I just upgraded Vue CLI from version 2 to 3 and now part of the hotreloading is broken. Vue is still automatically picking up changes and recompiling but my browser isn't refreshing automatically with those changes, I need to manually reload the page. In the Chrome DevTools network console I see that all the calls to the sockjs-node endpoint are going to the Django server instead of the Vue server. I am using Django to serve the Vue files via django-webpack-loader and what I assume is happening is that Vue is giving a relative path to get to the sockjs-node endpoints which means they are now pointing at my Django server instead of the Vue server. I have tried to fix this by simply forwarding the requests in Django to the Vue server but I bumped into Access-Control issues that I didn't know how to solve. How can I fix VueCLI's hot reloading? Links: Article I used to configure Vue Simple repo that reproduces the issue -
Can install packages but can't import in python
I have installed django multiselectfield using the command pip install django-multiselectfield I get Requirement already satisfied: django-multiselectfield in c:\users\lenovo\appdata\local\programs\python\python37\lib\sit e-packages (0.1.8) Requirement already satisfied: django>=1.4 in c:\users\lenovo\appdata\local\programs\python\python37\lib\site-packages\d jango-2.0.3-py3.7.egg (from django-multiselectfield) (2.0.3) Requirement already satisfied: pytz in c:\users\lenovo\appdata\local\programs\python\python37\lib\site-packages\pytz-201 9.1-py3.7.egg (from django>=1.4->django-multiselectfield) (2019.1) I am unable to import the package multiselectfield in my program. python version: 3.7.3 pip version: 19.1.1 -
Register Form in Django wont post the request method
I changed my RegisterForm from django UserCreationForm, because I wanted to translate labels in form. It works fine, but when I try to press Sign Up button it shows an error msg: 'RegisterForm' object is not callable It probably become error, because I changed UserCreationForm in class RegisterForm(UserCreationForm) and return only a var called user - without __call__ method for the UserCreationForm and used POST method for that user var. There is even a problem line in error message. This is the line and here is the whole code. Is there a way to be able to use POST method for that edited UserCreationForm? form = user(request.POST) from django.shortcuts import render, redirect from django.contrib.auth.forms import UserCreationForm from django import forms from django.contrib.auth.models import User from django.contrib import messages class RegisterForm(UserCreationForm): email = forms.EmailField(label = "Eメール", widget=forms.TextInput(attrs={'style': 'position: relative;left: 61px;'})) first_name = forms.CharField(label = "名", max_length=10, widget=forms.TextInput(attrs={'style': 'position: relative;left: 105px;'})) last_name = forms.CharField(label = "性", max_length=10, widget=forms.TextInput(attrs={'style': 'position: relative;left: 105px;'})) username = forms.CharField(label = "ユーザー名", max_length=10, widget=forms.TextInput(attrs={'style': 'position: relative;left: 40px;'})) password1 = forms.CharField(label = "パスワード", widget=forms.TextInput(attrs={'style': 'position: relative;left: 40px;'})) password2 = forms.CharField(label = "パスワード確認", widget=forms.TextInput(attrs={'style': 'position: relative;left: 8px;'})) class Meta: model = User fields = ("username", "first_name", "last_name", "email", "password1", "password2") …