Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
rendering django forms with one field inside other
I want to create following form with Django "forms". can anyone give me a clue how to create such form in which there is option to add text if radio button is selected and there would be two groups of radio buttons. There is no model for this form. If it is not possible with Django forms than how we can create it with Django framework. -
How to use reverse relation in my query?(django)
I'm trying to make a query to show all the branches which have the food. I've tried a lot but I can't make it work. Could someone help me? Here are my models: class Branch(models.Model): name = models.CharField(max_length=100) created = models.DateTimeField(auto_now_add=True) is_main = models.BooleanField() description = models.TextField(max_length=500) food_restaurant_category = models.OneToOneField(FoodRestaurantCategory, on_delete=models.CASCADE) restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE) branch_address = models.OneToOneField(BranchAddress, on_delete=models.CASCADE) manager = models.OneToOneField("accounts.Staff", on_delete=models.CASCADE) class Food(models.Model): name = models.CharField(max_length=100) image = models.ImageField(upload_to=upload_path) description = models.TextField(max_length=500) created = models.DateTimeField(auto_now_add=True) meal_category = models.ManyToManyField(MealCategory, related_name="meal") food_restaurant_category = models.ManyToManyField(FoodRestaurantCategory, related_name="food_cat") class Menu(models.Model): inventory = models.PositiveIntegerField() price = models.DecimalField(validators=[MinValueValidator(0.0)], max_digits=10, decimal_places=1) food = models.ForeignKey(Food, on_delete=models.CASCADE, related_name="food_rel") branch = models.ForeignKey(Branch, on_delete=models.CASCADE, related_name="branch_rel") -
Django Customer with onetoone relationship with User - how to create the fields for that model when creating User?
Here is my problem - upon creation of User in django i want to also create Customer with Onetoone relationship. I was able to get this working but problem started when I wasn't able to also create fields - dob and mobile. (User is default django user) My forms.py class CreateUserForm(UserCreationForm): class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] mobile = CharField(max_length=30) class CreateCustomerForm(ModelForm): class Meta: model = Customer fields = ['mobile', 'dob'] My models.py class Customer(Model): user = OneToOneField(User, on_delete=CASCADE) mobile = CharField(max_length=12,null=True) dob = DateField(null=True) def __str__(self): return self.user.username My views.py def customer_registration(request): form = CreateUserForm() if request.method == 'POST': form = CreateUserForm(request.POST) if form.is_valid(): user = form.save() username = form.cleaned_data.get('username') group = Group.objects.get(name='customer') user.groups.add(group) Customer.objects.create( user=user, ) messages.success(request, 'Account was created for ' + username) return redirect('index') context = {'form': form} return render(request, 'signup.html', context) I need to add 2 more fields into that Customer model (dob=form.dob, mobile=form.mobile), I was trying to have second form for this but it wouldn't work. This is what I have tried: def customer_registration(request): form = CreateUserForm() form2 = CreateCustomerForm() if request.method == 'POST': form = CreateUserForm(request.POST) if form.is_valid(): user = form.save() username = form.cleaned_data.get('username') group = Group.objects.get(name='customer') user.groups.add(group) … -
it is showing me ValueError at /edit/update/3 The view branch.views.updateuser didn't return an HttpResponse object. It returned None instead
in django python def updateuser (request , user_id ): updateuser = User.objects.get (user_id = user_id) form= userform (request .POST, instance = updateuser) if form. is_valid (): form .save() messages .success (request ,"Record Updated successfully.....!") return render(request,'bdata.html',{"User":updateuser}) -
how to alter model field to foreign key with existing tables
I have a simple model. This table has a few entries in the db. And, the category field of them is not empty: # blog.models.py from django.db import models class Article(models.Model): title = models.CharField(max_length=100) category = models.CharField(max_length=50) I want to change the category field to foreign key. The category table is created as follows and those fields are changed to foreign keys: # blog.models.py from django.db import models from account.models import User class Category(models.Model): title = models.CharField(max_length=50) def __str__(self): return self.title class Article(models.Model): title = models.CharField(max_length=100) # category = models.CharField(max_length=50) category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True, blank=True, default=Category.objects.get(title=title)) I have these restrictions: the migration directory of the blog app shouldn't be deleted. the category key should point to a category object that has the same title equal to its own. If a category object gets deleted, the category field of articles pointing to it should become null. Here is my problem: When I perform migrate, django says raise self.model.DoesNotExist( blog.models.Category.DoesNotExist: Category matching query does not exist. This is because I have a few articles. But, the category table is empty. So, Django doesn't find any category object to point existing articles to. I tried to deleted category field's default value: category … -
how to add more attributes to what an api returns
I am trying to write an API using django rest framework in which, you give a username and a password and in return you get an AuthToken or in other words you login. now I want this API to also return some fields like the email of the user along with the AuthToken. so if the authentication was successful, the get an authToken and the user's email. Can anyone help me on how I could be able to do this by adding or changing a bit of my code? These are my models: class UserManager(BaseUserManager): def createUser(self, email, password=None, **extra_fields): if not email: raise ValueError('Email Not Found!!!') user = self.model(email=self.normalize_email(email), **extra_fields) user.set_password(password) user.save(using=self._db) return user def createSuperUser(self, email, password): user = self.createUser(email, password) user.isAdmin = True user.isSuperUser = True user.save(using=self._db) return user class User(AbstractBaseUser, PermissionsMixin): username = models.CharField(max_length=100, unique=True, validators=[RegexValidator(regex="^(?=[a-z0-9._]{5,20}$)(?!.*[_.]{2})[^_.].*[^_.]$")]) email= models.EmailField(max_length=100, unique=True, validators=[EmailValidator()]) name = models.CharField(max_length=100) isSuspended = models.BooleanField(default=False) isAdmin = models.BooleanField(default=False) emailActivation = models.BooleanField(default=False) balance = models.IntegerField(default=0) objects = UserManager() USERNAME_FIELD = 'username' These are my serializers: class UserSerializer(serializers.ModelSerializer): class Meta: model = get_user_model() fields = ('username','email', 'password', 'name') extra_kwargs = {'password': {'write_only': True, 'min_length': 8}} def create(self, validated_data): return get_user_model().objects.createUser(**validated_data) def update(self, instance, validated_data): password = validated_data.pop('password', … -
How I can use pagination for my Class (DetailView) with get_context_data?
How can I get pagination for the current code? I can't change the DetailView to View or ListView, so in this class I get a filter of products. class CategoryDetailView(DetailView): model = Category queryset = Category.objects.all() context_object_name = 'category' template_name = 'category_products.html' ... def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) ... products = Product.objects.filter(id__in=[pf_['product_id'] for pf_ in pf]) context['category_products'] = products return context -
Python: How to setup virtuel enviroment?
I'm trying to set up a virtual environment for my Python + Django project, so I ran the following in my terminal: pip3 install pipenv Afterward while being in my folder I tried doing this pipenv install django but I keep getting this error, and I have no idea how to solve it. Not sure if this makes a difference but i work in VScode zsh: command not found: pipenv Any ideas on how to solve this problem? -
Can we deploy Django on Lambda without Zappa or Serverless (Want to use native CloudFormation or Terraform)
I'm new to Django, I'm a NodeJS developer, I used CloudFormation for deploying my NodeJS applications on lambda using codebuild and codepipeline, trying to replicate the deployment mechanism for Django on Lambda. Googling out, but all solutions are using Zappa or Serverless. Looking for something native way deploying Django applications on Lambda using CloudFormation or Terraform -
auto-save the selected answers and cheaking the answear for the quiz beacuse of it is out of the time
in my quiz app i have the following models : from django.db import models class Quizzes(models.Model): title = models.CharField(max_length=200) description = models.TextField() question_number = models.PositiveIntegerField() total_marks = models.PositiveIntegerField() date = models.DateTimeField(auto_now_add=True) time_limit_mins = models.PositiveIntegerField() def __str__(self): return self.title class Question(models.Model): quiz = models.ForeignKey(Quizzes,on_delete=models.CASCADE) question=models.CharField(max_length=600) marks=models.PositiveIntegerField() option1=models.CharField(max_length=200) option2=models.CharField(max_length=200) option3=models.CharField(max_length=200) option4=models.CharField(max_length=200) cat=(('Option1','Option1'),('Option2','Option2'),('Option3','Option3'),('Option4','Option4')) answer=models.CharField(max_length=200,choices=cat) class Attempter(models.Model): quiz = models.ForeignKey(Quizzes, on_delete=models.CASCADE) score = models.PositiveIntegerField() completed = models.DateTimeField(auto_now_add=True) def __str__(self): return self.user.username class Result(models.Model): exam = models.ForeignKey(Quizzes,on_delete=models.CASCADE) marks = models.PositiveIntegerField() date = models.DateTimeField(auto_now=True) and i have the following js code for keeping track of the time that is allowed to the exam and if the time is out the quiz page redarect to the result page : <script> function saveAns(){ var ele = document.getElementsByTagName('input'); for(i = 0; i < ele.length; i++) { if(ele[i].type="radio") { if(ele[i].checked){ setCookie(ele[i].name,ele[i].value,3) } } } } function setCookie(cname, cvalue, exdays) { var d = new Date(); d.setTime(d.getTime() + (exdays*24*60*60*1000)); var expires = "expires="+ d.toUTCString(); document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/"; } window.onload = function begin(){ document.getElementById('timer').innerHTML = {{quiz.time_limit_mins}} + ":" + 00; startTimer(); } function startTimer() { var presentTime = document.getElementById('timer').innerHTML; var timeArray = presentTime.split(/[:]+/); var m = timeArray[0]; var s = checkSecond((timeArray[1] - … -
to each formset to match an automatically different value taken from a field of the model
I have a formset set to have an extra = 6. pasto it is the variable that allows me to choose which one pasto but I would like those six to be automatically set with the 6 values present in the formset. so when I save the formset it saves in the field pasto the value 1 if it is the first of the formset, 2 if it is the second etc ... my model class PianoDay(models.Model): scelta_pasto = [ ("1","Colazione"), ("2","Spuntino mattina"), ("3","Pranzo"), ("4","Merenda"), ("5","Cena"), ("6","Spuntino sera") ] pasto = models.CharField( choices = scelta_pasto, max_length = 300, default = '-' ) kcal = models.IntegerField(default = 0) grassi = models.IntegerField(default = 0) carboidrati = models.IntegerField(default = 0) proteine = models.IntegerField(default = 0) piano_day = models.ForeignKey( PianoSingleDay, on_delete = models.CASCADE, related_name = 'piano_day' ) form class PianoDayForm(forms.ModelForm): class Meta: model = models.PianoDay exclude = ['piano_day', 'pasto'] view @login_required def PianoSingleView(request, id): piano = get_object_or_404(models.Piano, id = id, utente_piano = request.user) datiFormSet = formset_factory(PianoDayForm, extra = 6) if request.method == 'POST': giorno_form = PianoSingleDayForm(request.POST, piano = piano, prefix = 'giorno') dati_formset = datiFormSet(request.POST, prefix = 'dati') if giorno_form.is_valid(): day_instance = giorno_form.save(commit= False) day_instance.single_piano = piano day_instance.save() if dati_formset.is_valid(): for dato in dati_formset: … -
Django how to transfer data from SQLite database after migrating to PostgrSQL
I migrated my Django app from SQLite to PostgreSQL in the process of preparing it for deployment using Heroku, but I forgot to transfer the data in the original SQLite database before migrating (I should have done something like this (https://www.shubhamdipt.com/blog/django-transfer-data-from-sqlite-to-another-database/). I still have the SQLite database and so I'm trying to figure out how to transfer the data over. My first thought was to try and migrate back to the SQLite database to then transfer the data, but I have not been able to do this. I tried changing the settings.py files back to how it was: DATABASES = { "default": { "ENGINE": "django.db.backends.sqlite3", "NAME": os.path.join(BASE_DIR, "db.sqlite3"), } } and then I ran python manage.py migrate but when I locally host the app, the data is not accessed. Does someone know if I'm missing anything to revert back to my original SQLite database or maybe another way to transfer the data without migrating back? -
Getting net::ERR_CONNECTION_REFUSED when trying to make a request to Django REST Server
I am trying to test a Django app by using other devices in my local network. I am using Angular as my client. So far, I am able to run my Angular app on other devices. However, whenever I try to make any sort of request, I get back a response specifying: net::ERR_CONNECTION_REFUSED I am able to properly run both the client app and Django REST server in my local machine but it's not the case when it comes to other devices. Based on some of the already posted solutions, I have done : Binding Django server to IP : 0.0.0.0:8000 by running python .\manage.py runsslserver --certificate .\ssl\server.crt --key .\ssl\server.key 0.0.0.0:8000 (I am using SSL for both client and server). Setting ALLOWED_HOSTS to ['*'] in settings.py. But the error is still persistent. All the devices (including my local machine) which I am using is Windows if that's important. Can someone help me in fixing this issue? Or are there any other way to run the API server? -
Django populating dropdown with values
Hello guys i want to populate a dropdown with the ids from the database, but when iterating over the list i get back also the brackets and the commas and some spaces. In views.py, i have the following: id = list(Device.objects.values_list('patientId', flat=True).distinct()) print(id) for item in id: print(item) context = {"filename": filename, "collapse": "", "patientId": json.dumps(id), "labels": json.dumps(labels, default=str), "data": json.dumps(data), } The print is returning exactly what i want the ids(1,2,3), but when going in the frontend(index.html), with the following code: {{patientId}} <div class="row"> <label for="patientId">Choose a patient:</label> <select name="patient" id="patient"> {% for item in patientId%} <option value="{{item}}"> {{item}} </option> {%endfor%} </select> What i get How can i get in the frontend the dropdown with the correct values? -
capture input text from url in django rest framework
I am using django rest framework to take two string from URL and output as a json response. below is the code I have tried and the response I got. Input URL: http://127.0.0.1:8000/predict/?solute=CC(C)(C)Br&solvent=CC(C)(C)O. here inputs are CC(C)(C)Br and CC(C)(C)O and I was expecting the json response contains both the inputs but I got null as output This is my urls.py file @api_view(['GET']) def result(request): response = {} solute = request.POST.get('solute') solvent = request.POST.get('solvent') results = [solute,solvent] return Response({'result':results}, status=200) I got null as output json response -
Css not working in django after deployment
I was working on Django==3.1.7 in dev, but I had to move to Django==3.0.14 during production. I don't know if that is why, but my css is not working for all of my webpages. Here is my settings.py: STATIC_URL = '/static/' STATICFILES_DIRS = [ BASE_DIR / "static" ] STATIC_ROOT = "static_root" Thank you, and please leave a comment if you have any questions. -
How to iterate json list with dict in python
I am calling data via an API and want to write that data to my Django model. The API provides me with a JSON with the following structure: "results": [ { "key1": "value", "key2": "value" }, { "key1": "value", "key2": "value", }, { "key1": "value", "key2": "value", }, .... My code looks like this: for data in response['results']: print(data) mydata = MyModel.add(**data) return results I get this error: list indices must be integers or slices, not str What I am doing wrong? A screenshot of the variables in PyCharm -
Django can't serialize Object because of _id prefix
I'm making a program which allows my frontend to send a Question Number and Category name to receive a question from the database. However, When i go to serialize the question object to send it back, the serializer errors. Model.py from django.db import models from django.db import models from django.contrib.auth.models import User class Category(models.Model): #Might Change later CategoryTitle = models.TextField() class Question(models.Model): questionText = models.TextField() QuestionType = models.TextField() questionScore = models.IntegerField() QuestionNist = models.TextField() Category = models.ForeignKey(Category, on_delete=models.CASCADE) Serializer.py from rest_framework import serializers from .models import(Question) class QuestionSerializer(serializers.ModelSerializer): class Meta: model = Question fields = ('id','questionText','QuestionType','questionScore','Category') View.py from django.http import JsonResponse from django.core import serializers from rest_framework.views import APIView from django.http import HttpResponse from .models import (Category, Question) from django.contrib.auth.models import User from .serializers import (QuestionSerializer, QuestionSender) from rest_framework.response import Response as Rs class questionRecive(APIView): QuestionSerializer = QuestionSerializer QuestionSender = QuestionSender def get(self, request): user = self.authcall(request) QuestionSenderInstance = self.QuestionSender(data=request.data) print(request.data) if QuestionSenderInstance.is_valid(): print(QuestionSenderInstance.validated_data.get('Category')) CategoryRequested=QuestionSenderInstance.validated_data.get('Category') try: CategoryID = Category.objects.get(CategoryTitle=CategoryRequested) except: Response = HttpResponse("Invalid Category", content_type="text/plain") return Response try: QuestionObject = Question.objects.filter(Category=CategoryID).values() print(QuestionObject) except: Response = HttpResponse("No QUestions Within Category", content_type="text/plain") return Response questionnumber = QuestionSenderInstance.validated_data.get('QuestionNumber') print(questionnumber) SelectedQuestion = QuestionObject[questionnumber] print(f'{SelectedQuestion} HERE') SerializedQuestion = self.QuestionSerializer(data=SelectedQuestion) if not SerializedQuestion.is_valid(): print(SerializedQuestion.errors) return Rs(SerializedQuestion.data) … -
how to do you use django-tailwind pip with django on python 3.6
I am trying to download django-tailwind, but it downloads django-tailwind==0.9.0(which I think is an older version) and installs my Django as Django==3.0.14. I think this is because I have python 3.6. However, I cannot change my python version as it is already set by the host provider. I would like to use Django==3.1.17, but then I get an error when installing django-tailwind. Is there a way I can use Django==3.1.17 and django-tailwind together on python 3.6? -
How serve media files using dreamhost with django
I would like to say that i researched a lot before ask this, there are similar questions on Dreamhost, but it's not a repeated question because there's not a answer yet for this question. For django static files are part of your application code, while media files is for generated content by your application or users of your application. My application have a database of images that will be created for users, but i have no idea about how to serve this image files. All tutorials that i saw don't explain how serve media files, only static files. Dreamhost deploy django apps using this file passenger_wsgi.py on folder /home/username/domain import sys, os INTERP = "/home/username/example.com/venv/bin/python3" #INTERP is present twice so that the new python interpreter #knows the actual executable path if sys.executable != INTERP: os.execl(INTERP, INTERP, *sys.argv) cwd = os.getcwd() sys.path.append(cwd) sys.path.append(cwd + '/djangoprojectname') #You must add your project here sys.path.insert(0,cwd+'/venv/bin') sys.path.insert(0,cwd+'/venv/lib/python3.8/site-packages') os.environ['DJANGO_SETTINGS_MODULE'] = "djangoprojectname.settings" from django.core.wsgi import get_wsgi_application application = get_wsgi_application() Can i solve this creating a .htaccess file? If yes, how it is and which directory save it? How can i solve this problem? Is it possible solve this and don't pay for another hosting service? -
Git push django project error - No such file or directory
I typed git push heroku master in the command(Terminal) then this error occurs remote: ERROR: Could not install packages due to an OSError: [Errno 2] No such file or directory: '/home/ktietz/src/ci/alabaster_1611921544520/work' I can ensure that my prework before these steps is all correct because I had followed the tutorial video. Does any brother know this error before, and do you know how to fix it, please help my school project🙏 -
Flutter persistent login using django rest framework - jwt token authentication
I have some doubts related to how exactly should I have a persistent login system for my flutter app, using django backend. So, I am using jwt token authentication, but suppose the user goes offline then how am I supposed to keep them logged in, I mean the token would expire, so I will not be able to use it then how am I supposed to get the new token, I obviously cannot ask the user to login every time so I was thinking how I should be doing this. I am still learning django and so, I do not know exactly how I should be doing this. Sorry if this question is not very good. -
How to cache 404 responses in django?
I use django FileBasedCache backend. By default it caches only 200 responses and documentation doesn't mention any settings parameter that help specify which status code to cache. How to customize it to cache 404 responses? -
getting wrong format of date in Django
I am trying to create a form to receive date input from the user and then pass that input to my another python script my Django form code is as below from Django import forms class NameForm(forms.Form): lev=forms.IntegerField(label='lev') status = forms.CharField(label='status', max_length=100) start_date = forms.DateField(widget=forms.DateInput(format = '%Y/%m/%d',attrs={'type': 'date'})) i am receiving the date and all other values in my views.py file and then passing them to my python script my views.py code is def generate(request): form=NameForm(request.POST) if form.is_valid(): a=str(form.cleaned_data.get('lev')) b= form.cleaned_data.get('status') c=str(form.cleaned_data.get('start_date')) output=run([sys.executable,'C:\\Users\\siddhant\\Desktop\\internship\\indicator\\work\\water.py',a,b,c],stdout=PIPE,text=True) events_list=level.objects.all() return render(request,'result.html',{'res':events_list}) and I am doing a strptime conversion of passed date in my work.py code as follow current_level=int(sys.argv[1]) x=sys.argv[2] start_date=sys.argv[3] print(start_date) start=datetime.strptime(start_date, "%y/%d/%m") but i am getting error that ValueError: time data '2022-01-01' does not match format '%y/%d/%m' please can someone suggest how to do tackle with this problem -
All-auth does not work properly with djongo, shows DatabaseError at /accounts/google/login/callback/
I am implemeting all-auth for google oauth authentication with django. Earlier when I was using default sqlite database configurations, it was working fine (i have configured api in developer console and added it to socialapplications with proper site configuration). But When I migrated the database to mongodb using djongo with the following database configuration replacing the default one # Database # https://docs.djangoproject.com/en/4.0/ref/settings/#databases # DATABASES = { # 'default': { # 'ENGINE': 'django.db.backends.sqlite3', # 'NAME': BASE_DIR / 'db.sqlite3', # } # } DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': 'teqsrch' } } it is giving the following error on trying to authenticate with google oauth Request Method: GET Request URL: http://127.0.0.1:8000/accounts/google/login/callback/?state=FhTF1EeKyY0T&code=4%2F0AX4XfWi8PEE5Z6eCdaOWJrB8tIPHYE10OcnT7z25MPELbvJfDQlXn5PUHFT2ipb0OnanBQ&scope=email+profile+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email+openid&authuser=1&prompt=consent The above exception ( Keyword: None Sub SQL: None FAILED SQL: ('SELECT (1) AS "a" FROM "account_emailaddress" WHERE ("account_emailaddress"."user_id" = %(0)s AND "account_emailaddress"."verified") LIMIT 1',) Params: ((2,),) Version: 1.3.6) was the direct cause of the following exception: File "/home/abhi/Projects/smartbull-backend/backend.env/lib/python3.10/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "/home/abhi/Projects/smartbull-backend/backend.env/lib/python3.10/site-packages/djongo/cursor.py", line 59, in execute raise db_exe from e The above exception () was the direct cause of the following exception: File "/home/abhi/Projects/smartbull-backend/backend.env/lib/python3.10/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/abhi/Projects/smartbull-backend/backend.env/lib/python3.10/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File …