Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: To save up to child objects based on submitted json data
I have these models: class Template_folder(models.Model): tf_id = models.AutoField(primary_key=True) tf_foldername = models.TextField(max_length=100) tf_parent = models.IntegerField() tf_seq = models.IntegerField() tf_sorter = models.TextField() tf_regdate = models.DateTimeField(default=timezone.now) tf_deleted = models.TextField() tf_creater = models.IntegerField() tf_groupid = models.IntegerField() tf_isLeaf = models.TextField() class Meta: db_table = 'template_folder' Then, this serializer: class TemplateFolderSerializer(serializers.ModelSerializer): class Meta: model = Template_folder fields = '__all__' this json Data: [ [ { "id": 1, "isLeaf": false, "name": "contents1", "pid": 0, "tf_groupid": 1, "children": [ { "id": 2, "isLeaf": true, "name": "contents sub1", "pid": 1, "tf_groupid": 1 }, { "id": 3, "isLeaf": true, "name": "contents sub2", "pid": 1, "tf_groupid": 1 } ] }, { "id": 6, "isLeaf": false, "name": "contents4", "pid": 0, "tf_groupid": 1 } ] ] I want to save the submitted json data.... I want to save json data with a parent child relationship. how can store that type of json data using serializer. -
Nginx welcome page showing up rather than the landing page
I deployed my Django project on Digital Ocean using this guide (https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-16-04), I completed the steps shown in the guide and all of them seem to run without any error on the terminal still when I type the IP address of the website the Nginx welcome page shows up. The website was working fine up to this command (gunicorn --bind 0.0.0.0:8000 NGOsamyak.wsgi) after configuring Ngnix the problem occurred. /etc/nginx/sites-available/NGOsamyak server { listen 80; server_name 165.22.216.110; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/samyakbvs/NGOsamyak-project; } location / { include proxy_params; proxy_pass http://unix:/home/samyakbvs/NGOsamyak-project/NGOsamyak.sock; } } Picture of the terminal log Picture of the welcome page -
How to use update view for updating the model containing User model?
I need to update the UserProfile form but I am not able to figure out how to do it since it contains User model. I have tried a code but in that case only the userprofile form contains instance and not the user form. please Help. models class UserProfile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) mobile = models.CharField(validators=[phone_regex], max_length=17, null=True,blank=True) address = models.CharField(max_length=255,null=True,blank=True) city = models.CharField(max_length=100) is_active = models.BooleanField(default=True) role = models.ForeignKey(Role, on_delete=models.CASCADE) slug = models.SlugField(unique=False, blank=True) views class AddUserProfile(FormView): @method_decorator(user_passes_test(lambda u: u.is_superuser, login_url=LOGIN_URL)) def dispatch(self, *args, **kwargs): return super(AddUserProfile, self).dispatch(*args, **kwargs) login_required = True form_class = UserForm template_name = 'user_form.html' def form_valid(self, form): if form.is_valid : user = User() user.username = self.request.POST.get('username') user.set_password(self.request.POST['password1']) user.email = self.request.POST['email'] user.first_name = self.request.POST['firstname'] user.last_name = self.request.POST['lastname'] user.is_superuser=False user.save() userprofile = form.save(commit=False) userprofile.user = user if str(userprofile.role).lower() != 'client': print(userprofile.role) user.is_staff = True user.save() else: userprofile.user.is_staff = False user.save() userprofile.save() messages.success(self.request,'Successfully Added') return HttpResponseRedirect('/qworky/UserList/') -
Display name of column using foreign key with distinct
I am doing a movie booking project in which i want to display movies with their cinema and time slots available from this code i want to get cinema name with distinct def movies(request, id): cin = shows.objects.filter(movie_id=id).values_list('cinema_id',flat=True).distinct() print(cin) #cin = shows.objects.filter(movie_id=id) movies = movie.objects.filter(movie_id=id) show = shows.objects.filter(movie_id=id) context = { 'movies':movies[0], 'show':show, 'cin':cin, } return render(request, "movies.html", context ) Here's my model.py with Pk,Fk keys set from django.db import models from django.contrib.auth.models import User # Create your models here class cinema(models.Model): cinema_id=models.AutoField(primary_key='true') role=models.CharField(max_length=30,default='cinema_manager') cinema_name=models.CharField(max_length=50) phoneno=models.CharField(max_length=15) city=models.CharField(max_length=100) address=models.CharField(max_length=100) user = models.OneToOneField(User,on_delete=models.CASCADE) def __str__(self): return self.cinema_name class movie(models.Model): movie_id=models.AutoField(primary_key='true') movie_name=models.CharField(max_length=50) movie_des=models.TextField() movie_rating=models.DecimalField(max_digits=3, decimal_places=1) movie_poster=models.ImageField(upload_to='movies/poster', default="movies/poster/not.jpg") def __str__(self): return self.movie_name class shows(models.Model): show_id=models.AutoField(primary_key='true') cinema_id=models.ForeignKey('cinema',on_delete=models.CASCADE) movie_id=models.ForeignKey('movie',on_delete=models.CASCADE) time=models.CharField(max_length=100) seat=models.CharField(max_length=100) price=models.IntegerField() def __str__(self): return self.cinema_id.cinema_name +" | "+ self.movie_id.movie_name +" | "+ self.time Sample DATABASE accounts_shows enter image description here -
How to use IF statement insde FOR loop in django templates
I used if condition inside for loop. I'm trying to display messages if condition is satisfied, condition is not satisfied don't want to display. Help me in that. views.py username = request.session['username'] sent_msg = Message.objects.filter(sender= username).values() for i in sent_msg: print(i.sender) print(i.message) return render(request, 'mes.html',{'sent_msg': sent_msg}) msg.html {% for i in sent_msg %} {% if i.action_view == 0 %} <p>{{ i.sender }}</p> <p>{{ i.recipient }}</p> <p>{{ i.message }}</p> {% endif %} {% endfor %} Here i'm trying to display data when if condition satisfied, otherwise it display nothing. I tried in this way but its not displaying anything. -
How can i install auto update my django database?
I add some data from public API to my sqlite database in views.py. And transmit it with django rest framework to axios (vuejs application display this data). Public API updated every second, i want run my views.py code every time as well to update my database automaticly. I tried write some rough code like: While True: #my views.py function time.sleep(30). Can axios have a function to launch views.py code, or some inner django function to run my code? -
unsupported operand type error occured durin subtracting
i m subtracting two amounts in function but its giving me the stated error of unsupported operand type class SupplierStatement(models.Model): supplier = models.ForeignKey( Supplier, related_name='supplier', null=True, blank=True ) supplier_amount = models.CharField(max_length=100, null=True, blank=True) payment_amount = models.CharField(max_length=100, null=True, blank=True) description = models.TextField(max_length=500, null=True, blank=True) date = models.DateField(null=True, blank=True) def __unicode__(self): return self.supplier.name if self.supplier else '' def remaining_amount(self): return self.supplier_amount - self.payment_amount error is coming in last line return self.sup...... -
Can't able to download csv file from views in django
I'm not able to download the csv file once I execute the script using django I have execute button once I click the button the query executes and the download csv file appears. I want to download the csv file but not able to do that and In views.py def fetch_records(request): context={} my logic.... context["download_path"] = settings.MEDIA_ROOT+"/"+filename return render(request, "my.html", context) In views.py In html file-- The user can input the output file like test.csv in text box and can click on execute <tr> <td><label for="start">Output filename </label></td> <td><input type="text" name="filename"></td> </tr> {% if download_path != "" %}` <a href="{{ download_path }}" target="_blank">Download CSV</a> {% endif %} Actual -Not able to download the csv file / Expected- User should download the csv file -
Django - Know which sensors are connected to computer and send their data to a cloud server
I want to know which sensors are connected to a computer and send the list to a cloud server. Then, the server asks for data of particular sensor, then the computer reads the data of that sensor and sends it back to the cloud server. I want to use Django/Python. Can you please explain the whole process to do it. I want to know the whole process but my main focus is on code. Please help me fast and try to provide as detailed information as possible. -
How to solve this SyntaxError in django due to manage.py
I've started learning django. Through the django docs, I am using vscode for the project. The matter is that I've started a new project named "mysite" in the project folder named "web-project" by using the following commands as mentioned in this screenshot. But if you noticed an error in the last of the screenshot. It pops every time I tried to run the server -
Error with my cookies domain, need to replace the IP to my domain (Django)
This is my first question. I'm trying to deploy a web app which uses react and django, the problem is that when I use my VPS IP the page works fine but when I use mydomain.tk it stores the cookie using the IP as domain not the mydomain.tk I hope this image helps you better understand what I say (screen from chrome cookies visualizer): https://i.imgur.com/AIz8yab.png This is an example about how I need to store the cookie: https://imgur.com/4lVxJSi.png I tried changing this in my settings.py: CSRF_COOKIE_DOMAIN = ".mydomain.tk" SESSION_COOKIE_DOMAIN = ".mydomain.tk" But when I tried that the only difference was that these 2 cookies "disappeared" (the cookies were not saved) Thanks for your attention and sorry for my english -
Code Correction with CSV and multiple output
I have the following code. It's working perfectly like I want but I have a few problems with it. 1. The CSV file is not getting written 2. I am getting multiple saves of an object rather than one as I want. (Main problem) 3. How do I send the generated template as an email. The Basic idea of the function LCR is that. I have some cities or country codes in the database. I want to compare the codes with values from files uploaded by the users. after comparing the values I want to see the following result '1':[("PTCL","0.25"),("TATA","1.25")] . . . Where '1' is the value fetched from the user file 'PTCL, TATA' are users '0.25 & 1.25' are the user rates offered for that value. But I'm getting this {'25': ['Tata', ' 4.150', 'Tata', ' 4.150', 'Tata', ' 4.150', 'Tata', ' 4.150', 'Tata', ' 4.150', 'Tata', ' 4.150', 'PTCL', ' 0.888', 'PTCL', ' 0.888', 'PTCL', ' 0.888', 'PTCL', ' 0.888', 'PTCL', ' 0.888', 'PTCL', ' 0.888'], '21': ['Tata', ' 4.150', 'Tata', ' 4.150', 'Tata', ' 4.150', 'Tata', ' 4.150', 'Tata', ' 4.150', 'Tata', ' 4.150', 'PTCL', ' 0.888', 'PTCL', ' 0.888', 'PTCL', ' 0.888', 'PTCL', ' 0.888', … -
How can i use if condition inside for loop in django template
I used if condition inside for loop. I'm trying to display messages if condition is satisfied, condition is not satisfied don't want to display. Help me. views.py username = request.session['username'] sent_msg = Message.objects.filter(sender= username).values() for i in sent_msg: print(i.sender) print(i.message) return render(request, 'mes.html',{'sent_msg': sent_msg}) mes.html {% for i in sent_msg %} {% if i.action_view == 0 %} <p>{{ i.sender }}</p> <p>{{ i.recipient }}</p> <p>{{ i.message }}</p> {% endif %} {% endfor %} Here i'm trying to display data when if condition satisfied, otherwise it display nothing. I tried in this way but its not displaying anything. -
Container orchestrated autoscaling deployments of Django opens too many connections with the database
I have deployed Django on Kubernetes. The node pool is configured to allow up to 1000 pods to serve traffic. As the number of pods increase, my database starts to throw "Sorry, too many clients". The database is PostgreSQL, and outside of K8 - on a standalone Linux machine. As a temporary measure, I have increased max_connections for my database. This is not the answer I am looking for. I am trying to understand why this issue comes up in the first place - does Django open database connections and keep it open? Would 1000 pods cause 1000 live connections to my database? I am also trying to understand the different ways to approach this problem. Do I need to change something with my Django config to reduce the number of connections? Or do I need to change my database layer to support a higher number of connections? How do web deployments on container orchestration systems usually deal with this problem? -
One model multiple "origins"
I have a model design issue. Models User, Patient, Doctor, Nurse can write Note(s). They all have a foreign key to Note. What I'd like is to add a field to Note so I know from what type of model the Note comes from. In SQL I could write something like SELECT * FROM notes WHERE origin='nurse' Do I have to add a field as CharField and I assign the referred model string name or there is a field type more specific for what I want to do ? Thanks -
Radio button in react does not respond
I am trying to create a simple SignUp form in a DRF-React app which contains two radio buttons but the data I am receiving in serializers is always false for those two radio buttons Serializers.py class UserSerializerWithToken(serializers.ModelSerializer): token = serializers.SerializerMethodField() password = serializers.CharField(write_only=True) # remember_me = serializers.BooleanField() def get_token (self, obj): jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER payload = jwt_payload_handler(obj) token = jwt_encode_handler(payload) return token def create (self, validated_data): password = validated_data.pop('password', None) instance = self.Meta.model(**validated_data) if password is not None: instance.set_password(password) instance.save() return instance class Meta: model = User fields = ('token', 'username', 'password','is_teacher') Serializers.data {'token': 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjo3LCJ1c2VybmFtZSI6IjciLCJleHAiOjE1NjQ2NDI0OTgsImVtYWlsIjpmYWxzZX0.9MMUrCIYm1zuXNDJ82F-jcIbTfrw0br9K1weAjtIuNw', 'username': '7', 'is_teacher': False} SignupForm.js class SignupForm extends React.Component { state = { username: '', password: '', type: '', }; handle_change = e => { const name = e.target.name; const value = e.target.value; this.setState(prevstate => { const newState = { ...prevstate }; newState[name] = value; console.log(newState); return newState; }); }; render() { return ( <form onSubmit={e => this.props.handle_signup(e, this.state)}> <h4>Sign Up</h4> <label htmlFor="username">Username</label> <input type="text" name="username" value={this.state.username} onChange={this.handle_change} /> <label htmlFor="password">Password</label> <input type="password" name="password" value={this.state.password} onChange={this.handle_change} /> <label htmlFor="type">User type</label> <input type="radio" name="type" value="1" checked={this.state.type == "1"} onChange={this.handle_change} />Shipper <input type="radio" name="type" value="1" checked={this.state.type == "1"} onChange={this.handle_change} />Supplier <input type="submit" /> </form> … -
Is it possible in django when user is login that time user active login browser name store in database?
Django in we already store session details in django_session, and last_login in the auth_user table but I want to store when user login in browser that time browser name store in the database. I already do: get browser name in frontend page from active browser with the use of javascript but actually, I want its store in the database. I expect the output is store active browser name in the database. This is my javascript code: <html> <body> <div id="demo"></div> <script> let browserName = ""; if(navigator.vendor.match(/google/i)) { browserName = 'Browser Name: Google Chrome'; } else if(navigator.vendor.match(/apple/i)) { browserName = 'Browser Name: Apple Safari'; } else if(navigator.userAgent.match(/firefox\//i)) { browserName = 'Browser Name: Mozila Firefox'; } else if(navigator.userAgent.match(/edge\//i)) { browserName = 'Browser Name: Microsoft Edge'; } else if(navigator.userAgent.match(/trident\//i)) { browserName = 'Browser Name: Internet Explorer'; } else { browserName = navigator.userAgent + "\n" + navigator.vendor; } </script> <h2><script type="text/javascript">document.write(browserName)</script></h2> </body> </html>``` -
what are META classes in python
What are metaclasses and what do we use them for? I was trying to get to know a detailed explanation of it. -
Transmit params to meta subclass of an abstract model
Django 2.2.3 Could you help me transmit a param to Meta inner class of an abstract model. My efforts: class GeneralUtmAbstract(models.Model): where = "" class Meta: def __init__(self): self.verbose_name_plural = "General UTM-labels: {}".format(GeneralUtmAbstract.where) self.verbose_name = verbose_name_plural class GeneralUtm(GeneralUtmAbstract): where = "Both" class BingUtm(GeneralUtmAbstract): where = "Bing" class GoogleUtm(GeneralUtmAbstract): where = "Google" My code doesn't raise any errors. But verbose names just don't show as planned. I get "general utm" instead of "General UTM-labels: both". Could you give me a kick here? -
Error Specifying a namespace in include() without providing an app_name
When I tried my project runserver, this error File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\apple\Desktop\web3start\tests\urls.py", line 8, in <module> url(r'^', include('web3auth.urls', namespace='web3auth')), File "C:\Users\apple\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\urls\conf.py", line 39, in include 'Specifying a namespace in include() without providing an app_name ' django.core.exceptions.ImproperlyConfigured: Specifying a namespace in include() without providing an app_name is not supported. Set the app_name attribute in the included module, or pass a 2-tuple containing the list of patterns and app_name instead. came out. conf.py if isinstance(urlconf_module, str): urlconf_module = import_module(urlconf_module) patterns = getattr(urlconf_module, 'urlpatterns', urlconf_module) app_name = getattr(urlconf_module, 'app_name', app_name) if namespace and not app_name: raise ImproperlyConfigured( 'Specifying a namespace in include() without providing an app_name ' 'is not supported. Set the app_name attribute in the included ' 'module, or pass a 2-tuple containing the list of patterns and ' 'app_name instead.', urls.py # -*- coding: utf-8 -*- from __future__ import unicode_literals, absolute_import from django.conf.urls import url, include urlpatterns = [ url(r'^', include('web3auth.urls', namespace='web3auth')), ] What should I do?? I need a specific code directly to write on! -
"detail": "Method \"GET\" not allowed." Django Rest Framework
I know this question maybe a duplicate, but I have tried many solutions and could not understand any. I have followed this tutorial exactly and yet I get this error on the 'userlist' page. Everything else works just fine. Can somebody point out what the error is ? class UserList(APIView): """ Create a new user. It's called 'UserList' because normally we'd have a get method here too, for retrieving a list of all User objects. """ permission_classes = (permissions.AllowAny,) http_method_names = ['get', 'head'] def post (self, request, format=None): self.http_method_names.append("GET") serializer = UserSerializerWithToken(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) -
Django - "Post.user" must be a "User" instance
I have a memberships- app with a UserMembership-model that has a user field. memberships/models.py class UserMembership(models.Model): user = models.OneToOneField( settings.AUTH_USER_MODEL, on_delete=models.CASCADE) stripe_customer_id = models.CharField(max_length=40) membership = models.ForeignKey( Membership, on_delete=models.SET_NULL, null=True) website = models.URLField(default='', blank=True) member = models.DateTimeField(auto_now=True) def __str__(self): return self.user.username def post_save_usermembership_create(sender, instance, created, *args, **kwargs): user_membership, created = UserMembership.objects.get_or_create( user=instance) post_save.connect(post_save_usermembership_create, sender=settings.AUTH_USER_MODEL) When I try to use this user in another app, for example: user = request.user I get a unique constraint error or "usermembership cant be the sender of the message...". home/models.py from django.db import models from django.conf import settings class Post(models.Model): post = models.CharField(max_length=500) user = models.OneToOneField( settings.AUTH_USER_MODEL, on_delete=models.CASCADE) date = models.DateTimeField(auto_now=True) How do I get the user from the usermembership - model or the current logged-in user? home/views.py from django.contrib.auth import get_user_model user = get_user_model() class HomeView(TemplateView): template_name = 'home/home.html' def get(self,request): form = HomeForm() args = {'form': form} return render(request,self.template_name,args) def post(self,request): form = HomeForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.user = user post.save() text = form.cleaned_data['post'] form = HomeForm() args = {'form':form,'text':text} return render(request, self.template_name, args) Thank you -
Got Stuck When trying to Deploy a Restaurants Sentimental Analysis Model using Django
I am trying to Deploy my sentimental analysis model using Django but getting the following error. views.py file from django.shortcuts import render from django.http import HttpResponse from django.contrib.auth import authenticate import pandas as pd import matplotlib.pyplot as plt import pickle import re import nltk from nltk.tokenize import word_tokenize from nltk.stem import WordNetLemmatizer from string import punctuation from nltk.corpus import stopwords from sklearn.feature_extraction.text import CountVectorizer from sklearn.preprocessing import LabelEncoder # Create your views here. badfood=pickle.load(open('mymodel/pkl/BadFood.pickle','rb')) def index(request): return render(request,'mymodel/index.html') def remove_non_ascii_1(text): return ''.join(i for i in text if ord(i)<128) def clean_text(input_str): lemmatizer= WordNetLemmatizer() input_str=input_str.lower() remove_num=re.sub(r'\d+','',input_str) remove_punc=remove_num.translate(str.maketrans("","",punctuation)) remove_white=remove_punc.strip() stop_words=set(stopwords.words('english')) tokens=word_tokenize(remove_white) result=[i for i in tokens if not i in stop_words] lemmatized_words=[lemmatizer.lemmatize(word) for word in result] review=' '.join(lemmatized_words) return review def predict(request): # Grabbing data from user if request.method=="POST": review=request.POST.get('review','') city=request.POST.get('city','') input_data=[{'review':review,'city':city}] dataset=pd.DataFrame(input_data) dataset = dataset.replace(r'\r',' ', regex=True) dataset['review']=dataset['review'].apply(lambda x:remove_non_ascii_1(x)) dataset['review']=dataset['review'].apply(lambda x:clean_text(x)) # Bag of words vectorizer=CountVectorizer() features_data= pd.DataFrame(vectorizer.fit_transform(dataset.review).toarray()) features_data.columns=vectorizer.get_feature_names() features_data.insert(0,'city_x',dataset['city']) # Label Encoding the city column labelencoder=LabelEncoder() features_data['city_x']=labelencoder.fit_transform(features_data.city_x) features_data['city_x']=features_data['city_x'].astype('category') regressor=badfood.predict(features_data) return render(request,'mymodel/result.html',{'res':regressor}) ValueError at /predict/ Number of features of the model must match the input. Model n_features is 7397 and input n_features is 12 I have designed a user interface in which I am giving a text box field in which the … -
Django url error"NoReverseMatch at /2/ipd/"
I am having form which creates Ipd and Ipd model is created using patient model with one to many relationship, and I am already having one table with patient list in urls. I am trying to create the list of all Ipd that are created using form, I am trying to redirect the form page to Idp list after I submit for Ipd form but ending with this error "NoReverseMatch at /1/ipd/", One thing I want to clear is each Ipd is having unique id and Ipd is created from patient with one to many relationship which also have another unique id , the number which is in the error is patient id views.py @login_required def ipd(request, patient_id): object = get_object_or_404(Patient,pk=patient_id) if request.method == "POST": formtwo = IpdForm(request.POST) if formtwo.is_valid() : instance = formtwo.save(commit=False) instance.save() return HttpResponseRedirect(reverse('ipd_list', args=[patient_id])) else: return HttpResponse(formtwo.errors) else: formtwo = IpdForm() return render(request, 'newipd.html', {'object':object, 'form2': formtwo}) @login_required def ipd_list(request): ipdlist = Ipd.objects.all() return render(request, 'Ipdlist.html', {'ipd': ipdlist }) urls.py re_path(r'^(?P<patient_id>\d+)/ipd/$', my_patient.ipd, name='ipd'), path(r'^ipdlist/', my_patient.ipd_list,name='ipdlist' ), Template <ul> <li><a href="{% url 'ipdlist' %}" ><span class="title">Indoor Patient Department</span></a></li> </ul> ######## in ipdform <form class="col s12" role="form" action="{% url 'ipd_list' 'patient_id' %}" method="post" enctype="multipart/form-data"> {% csrf_token %} -
Customize Django Admin user password change form
I've customized my user model by using AbstractBaseUser. Everything works fine, but when I am in the Django Admin interface and us the form to change a user's password, in addition to the new password 1 and new password 2 fields, I also see their email in a text box: How can I remove their email address from appearing in my admin change password form? Is there a special Django form that I can subclass?