Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
Turn off or edit autocomplete for Django allauth signup fields
I have an issue using allauth for Django on the signup fields, right now if I select the autocomplete option for the email field of my signup form then it fills the selected email into email and username. I am not quite sure how to fix this. allauth settings for my app: #django-allauth registraion settings ACCOUNT_EMAIL_SUBJECT_PREFIX ='VYGR ' ACCOUNT_EMAIL_VERIFICATION = "mandatory" ACCOUNT_LOGIN_ATTEMPTS_LIMIT = 5 ACCOUNT_USERNAME_REQUIRED = True ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_SIGNUP_PASSWORD_VERIFICATION = False ACCOUNT_CONFIRM_EMAIL_ON_GET= True ACCOUNT_LOGIN_ON_EMAIL_CONFIRMATION= True ACCOUNT_AUTHENTICATION_METHOD = 'email' LOGIN_REDIRECT_URL = '/' ACCOUNT_LOGOUT_ON_GET=True ACCOUNT_LOGOUT_REDIRECT_URL='/' The specific template: <div class="registration-form"> <form class="signup" id="signup_form" method="post" action="{% url 'account_signup' %}"> <div class="login-page-title page-title" href="#">VYGR</div> {% csrf_token %} {% for field in form %} {{ field }} {{ field.errors }} {% endfor %} {% if redirect_field_value %} <input type="hidden" name="{{ redirect_field_name }}" value="{{ redirect_field_value }}" /> {% endif %} <button type="submit">{% trans "Sign Up" %}</button> <p class="signup registration">{% blocktrans %}Already have an account? Then please <a href="{{ login_url }}">Sign In</a>.{% endblocktrans %}</p> </form> </div> What I see in Chrome developer tools: <div class="registration-form"> <form class="signup" id="signup_form" method="post" action="/accounts/signup/"> <div class="login-page-title page-title" href="#">VYGR</div> <input type="hidden" name="csrfmiddlewaretoken" value="xxx"> <input type="email" name="email" placeholder="E-mail address" autocomplete="email" required="" id="id_email"> <input type="text" name="username" placeholder="Username" autocomplete="username" minlength="1" maxlength="150" required="" id="id_username"> … -
How do you solve django.db.migrations.exceptions.NodeNotFoundError in Django?
I get the following error when I do python manage.py makemigrations: django.db.migrations.exceptions.NodeNotFoundError: Migration leads.0001_initial dependencies reference nonexistent parent node ('auth', '0012_alter_user_first_name_max_length') This is a part of my 0001_initial.py: class Migration(migrations.Migration): initial = True dependencies = [ ('auth', '0012_alter_user_first_name_max_length'), ] operations = [ migrations.CreateModel( name='User', ... How am I supposed to solve this error? Currently, I am in production. Thank you, and please leave a comment if you have any questions. -
No matching version found for @vue/cli-plugin-router@3.12.1 after npm audit fix --force
I have just run this: after npm audit fix --force But after that I got this issue: djackets_vue@0.1.0 serve vue-cli-service serve node:internal/modules/cjs/loader:936 throw err; ^ Error: Cannot find module '@vue/cli-plugin-router' Require stack: - C:\DjangoWeb\venv\Scripts\djackets_django - Copy\djackets_vue\node_modules\@vue\cli-service\lib\Service.js - C:\DjangoWeb\venv\Scripts\djackets_django - Copy\djackets_vue\node_modules\@vue\cli-service\bin\vue-cli-service.js at Function.Module._resolveFilename (node:internal/modules/cjs/loader:933:15) at Function.Module._load (node:internal/modules/cjs/loader:778:27) at Module.require (node:internal/modules/cjs/loader:1005:19) at require (node:internal/modules/cjs/helpers:102:18) at idToPlugin (C:\DjangoWeb\venv\Scripts\djackets_django - Copy\djackets_vue\node_modules\@vue\cli-service\lib\Service.js:150:14) at C:\DjangoWeb\venv\Scripts\djackets_django - Copy\djackets_vue\node_modules\@vue\cli-service\lib\Service.js:190:20 at Array.map (<anonymous>) at Service.resolvePlugins (C:\DjangoWeb\venv\Scripts\djackets_django - Copy\djackets_vue\node_modules\@vue\cli-service\lib\Service.js:176:10) at new Service (C:\DjangoWeb\venv\Scripts\djackets_django - Copy\djackets_vue\node_modules\@vue\cli-service\lib\Service.js:34:25) at Object.<anonymous> (C:\DjangoWeb\venv\Scripts\djackets_django - Copy\djackets_vue\node_modules\@vue\cli-service\bin\vue-cli-service.js:16:17) { code: 'MODULE_NOT_FOUND', requireStack: [ 'C:\\DjangoWeb\\venv\\Scripts\\djackets_django - Copy\\djackets_vue\\node_modules\\@vue\\cli-service\\lib\\Service.js', 'C:\\DjangoWeb\\venv\\Scripts\\djackets_django - Copy\\djackets_vue\\node_modules\\@vue\\cli-service\\bin\\vue-cli-service.js' ] } Here is my package.json: { "name": "djackets_vue", "version": "0.1.0", "private": true, "scripts": { "serve": "vue-cli-service serve", "build": "vue-cli-service build" }, "dependencies": { "axios": "^0.24.0", "bulma": "^0.9.3", "bulma-toast": "^2.4.1", "core-js": "^3.6.5", "vue": "^3.0.0", "vue-router": "^4.0.0-0", "vuex": "^4.0.0-0" }, "devDependencies": { "@vue/cli-plugin-babel": "^3.3.0", "@vue/cli-plugin-router": "3.12.1", "@vue/cli-plugin-vuex": "~4.5.0", "@vue/cli-service": "^3.12.1", "@vue/compiler-sfc": "^3.0.0", "sass": "^1.26.5", "sass-loader": "^8.0.2" } } I have just tried to unistall node_modules and npm then reinstall all of this, but still nothing Any idea? Thank you in advance -
Django Favorite system
I am trying to build a "add to favorite" system in django for my app. So far, I have a detail page called ad_detail, where I have a button that if the user clicks on, wether he already clicked on it or not, adds or remove the ad to his "watch list". This works fine. Now I am trying to do the same thing but in home.html, where I have couple ads that I render to the template. For each ad, I want to add the "add to watch list" button. If the user has aleady added the ad in his favorites, then show the icon-fill. If not show simply the icon-not-fill. When the user clicks on one of the displayed "add to favorite" button, then I want in views.py to be able to get the exact button that has been clicked, to then add it to user's favorites. Code below: models.py class VlandAd(models.Model): metaverse_name = models.CharField(max_length=100) title = models.CharField(max_length=100) description = models.TextField(null=True, blank=True) price = models.CharField(max_length=50) currency = models.CharField(max_length=8) ad_link = models.CharField(max_length=200) sold = models.BooleanField(default=False) bought_by = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True, related_name="has_bought") created = models.DateTimeField(auto_now_add=True) published = models.CharField(max_length = 30, choices=STATUS_CHOICES, default="Published" ) user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) … -
Hello everyone , i built web site with django framework for online services like freelancer,
and i want when the normal user requests a specific project from a particular freelancer ,I want to send him an email with project details what can i do? -
how to compare two objects fields in django
I have two objects and I want to compare them in order to find which fields are field in one and miss in the other... what should I do? how can I do it in a query(if it is possible) or how can I do it in python? assume two objects school1 and school2( from model School). the fields are students_number, classes, name, address) example: school1( 10,4,"","") school2(12,5,"alexi", "USA,alex street") -
Not Able to import 'RetrieveUpdateDestoryAPIView' from 'rest_framework.generics'
I am able to import other APIViews but not RetrieveUpdateDestoryAPIView using rest_framework.generics. from .models import Employee from .serializers import EmployeSerializer from rest_framework.generics import ListCreateAPIView, RetrieveUpdateDestoryAPIView # Create your views here. class emp_get(ListCreateAPIView): queryset = Employee.objects.all() serializer_class = EmployeSerializer class emp_api(RetrieveUpdateDestoryAPIView): queryset = Employee.objects.all() serializer_class = EmployeSerializer **File "../genericsAPIViewAndMixin/concreteApi/views.py", line 3, in from rest_framework.generics import ListCreateAPIView, DestroyAPIView, RetrieveUpdateDestoryAPIView ImportError: cannot import name 'RetrieveUpdateDestoryAPIView' from 'rest_framework.generics** -
Search part in navbar doesn't work properly (django)
I wanted to create a search box in my navbar and show the food which I search, but it seems it doesn't work properly. I can't find out where's the problem; I mean if I search a food which exists it shows me nothing. my views.py file: class SearchResultsView(ListView): model = Food template_name = "restaurant/food_search_results.html" context_object_name = "data" def get_queryset(self): query = self.request.POST.get("search") if query is not None: return Food.objects.filter(name__icontains=query) else: return my urls.py file: path("search", SearchResultsView.as_view(), name='search_results'), my base.html file: <form class="form-inline my-2 my-lg-0" action="/search" method="get"> {% csrf_token %} <div class="input-group"> <label> <input name="search" type="text" class="form-control" placeholder="Search Foods ..."> </label> <div class="input-group-append"> <a class="btn btn-outline-warning" href="{% url 'search_results' %}" type="submit" >Search</a> </div> </div> </form> -
Get Average of every n records in django in a efficient way
Imagine that you have 6 records like [1,2,3,4,5,6] how it is possible to calculate result bellow with least query to db in django? { 1 : (1+2)/2, 2 : (3+4)/2, 3 : (5+6)/2, } -
Navigation .a and help understand
Need help understanding if what my wicked mind has stumbled across and what thought I put back into universe has done any justice for my keenly thought out plan? Navigation is needed to assure my Renaissance..a -
Application error in Heroku web after deployment
I have successfully deployed my sentiment analysis web application on Heroku. Most of the features are working properly. One of the features is to extract Twitter data and analyze it. I have set the limit from 1-200 tweets. Supposedly, this is what the result should be: This is in my local host, I can extract up to 200 tweets: If I select a smaller number like the system works just fine but the error starts at 71 tweets and above: but sometimes, the amount that were successful before then have error if I try it again. Like I tried until 70 and it worked but then I tried 70 again then I get this error So I try to get the logs. I cant post it here because of the text limit but here's a text link to the logs: https://justpaste.it/46muj It works perfectly in my localhost but it have some issues in heroku. here's the link to my web app: https://sentymeter.herokuapp.com/ The problem is at import tweets. Can you help me solve this issue? I cant seem to figure it out. -
Celery with redis in django can't read django settings
I want to use celery with django and for that I installed celery and redis as backend for celery. This is celery.py: import os from celery import Celery from celery.schedules import crontab os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'finteck.settings.local') app = Celery('finteck') app.config_from_object('django.conf:settings', namespace='Celery') app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print(f'Request: {self.request!r}') app.conf.beat_schedule = { #Scheduler Name 'print-message-ten-seconds': { # Task Name (Name Specified in Decorator) 'task': 'print_msg_main', # Schedule 'schedule': crontab(minute="*/1"), # Function Arguments 'args': ("Hello",) }, } and this is the settings for celery inside local.py: CELERY_BROKER_URL = 'redis://localhost:6379' CELERY_RESULT_BACKEND = 'redis://localhost:6379' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TIMEZONE = "UTC" but when I run celery -A finteck worker -l info I get this error: [2022-01-09 08:03:41,229: WARNING/MainProcess] No hostname was supplied. Reverting to default 'localhost' [2022-01-09 08:03:41,229: ERROR/MainProcess] consumer: Cannot connect to amqp://guest:**@localhost:5672//: Connection.open: (541) INTERNAL_ERROR - access to vhost '/' refused for user 'guest': vhost '/' is down. Trying to reconnect... I don't know what to do to solve this. -
Nginx 404 error on all static files, but directory is correct
I apologise that this has been asked many times. However all the solutions I found did not seem to fix my issue. I'm setting up a web server with Nginx and Gunicorn to host a Django app. I am using Gunicorn as a web server, which is running on 127.0.0.1 on port 8000. I'm able to connect to the web server through Nginx, but all static files give a 404 error despite their paths being correct. Here is the setup for Nginx: server { listen 80; server_name 192.168.1.70; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { alias /home/willis/indabom/bomenv/static; } location / { include proxy_params; proxy_pass http://127.0.0.1:8000; } } The nginx.conf file is unchanged from default as well. I have a folder in the 'bomenv' directory, which inside has two folders: 'admin' and 'bom', which both contain all of the static files the application needs. My settings.py for my Django app is all untouched aside from the following lines: STATIC_URL = '/home/willis/indabom/bomenv/static/' STATIC_ROOT = '/home/willis/indabom/bomenv/static/' -
TypeError at /predict/ 'method' object is not subscriptable in django
I am doing prediction on a machine learning model using PyTorch and in Django rest framework. while loading I am getting TypeError: 'method' object is not subscriptable error. How to rectify this error. My views.py file response = {} @api_view(['GET']) def result(request): solute = request.POST.get['solute'] solvent = request.POST.get['solvent'] results = predictions(solute, solvent) response["predictions"] = results[0].item() response["interaction_map"] = (results[1].detach().numpy()).tolist() return Response({'result': response}, status=200) apps.py class ApiConfig(AppConfig): name = 'api' MODEL_FILE = os.path.join(settings.MODELS) model = joblib.load(MODEL_FILE) urls.py urlpatterns = [ path('predict/',result, name='result'), ] -
How to return child object names along with parent details in django
I have two models Destination and Cruise #Models class Destination(models.Model): name = models.CharField(unique= True, null= False, blank=False, max_length= 50) description = models.TextField(max_length= 2000, null= False, blank=False) slug = models.SlugField() def __str__(self) -> str: return self.name class Cruise(models.Model): name = models.CharField(unique= True, null= False, blank=False, max_length= 50) description = models.TextField(max_length= 2000, null= False, blank=False) destinations = models.ForeignKey("Destination", null=True, blank=True, on_delete=models.SET_NULL) Im trying to show the Destination details along with all the Cruises under that destination. #Views class DestinationDetailView(DetailView): template_name = 'destination_detail.html' queryset = models.Destination.objects.all() context_object_name = "destination" HTML #html {% block content %} Destination Name = {{destination.name}} Description = {{destination.description}} Cruise = {{destination.cruises}} {% blockend content %} Please advise how to print all cruises under perticual destination. -
Unique Together validation on serializers
So I have a serializer where I pass a List of values rather than a dictionary. The validation works fine when the data received is a dictionary but fails to validate when list. this is my serializers - class itemSubCatSerializer(serializers.ModelSerializer): class Meta: model = itemSubCat fields = '__all__' validators = [ UniqueTogetherValidator( queryset=itemSubCat.objects.all(), fields=['tenant', 'name'] ) ] and this is my viewset create method - def create(self, request, format=None): data = request.data if isinstance(data, list): # <- is the main logic serializer = self.get_serializer(data=request.data, many=True) else: serializer = self.get_serializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Any recommended way to use validator whan passing a List ? -
Django - Form Save
I can't save my signup form. I use allauth base.py ACCOUNT_SIGNUP_FORM_CLASS = 'userauth.forms.SignupForm' models.py from modelcluster.contrib.taggit import ClusterTaggableManager from django.contrib.auth.models import User class Userr(models.Model): tags = ClusterTaggableManager(blank=True) forms.py class SignupForm(forms.ModelForm): first_name = forms.CharField(max_length=100) last_name = forms.CharField(max_length=100) class Meta: model = Userr fields = ['tags'] def signup(self, request, user): user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.save() user.userr.tags = self.cleaned_data['tags'] user.userr.save() i get error AttributeError at /accounts/signup/ 'User' object has no attribute 'userr'