Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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> … -
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)