Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Action attribute in html form tag is not sending the data in django
I want to send song.id from each song in an album model but every time I send it, I get A KeyError This is what I wrote in details.html {% if error_message %} <p><strong>{{ error_message }}</strong></p> {% endif %} <form action="{% url 'music:favorite' album.id %}"> {% csrf_token %} {% for song in album.song_set.all %} <input type="radio" id="song{{ song.id }}" name="song" value="{{ song.id }}"> <label for="song{{ song.id }}"> {{ song.song_title }} {% if song.is_favorite %} <img src="https://png.pngtree.com/png-vector/20190726/ourmid/pngtree-cute-light-star-with-black-frame-png-image_1633374.jpg"> {% endif %} </label> <br> {% endfor %} <input type="submit" value="Favorite"> </form> This is my views.py def favorite(request, album_id): album = get_object_or_404(Album, pk=album_id) try: selected_song = album.song_set.get(pk=request.POST['song']) except (KeyError, Song.DoesNotExist): return render(request, 'music/detail.html', { 'album':album, 'error_message':"You did not select a valid song", }) else: selected_song.is_favorite = True selected_song.save() return render(request, 'music/detail.html', {'album':album}) -
Filter users in form
I have a form for multi select drop-down. I want to use filter user=request.user in forms. class AssignPlanToUserForm(forms.Form): user_options = forms.ModelMultipleChoiceField(Company.objects.all(), widget=forms.SelectMultiple(attrs={'class': 'form-control name-option name-control'}), required=True) I want to add filter user=request.user in this field. Can anyone help or suggest anything. -
Hide some part of code in views DJANGO before send to GIT
Is is possible to hide some part of code in views before I send it to git or it is impossible? I have one issue and it would be the easiest way to solve it, i am trying to use .env file but unfortuntely does not work as it should. My problem TWILIO API ERROR Credentials are required to create a TwilioClient django so i have code which works in views, but not with using env file. -
Minimum mobile resolution in present date
What should me the minimum screen width a web developer should design his/her website in present date.It is 320px or 360px or even higher. -
ValueError: Field 'X' expected a number but got 'X'
So I was working on some fields in my models.py and ran a python3 manage.py makemigrations and python3 manage.py migrate. A few minutes later I decided to get rid of one of the fields, and replace it with something else - however, everytime I try to migrate and makemigrations, the error that Field 'X' (which is deleted) expected a number but got 'X'. Anyway around this considering my field is deleted? The exact error is: ValueError: Field 'randkey' expected a number but got '1AB2CD'. -
SMTPRecipientsRefused at /accounts/signup/ django-allauth
When I'm using django all-auth i'm facing error somethings like this. {'test@gmail.com': (553, b'5.7.1 : Sender address rejected: not owned by user .... enter image description here With out django allauth it is working fine. Here is my configurations 1 EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'mail.domain_naame.com' EMAIL_USE_TLS = True EMAIL_PORT = 587 EMAIL_HOST_USER = 'sandeep@domain_name.com' EMAIL_HOST_PASSWORD = 'account_password' -
Routing URLs between Django and Angular
I'm currently creating a website in Django and Angular. Django is serving the Angular build files. Excluding /api calls, all URLs are returned a template that loads the Angular index. This part works. The part I'm having trouble with is when I try to lazy-load modules. Angular will try to find a module foo at localhost:8000/foo-module.js, but it's really at localhost:8000/static/mydjangoapp/angular/foo-module.js. I know I could solve this problem by setting <base href="/" /> in index.html to <base href="/static/mydjangoapp/angular" />, but I want the frontend to be served from /. I could also avoid lazy-loading modules, but I feel like there's a better way to serve Angular from Django using which I can lazy-load. How can I get Angular to properly fetch the URLs? I'm also having a similar issue with serving Angular assets. -
django send response to website without changing it
This is what the form looks like right now This piece of code gets the input and has a rough IF statement that confirms if the confirm pasword input == password input, if not it redirects you and sends an http response that passwords do not match, now instead of an http response what i want to do is send a message without changing the website that confirm password == password like a little message that says passwords do not match while you type or after you press submit. views.py def get_data(request): username = request.POST.get('username', None) email = request.POST.get('email', None) password = request.POST.get('password', None) confirm_password = request.POST.get('confirmpassword', None) try: #validate the email validate_email(email) if confirm_password == password: # confirm password a = Account() a.username = username a.email = email a.password = password a.save() return HttpResponse('User %s has been registered. ' %(username)) else: return HttpResponse('<h1>Passwords do not match</h1>') except: return HttpResponse('<h1>%s is not a valid e-mail id.</h1>' %(email)) models.py from django.db import models from django import forms # Create your models here. class Account(models.Model): username = models.CharField(max_length=32) email = models.EmailField(max_length=64) password = models.CharField(max_length=16) urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('get-data', views.get_data, name='get-data'), … -
Django key, value dictionary returning data under the same key
I'm pulling post data from my firebase database and trying to pass it into my template in Django. I can easily pass just the values into the template but I'm trying to also pass the ID using a key-value dictionary but for some reason, I can't get it to work the way I want it to. It's returning all the values under the same key I would like each key to match the relating value. Database structure: "posts" : { "-LqytRym_35j-6il-nHQ" : { "title" : "Purple", "uid" : "LTAeaDscQyexbud3ijIMYpDCucO2" }, Views.py: posts = database.child("posts").child(favKey).get() posts_dict.append(posts.val()) at1 = {posts.query_key:[posts.val()]} print(at1) return render(request, 'users/favourites.html', {'posts': at1}) Template: {% for key, value in posts.items %} <article class="media content-section col-md-9 ml-sm-auto col-lg-10 px-4"> <img class="rounded-circle article-img" src="{{ post.author.profile.image.url }}"> <div class="media-body"> <div class="article-metadata"> <a class="mr-2" href="#">{{ key }}</a> <small class="text-muted"></small> </div> <h2><a class="article-title" href="#">{{ value.title }}</a></h2> <p class="article-content">{{ post.uid }}</p> </div> </article> {% endfor %} -
Update a single object from a database - Django/Python
So I am trying to allow users to edit menu item prices that are in the database currently. The fields will auto-populate data into the page and users will be able to edit that data to change the price. Here is what I have. I have tried and asked many questions, but I am still lost. I have googled a lot and it helped me understand forms a bit, but I'm not able to fix it. Please let me know if you need more info. Views.py: def edit_menu(request): queryset = Product.objects.all() context = { "object_list": queryset } if request.method == 'POST': post=ProductModelForm(request.POST) if request.POST.get('price') and request.POST.get('name'): if 'name' == Product.name: post.name= request.POST.get('name') post.price= request.POST.get('price') post.save() return redirect('Edit Menu Item') else: return redirect('Edit Menu Item') else: return render(request, 'mis446/edit-menu-item.html', context) else: return render(request, 'mis446/edit-menu-item.html', context) forms.py: class ProductModelForm(forms.ModelForm): class Meta: model = Product fields = ['name','price'] # specify which field you need to be in the form HTML: <title>ACRMS - Edit Menu Price</title> <div class = "container"> <form action = "" method = 'POST'> {% csrf_token %} {% for instance in object_list %} <input name = "name" value = "{{ instance.name }}"></input> <input type="number" name="price" value = "{{ instance.price }}"/><br> {% … -
how to correctly import urls.py from app?
This is probably pretty simple but I can't get my head around it. I'm learning Django, have v3.0.4 installed and can't get the URLs from an app to work correctly. On the project urls.py I have the following: Project\urls.py: from django.contrib import admin from django.urls import path from django.urls import include from AppTwo import views urlpatterns = [ path('', views.index, name='index'), path('', include('AppTwo.urls')), path('admin/', admin.site.urls), ] I've created an app named "AppTwo" and have the following urls.py and views.py in the app: AppTwo\urls.py: from django.urls import path from . import views urlpatterns = [ path('/help', views.help, name='help'), ] AppTwo\views.py: from django.shortcuts import render from django.http import HttpResponse # Create your views here. def index(request): return HttpResponse("<em>My Second App</em>") def help(request): return HttpResponse("<em>Help Page!!!</em>") If I browse to http://127.0.0.1:8000/ the index page loads and I see the text "My Second App" as expected. However if I browse to http://127.0.0.1:8000/help I get page not found 404 error. I can also browse to the admin page just fine. So far this is a stock project, the only other change I made after creating it was to the settings.py file to install the "AppTwo" application. Based on the documentation, this looks like it should … -
django cannot get static css to work in template base.html
I am trying to setup a site wide css file. My css will render if I place it directly in my block content cat register/templates/register/register.html {% extends "base.html" %} {% block title %}Create an Account{% endblock %} {% load crispy_forms_tags %} {% block content %} <style> .registration_base { padding-top: 50px; margin: auto; width: 30%; } </style> <div class="registration_base"> <form method="POST" class="form-group"> {% csrf_token %} {{ form|crispy }} <button type="submit" class="btn btn-success">Register</button> </form> {% endblock %} </div> and it will function fine but I would like the code called from a style.css file site wide, in my base.html file. I cannot get the css file to actually render. In my templates/base.html I have <head> <link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}style.css"> </head> in my register/static/style.css I have the same css code: .registration_base { padding-top: 50px; margin: auto; width: 30%; } I can run #python3 manage.py findstatic style.css Found 'style.css' here: /home/user/www/src/register/static/style.css and it finds it, but my css formatting never changes. I have the app installed in site/settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'pages', 'register.apps.RegisterConfig', 'crispy_forms', ] How do I get a site wide css file properly included? -
how to detect url IP change in django
I am trying to detect the change in IP address for my website. If website IP address is changed, then redirect the page to login screen with new ip address. Detailed problem statement explanation given below Lets say website URL assigned to IP address 192.168.0.15 Login to the website and navigate to any page or just remain on the home page Change the website IP address to 192.168.0.12 (or something different from step 1) Select a link to a different page in already opened screen (in step 2) Confirm the Login screen is displayed. Could you please help me how this can be achieved in Django. -
django rest api not creating user
halo i'm working on a django rest_framework api code for user signup, but when i test the code with postman, they user doesn't get registered and it doesn't return any particular error, hoping anyone can help out, below is my models, serializers and views codes..... models class CustomUser(AbstractUser): username = None email = models.EmailField(_('email address'), unique=True) password = models.CharField(max_length=100) created = models.DateField(auto_now=True) timestamp = models.DateTimeField(auto_now=True) role = models.CharField(max_length=5) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] def __str__(self): return self.email class Meta: ordering = ('email',) objects = CustomManager() views @api_view(['POST', ]) def registration(request): if request.method =='POST': serializer = RegisterUserSerializer(data=request.data) data = {} if serializer.is_valid(): user = serializer.save() data['response'] = 'registration successful' data['email'] = user.email else: data = serializer.errors return Response(data) Serializers class RegisterUserSerializer(serializers.HyperlinkedModelSerializer): confirm_password = serializers.CharField(style= {'input_type': 'password'}, write_only=True) class Meta: model = CustomUser fields = ['id', 'email', 'password', 'confirm_password'] extra_kwargs = {'password': {'write_only': True, 'required': True}} def save(self): user = CustomUser( email = self.validated_data['email'], ) password = self.validated_data['password'] confirm_password = self.validated_data['confirm_password'] if password != confirm_password: raise serializers.ValidationError({'password: Password didn\' match'}) user.set_password(password) user.save() return user -
ProgrammingError at /admin/auth/user/1/change/
Cant add user to group Cant add permission to a group or user I already used pgAdmin and django shell but same throwing this error ProgrammingError at /admin/auth/user/1/change/ The whole traceback: Traceback Switch to copy-and-paste view C:\Users\User\Envs\work\lib\site-packages\django\db\backends\utils.py in _execute return self.cursor.execute(sql, params) … ▶ Local vars The above exception (syntax error at or near "ON" LINE 1: ...ser_groups" ("user_id", "group_id") VALUES (1, 1) ON CONFLIC... ^ ) was the direct cause of the following exception: C:\Users\User\Envs\work\lib\site-packages\django\core\handlers\exception.py in inner response = get_response(request) … ▶ Local vars C:\Users\User\Envs\work\lib\site-packages\django\core\handlers\base.py in _get_response response = self.process_exception_by_middleware(e, request) … ▶ Local vars C:\Users\User\Envs\work\lib\site-packages\django\core\handlers\base.py in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) … ▶ Local vars C:\Users\User\Envs\work\lib\site-packages\django\contrib\admin\options.py in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) … ▶ Local vars C:\Users\User\Envs\work\lib\site-packages\django\utils\decorators.py in _wrapped_view response = view_func(request, *args, **kwargs) … ▶ Local vars C:\Users\User\Envs\work\lib\site-packages\django\views\decorators\cache.py in _wrapped_view_func response = view_func(request, *args, **kwargs) … ▶ Local vars C:\Users\User\Envs\work\lib\site-packages\django\contrib\admin\sites.py in inner return view(request, *args, **kwargs) … ▶ Local vars C:\Users\User\Envs\work\lib\site-packages\django\contrib\admin\options.py in change_view return self.changeform_view(request, object_id, form_url, extra_context) … ▶ Local vars C:\Users\User\Envs\work\lib\site-packages\django\utils\decorators.py in _wrapper return bound_method(*args, **kwargs) … ▶ Local vars C:\Users\User\Envs\work\lib\site-packages\django\utils\decorators.py in _wrapped_view response = view_func(request, *args, **kwargs) … ▶ Local vars C:\Users\User\Envs\work\lib\site-packages\django\contrib\admin\options.py in changeform_view return self._changeform_view(request, object_id, form_url, extra_context) … ▶ Local vars C:\Users\User\Envs\work\lib\site-packages\django\contrib\admin\options.py … -
linkedin-oauth2 fails with "redirect_uri does not match the registered value" on Safari but works on Firefox and Chrome
I manage Presbot.com Linkedin works fine on Chrome, Firefox but fails with "The redirect_uri does not match the registered value" only on Safari. I am unable to track this issue down and need some guidance on debugging this. The linkedin App is configured with a redirect_url that starts with http. I suspect the issue is related to redirects but not sure how to debug. Any help would be appreciated. Server Os: Ubuntu 18.04.3 LTS (GNU/Linux 4.15.0-1021-aws x86_64) Web Server: nginx version: nginx/1.14.0 (Ubuntu) SSL: NGINX is configured with HTTPS certificates via Let’s Encrypt App server: Gunicorn (gunicorn==20.0.0) Web Framework: Django==2.2.4 social-auth-app-django==3.1.0 -
Django 3 and jQuery - sort <li> items on all paginated pages
Currently I can sort li items on one page but not all paginated pages. I select an item from a dropdown list to sort by various attributes based on a model. Here is the jquery for one of the items. ''' var sortIconsetsTitle = function () { $("ul.iconsets-list li[data-sort-title]").detach().sort(function(a,b){ return String($(b).attr('data-sort-title')) < String($(a).attr('data-sort-title')) }).appendTo($("ul.iconsets-list")) $('div.iconsets-sort span').text("Title"); // show the order by name }; $('li a.sort-title').on('click', function () { sortIconsetsTitle(); }); //make it so ''' The code works beautifully - but only on one page. How can I use this code to return results from all the paginated pages? -
Foreign Key between Django application
In Django, I would like to link foreign key from another app. Bellow is the method for same application, but in my case, they are two different applications on same project. App Client Model : name = models.CharField(max_length=64) App Invoice Model : client = models.ForeignKey('Client', on_delete=models.CASCADE) thanks -
Count the number times a choice is selected by users, and plot a chart based on the data
I have a model models.py ILLNESS_CHOICES = ( (1, "Anxiety"), (2, "Arthritis "), (3, "Asthma"), (4, "Anemia"), (5, "Cancer"), (6, "Covid-19"), (7, "Diabetes"), (8, "Ebola"), (9, "HIV"), ) class MedicalHistory(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) illness = MultiSelectField(choices=ILLNESS_CHOICES) symptoms = models.CharField(max_length=100) additional_info = models.CharField(max_length=100) disability = models.BooleanField(default=False) medications = models.BooleanField(default=False) created_at = models.DateTimeField(default=timezone.now) def __str__(self): return f'{self.user.username} Medical History' I am trying to plot a chart by counting the number of times an Illness is selected by users. I have seen similar questions from Count the number of occurrences of certain choices in models, Django Monthly/quartarly grouping of DateField() data and some other tutorials, but I am still not clear on how to approach. I am making use of Chart.js to display the data. views.py def pie_chart(request): labels = [] # illnesses as labels data = [] queryset = # get the count of each of the choices selected by users for entry in queryset: labels.append(#append the labels) data.append(#append the count of the choices) return JsonResponse(data={ 'labels': labels, 'data': data, }) Any help with this would be appreciated. -
Django how to annotate count nested forloop queryset dictionary
Good Day, My Problem is: my project depending on giving points to users who make any actions like (post, comment, favorite, likes ......). So, in users list page i want to list all users and other data for each user (name, points, badges, ....) to give the users points i have to count his posts, comments, likes, and so on..... i tried several methods and ways but all is failed to get annotate or prefetch_related or select_related Models.py class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='posts') Views.py def user_list(request): users = User.objects.all() template = 'user/users_list.html' nested_posts = {} for user in users: posts = user.posts.all() nested_posts[user, posts] = posts.count() print("nested : ", nested_posts) context = { 'users': users, 'user':user, 'posts': posts, 'nested_posts': nested_posts,} return render(request, template, context) when i print nested .. i found the count of every user' posts .. but how can i make it as variable to re-use in calculated field QuerySet nested : {(<User: Fareed>, <QuerySet [<Post: Senior Purchasing Specialist>]>): 1, (<User: Hussein>, <QuerySet [<Post: Senior Software Development Engineer in Test>]>): 1, (<User: Karima>, <QuerySet []>): 0, (<User: Yahia>, <QuerySet []>): 0} and i also tried : GetUserID = User.objects.get(id=2) var01 … -
Append information to queryset to sort
I have Book and and Reader models, and each of them have m2m relationship with Author and Genre. For any given book, I have a function that iterates over all readers and calculates a likely_to_read score (from 0 to 100, details of how it's calculated aren't particularly relevant). I'd like to now have this function return a list of readers sorted by likely_to_read from highest to lowest, that also includes the calculated score, but I'm not sure what the best way of achieving this is. I know I can create a local dictionary that stores just the reader_id and likely_to_read score, and then reverse it by score and have another queryset where id__in=<ids>, but I'm wondering if there's some way to 'extend' the queryset with this score? -
What's the purpose of setting "X-Forwarded-For" header in nginx
I have the following Nginx configuration for my Django application: upstream api { server localhost:8000; } server { listen 80; location / { proxy_pass http://api; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } location /staticfiles { alias /app/static/; } } I based this config on a tutorial here. After some research, looks like setting the Host header allows the Django API to determine original client's IP address (instead of the IP address of the proxy). What's the point of the X-Forwarded-For header? I see a field called $http_x_forwarded_for in the nginx logs but I'm not sure it's related. -
Django swagger ui not accessible on nginx
I have setup Django using nginx, gunicorn and postgres as per below url. https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-centos-7 Now I am trying to access swagger ui. Nginx is up and running however showing default page. When I run the same project using, python manage.py runserver myip:8000 and then access the same url I can see actual swagger ui with rest end points. I am not sure what I am doing wrong here. Here is what I have added to nginx file. server { listen 80; server_name <myipaddress>; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/threat-dashboard/backend; } location / { proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_pass http://unix:/tmp/backend.sock; } } -
Clear entire cart with one button click - Django/Python
So I have a working shopping cart. You can add and delete items, one at a time. However, once payment is submitted, I want to be able to just click a button and delete all of the items in the cart at once. Here is what I have: Cart Views.py: def remove_from_cart(request, id): try: the_id = request.session['cart_id'] cart = Cart.objects.get(id=the_id) except: return HttpResponseRedirect(reverse("cart")) cartitem = CartItem.objects.get(id=id) cartitem.delete() return HttpResponseRedirect(reverse("cart")) try: the_id = request.session['cart_id'] cart = Cart.objects.get(id=the_id) except: return HttpResponseRedirect(reverse("cart")) cartitem = Cart.objects.all() cartitem.delete.all() return HttpResponseRedirect(reverse("cart")) The top section is what allows users to delete one item at a time. The second half is me attempting to use the same view on the same page to delete every cart item. Models.py: class CartItem(models.Model): cart = models.ForeignKey('Cart', null= True, blank = True, on_delete = models.CASCADE) product = models.ForeignKey(Product, on_delete = models.CASCADE) quantity = models.IntegerField(default=1) line_total = models.DecimalField(default = 10.99, max_digits = 1000, decimal_places=2) def __unicode__(self): try: return str(self.cart.id) except: return self.product.title class Cart(models.Model): total = models.DecimalField(max_digits=100, decimal_places=2, default=0.00) active = models.BooleanField(default=True) def __unicode__(self): return "Cart id: %s" %(self.id) Urls.py: url(r'^add-to-cart/(?P<item_id>[-\w]+)/$', add_to_cart, name="add_to_cart"), url(r'^cart/(?P<id>\d+)/$', carts_views.remove_from_cart, name='remove_from_cart'), url(r'^cart/(?P<slug>[\w-]+)/(?P<qty>\d+)/$', carts_views.update_cart, name='update_cart'), url(r'^cart/$', carts_views.view, name='cart'), url(r'^cart/(?P<id>\d+)/$', carts_views.remove_from_cart, name='clear_cart'), HTML: {% for item in cart.cartitem_set.all %} <a … -
e.preventDefault() not letting me submit my form
I wrote some javascript to validate a form. However, if the form fields pass all validations, the form never submits! Is my code somehow incorrectly preventing the form from being able to submit? If I delete all of the javascript and use browser's built-in validation then form executes fine and user is added to the database. const form = document.getElementById('form'); const first_name = document.getElementById('first_name'); const last_name = document.getElementById('last_name'); const username = document.getElementById('username'); const email = document.getElementById('email'); const password = document.getElementById('password'); const password2 = document.getElementById('password2'); // Show input error message function showError(input, message) { input.className = 'form-control is-invalid'; const small = input.parentElement.querySelector('small'); small.className = 'invalid-feedback'; small.innerText = message; } // Show success outline function showSuccess(input, message) { input.className = 'form-control is-valid'; const small = input.parentElement.querySelector('small'); small.className = 'valid-feedback'; small.innerText = message; } function checkRequired(inputArray) { inputArray.forEach(function(input) { if (input.value.trim() === '') { showError(input, `${getFieldName(input)} is required`); return false; } else { showSuccess(input, "Looks Good!"); return true; } }); } // Check email is valid function checkEmail(input) { const re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; if (re.test(input.value.trim())) { showSuccess(input, 'Looks Good!'); return true; } else { showError(input, 'Email is not valid'); return false; } } // Check input length function checkLength(input, min, max) { if …