Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
- 
        
How to get data from multiple models in queryset utilizing 'select_related'?
I am trying to get combined queryset for two models, basically a LEFT JOIN for two tables. I read multiple answers on how to perform LEFT JOIN on querysets and I found that the easiest way is via select_related, so that is what I did. When I print the raw query, it looks good, it contains information from both tables (both models). However the returned queryset contains only the information from the first model. I read that this is a default and it can be overridden by get_query. And this is where I am lost, because the documentation provides get_query description only for class based view and so far I worked only with function based views. These are my models: class WorkPlace(models.Model): workplace = models.TextField(unique=True) nickname = models.TextField(null=True) def __str__(self): return f'{self.workplace}' class Status(models.Model): workplace = models.OneToOneField(WorkPlace, to_field="workplace", db_column="workplace", on_delete=models.SET_NULL, null=True) status = models.TextField() def __str__(self): return f'{self.status}' This it the view: def work_place_list_view(request): qs1 = WorkPlace.objects.select_related('status') print(qs1.query) context = {"workplace_list": qs1, "title": "Seznam pracovišť"} template_name = 'megavisor/workplace_list.html' return render(request, template_name, context) This is the raw query from console: SELECT "megavisor_workplace"."id", "megavisor_workplace"."workplace", "megavisor_workplace"."nickname", "megavisor_status"."id", "megavisor_status"."workplace", "megavisor_status"."status" FROM "megavisor_workplace" LEFT OUTER JOIN "megavisor_status" ON ("megavisor_workplace"."workplace" = "megavisor_status"."workplace") The output is the … - 
        
django - angular handling urls
I have created django api end-points for my app which will be hosted on google firebase and the frontend code will be all angular. While learning some stuff about integrating React with django I found out that django needs to be able to handle all the urls which react provides. That was easy for me because I had the code on my virtual environment together with the templates and static files. But regarding the real angular app I will not have the code on my side. Can anyone give me a general overview about these concepts. Thank you! - 
        
How to add title & description when documenting with core api using manual schema on django rest framework
I am using the core API library in documenting the following class view as shown below using a manual schema. How do I add the title and description so that they appear? As you can see from the screenshot below the query parameters defined from the manual schema only appear in the documentation. Class View class RecieptListAPIView(APIView): schema = schemas.ManualSchema(fields=[ coreapi.Field( "year", required=True, location="query", schema=coreschema.String( description="This is the year payed." ) ), coreapi.Field( "business_id", required=True, location="query", schema=coreschema.String( description="This is the unique business id of a business." ) ) ]) """Show reciept list. /api/sbp/receipts/?year=2018&business_id=1432658 """ queryset = Receipt.objects.all() serializer_class = ReceiptSerializer def get(self,request,format=None): """Return a list of reciepts.""" query = self.request.GET.get("business_id") year = self.request.GET.get("year") reciepts = Receipt.objects.filter(bill__business__business_id=query, bill__calender_year=year)[0] serializer = ReceiptSerializer(reciepts,many=True) return Response(data=serializer.data, status=status.HTTP_200_OK) Output - 
        
How to change the default registration in django
I have used django's default registration. I want to edit this forms because it's appearance does not look very good to me. I want to convert the instructions into tool tip or something better looking how can I do it?I am new to django html Register {% csrf_token %} {{ form.as_p }} Register - 
        
Using fixtures with pytest: How to share fixtures and use their parameters in different functions
I am struggling with setting up my fixtures correctly in pytest. I always get a missing 1 required positional argument: error. This is what I am trying: @pytest.mark.django_db class TestCreate: @pytest.fixture(scope='class') def user(self): username = 'testuser' password = 'mypassword' user_data = { 'username': username, 'password': password, } return user_data def setup(self, user): """Setup for tests to create user and project """ user_d = user print(user_d) username = user_d['username'] Basically I only want to access the dictionary in from my fixture. But I get E TypeError: setup() missing 1 required positional argument: 'user' I seems Pytest doesn't have access to my fixtures? Help is very much appreciated! Thanks in advance - 
        
Django url template tag not resolving when set through jquery
I've created a comment system for blog posts in Django (the comments are stored in a Comments model) in which the author of the post or comment can delete a comment by clicking on the delete link below the comment, which results in a modal pop up asking for confirmation. {% for comment in comments %} <!-- Display comment --> <a href="#" onclick="getCommentId(this)" data-id="{{ comment.id }}" data-toggle="modal" data-target="#exampleModalCenter">delete</a> {% endfor %} <!-- Modal --> <div class="modal fade" id="exampleModalCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLongTitle">Confirm Delete</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> Are you sure you want to delete the comment? </div> <div class="modal-footer"> <form id="confirm-delete-form" action="" method="POST"> {% csrf_token %} <button id="confirm-delete-btn" class="btn btn-danger" type="submit">Yes, Delete</button> </form> <button class="btn btn-secondary" data-dismiss="modal">Cancel</button> </div> </div> </div> </div> Corresponding views.py and urls.py sections: class CommentDeleteView(DeleteView): model = Comments success_url = '/' path('comment/<int:pk>/delete/', CommentDeleteView.as_view(), name='comment-delete') I'm dynamically setting the action attribute of the form in jquery when delete is clicked to pass the unique comment id: function getCommentId(comment) { var comment_id = $(comment).data("id"); var url = "{% url 'comment-delete' " + comment_id + " %}" $("#confirm-delete-form").attr('action', url) } But when … - 
        
Access to XMLHttpRequest at 'localhost:8000' from origin 'localhost:3000' has been blocked by CORS
I'm working on a project with Django Rest Framework as back-end and React as front-end. When I set a session variable initially in some function/view and later when I try to access the different view through axios call and in that view if I try to access session variable which i created previously, I get KeyError. Session doesn't seem stored. I googled I got the similar issue which I'm facing. Django rest framework Reactjs sessions not working I followed the process by adding { withCredentials: true } in axios call. Now i'm getting different error. Now the issue is not able to access the backend. I get an error saying Access to XMLHttpRequest at 'http://127.0.0.1:8000/url/' from origin 'http://localhost:3000' has been blocked by CORS policy Again I googled the issue which i'm getting and found that I've to add CORS_ORIGIN_WHITELIST in the django settings.py I have added CORS_ORIGIN_WHITELIST like this CORS_ORIGIN_WHITELIST = ( 'http://localhost:3000', 'http://127.0.0.1:3000' ) Still i'm facing the same issue. I don't know whats going wrong. Can any one please help me on this issue. Thank you. - 
        
Editing view for combined form and inlinel_formset
I have been trying to create an editing view that allows me manage both parent and child models using an inline formset based in the documentation here From what I can appreciate the formset doesn't validate. I did try and change it so that instead of validating the entire formset it iterated through each individual form in the formset and validated them individually. This did allow me to add items to the formset but not delete them. At the moment the code results in "didn't return an HttpResponse object. It returned None instead" value error as the redirect is in the If valid statement and so if that does not result in true there is no other redirect to fall back on. Models class Shoppinglist(models.Model): name = models.CharField(max_length=50) description = models.TextField(max_length=2000) created = models.DateField(auto_now_add=True) created_by = models.ForeignKey(User, related_name='lists', on_delete=models.CASCADE) last_updated = models.DateTimeField(auto_now=True) def __str__(self): return self.name class Item(models.Model): name = models.CharField(max_length=80, unique=True) amount = models.IntegerField(default=1) shoppinglist = models.ForeignKey(Shoppinglist, on_delete=models.CASCADE) def __str__(self): return self.name URL urlpatterns = [ url(r'^shoppinglists/(?P<pk>\d+)/edit/$', views.shoppinglist_edit, name='shoppinglist_edit'), ] View def packlist_edit(request, pk): try: shoppinglist = Shoppinglist.objects.get(pk=pk) except ShoppingList.DoesNotExist: raise Http404 ItemInlineFormset = inlineformset_factory(Shoppinglist, Item, extra=1, fields=('name', 'amount')) if request.method == "POST": form = ShoppinglistForm(request.POST, instance=shoppinglist) formset = … - 
        
Is it just not possible to have a celery server respond immediately to a message?
I have several celery servers with one worker each. The workers are busy doing long (8hr; I can't split it up) tasks. I want to be able to tell each server to do something immediately; but it looks like that's genuinely not possible - broadcast would put a task to be executed after the current one finishes, I believe? - 
        
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> …