Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to change this code to make sure the User can only send a follow request once and not multiple times?
Hey guys I have a model and a function to send follow request to other users and they will be accepting the request if the sender has to follow them. problem is I need to make sure that when the sender first sends a request, the button shouldn't show follow again, instead should show cancel option to delete that request. As of now the user can send requests again and again. These are the codes. def send_follow_request(request, username): user_from = request.user user_to = Account.objects.get(username=username) # is_requested = False send_request = notify.send(user_from, recipient=user_to, verb='has sent you a follow request', target=user_to) # is_requested = True return redirect('posts:userprofile', user_to.username) models.py class Contact(models.Model): user_from = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='rel_from_set', on_delete=models.CASCADE) user_to = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='rel_to_set', on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True, db_index=True) follow_status = models.CharField(choices=FOLLOW_STATUS, max_length=10) #USER_FROM IS THE ONE WHO IS FOLLOWING AND USER_TO IS ONE BEING FOLLOWED class Meta: ordering = ('-created',) def __str__(self): return f'{self.user_from} follows {self.user_to}' following = models.ManyToManyField('self', through=Contact, related_name='followers', symmetrical=False) #adding the above field to User Model class user_model = get_user_model() user_model.add_to_class('following', models.ManyToManyField('self', through=Contact, related_name='followers', symmetrical=False)) Thank you -
Django - 'QuerySet' object has no attribute 'künstler_set'
I have a relation between an artist and images. I want to show a single artist and his related images. I created two models for artist and image. Inside the image class I made a ForeignKey to artist: class Artist(models.Model): profilepic = models.ImageField( blank=True) surname = models.CharField(max_length=120) class Image(models.Model): image = models.ImageField() relArtist = models.ForeignKey(Artist, null=True, on_delete=models.SET_NULL) inside my views.py I tried to get the artist by ID (primaryKey) which is working perfectly but it didn't work with the images. def artistSingle(request, pk): artist = Artist.objects.filter(id=pk) images = artist.relArtist_set.all() return render(request, 'artists/artistSingle.html', { 'artist': artist, 'images': images, }) If I run the code it throws an error: 'QuerySet' object has no attribute 'relArtist_set' I dont know how to get the images which rely to the artist. Does someone have a solution? -
How to be sent to another html page using django ID
I am creating a website where i am using django database.The database will have one def called categories and one called gifi.So a gif will belong to a category and when one category will be clicked it will send the user to a page where all gifs that belong to that category will show up,and when i click to one of the gifs i will be sent to another html page that will contain information about the clicked gif.I know that i should do something like requesting ID but i dont know the code. This is the models: from django.db import models class categorite(models.Model): name = models.CharField(max_length=100) id = models.AutoField(primary_key=True) class Gifi(models.Model): foto = models.ImageField(upload_to='website/static/') emri = models.CharField(max_length=100) Source = models.CharField(max_length=100) Kodet = models.CharField(max_length=12) categoryId = models.ForeignKey(categorite, on_delete=models.CASCADE) id = models.AutoField(primary_key=True) This is views: from django.shortcuts import render,get_object_or_404 from .models import Gifi,categorite # Create your views here. def home(request): return render(request, 'website/home.html') def categories(request): content = { 'view': categorite.objects.all() } return render(request, 'website/categories.html',content) def PostaCode(request): return render(request, 'website/PostaCode.html') def Contact(request): return render(request, 'website/Contact.html') def category(request,id): content = { 'view': Gifi.objects.filter(categoryId_id=id), } return render(request, 'website/category.html',content) def code(request,id): content = { 'view': Gifi.objects.filter(id_id=id) } return render(request, 'website/code.html',content) The def code is the … -
django form doesn't upload images but admin panel does how can I solve this problem,
This is all files in my GitHub enter link description here -
Access to XMLHttpRequest at 'http://localhost:8000/api/posts/' from origin 'http://localhost:3000' has been blocked by CORS policy. Django and React
I am creating a full-stack app with Django and React. I created a component lookup in which I use cookies. This is my code: function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = cookies[i].trim(); if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } function lookup(method, endpoint, callback, data) { let jsonData; if (data){ jsonData = JSON.stringify(data) } const xhr = new XMLHttpRequest() const url = `http://localhost:8000/api${endpoint}` xhr.responseType = "json" const csrftoken = getCookie('csrftoken'); xhr.open(method, url) xhr.setRequestHeader("Content-Type", "application/json") if (csrftoken){ xhr.setRequestHeader("HTTP_X_REQUESTED_WITH", "XMLHttpRequest") xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest") xhr.setRequestHeader("X-CSRFToken", csrftoken) } xhr.onload = function() { callback(xhr.response, xhr.status) } xhr.onerror = function (e) { console.log(e) callback({"message": "The request was an error"}, 400) } xhr.send(jsonData) } export function createPost(newPost, callback){ lookup("POST", "/posts/create/", callback, {content: newPost}) } export function loadPosts(callback) { lookup("GET", "/posts/", callback) } This code results in this error in my frontend: (the backend works fine) Access to XMLHttpRequest at 'http://localhost:8000/api/posts/' from origin 'http://localhost:3000' has been blocked by CORS policy: Request header field http_x_requested_with is not allowed by Access-Control-Allow-Headers in preflight … -
Invalid base64-encoded string: number of data characters (217) cannot be 1 more than a multiple of 4
I am learning django and creating a todo app using it. while setting up the django rest framework api. I am getting an unusual error. I am using django for some time, but never got the same error before. I don't know why is this error coming. The error occurred the very first time when I executed the command manage.py runserver and navigated to users The error is as below Invalid base64-encoded string: number of data characters (217) cannot be 1 more than a multiple of 4 Request Method: GET Request URL: http://127.0.0.1:8001/users/ Django Version: 3.1 Exception Type: Error Exception Value: Invalid base64-encoded string: number of data characters (217) cannot be 1 more than a multiple of 4 Exception Location: /usr/local/Cellar/python@3.8/3.8.5/Frameworks/Python.framework/Versions/3.8/lib/python3.8/base64.py, line 87, in b64decode Python Executable: /Users/yogendrakumar/PycharmProjects/todo_app/bin/python Python Version: 3.8.5 Python Path: ['/Users/yogendrakumar/PycharmProjects/todo_app', '/usr/local/Cellar/python@3.8/3.8.5/Frameworks/Python.framework/Versions/3.8/lib/python38.zip', '/usr/local/Cellar/python@3.8/3.8.5/Frameworks/Python.framework/Versions/3.8/lib/python3.8', '/usr/local/Cellar/python@3.8/3.8.5/Frameworks/Python.framework/Versions/3.8/lib/python3.8/lib-dynload', '/Users/yogendrakumar/PycharmProjects/todo_app/lib/python3.8/site-packages'] Server time: Sat, 29 Aug 2020 12:25:01 +0530 views.py from django.contrib.auth.models import User, Group from rest_framework import viewsets from rest_framework import permissions from todo.serializers import UserSerializer, GroupSerializer class UserViewSet(viewsets.ModelViewSet): """ API endpoint that allows users to be viewed or edited. """ queryset = User.objects.all().order_by('-date_joined') serializer_class = UserSerializer permission_classes = [permissions.IsAuthenticated] class GroupViewSet(viewsets.ModelViewSet): """ API endpoint that allows groups to be viewed or … -
What is the preffered way to access Django Database ? Raw SQL or Django queries?
Django documentation suggests to use Django ORM queries to access database to avoid certain issues with Raw SQL. Later I found that almost any queries can be done with Django ORM queries. I have not studied SQL queries much and relied heavily on ORM. does Raw SQL queries have any advantages ? -
how can i solve this error ( Field 'total_price' expected a number but got {'price__sum': 222} ) django?
how can i get the total_price of books which the added by user in store. i also add a @property to calculate and save the total price. when i try to save the form i getting typeError Exception Value: Field 'total_price' expected a number but got {'price__sum': 222}. how can i solve this issue? Store class Book(models.Model): name = models.CharField(max_length=100) price = models.IntegerField(default=0) def __str__(self): return self.name class Store(models.Model): keeper = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) books = models.ManyToManyField(Book) total_price = models.IntegerField(default=0) @property def save(self): self.total_price = self.books.all().aggregate(Sum('price')) super(Store, self).save() -
How to compare dictionary key and queryset value in Django Template
I'm trying to compare a dictionary key with query set variable in a Django Template. Both output correctly on their own, however, together I cannot compare the values. Django template {% for object in query_set %} {% for key, value in dictionary.items %} var key = {{ key }}; {% if key == query_set.name %} <h5> You get this value: {{ value }}</h5> {% endif %} {% endfor %} {% endfor %} What ends up happening is that key gets all the variable values instead of a singular value and it cannot properly compare. Output of key key var = output 1; key var = output 2; key var = output 3; I think I'm just missing a syntax error or maybe I need to write a custom html tag to do this? -
Return key/attribute JSON object instead of array of JSONs for model Django Rest Framework
Like mentioned in the title.I have such JSON array being returned from backend: [ {id:1, name:'name1'}, {id:2, name:'name2'}, {id:3, name:'name3'}, {id:4, name:'name4'} ] and I would like to return something like this instead: { "1": {id:1, name:'name1'}, "2": {id:2, name:'name2'}, "3": {id:3, name:'name3'}, "4": {id:4, name:'name4') } Is it possible in Django Rest framework to send such object as Response ? Obviously there will not be too many keys so size should not be an issue. -
How to translate field name in Django?
I am writing a web app backend that need to reuse an existing REST API. The API has a list of configuration field in JSON looks like this: feature1.export.car.functionA feature1.export.car.functionB feature2.a.b.c Whereas it is a dot notation string and the value can be anything. I was planning to have several Django models that represent those fields base on the feature and each configuration field will be represented by each model field. I am planning to use verbose_name in the Field object to represent the actual Django model field so that I can do the mapping between the input field from the API and the Django model field: class Feature1(models.Model): export_car = models.CharField(verbose_name="feature1.export.car.functionA") class Feature2(models.Model): a_field = models.CharField(verbose_name="feature2.a.b.c") But I am not sure how to do the 1 to 1 mapping when I receive the request from the View class. Is there an easy way to do that in Django? -
cURL - file upload with file path location not working with windows command prompt
I am trying to send a file to server using cURL command from windows command prompt. But getting error message. But using postman I am able to send a file to server. Below given details. These are the two cURL commands I tried to send/upload file by just sending file location: curl --insecure -F user_file=@"C:/Users/402096/Desktop/dau_settings-123.conf" -H "Content-Type: application/json" -H "Authorization: Token 3f98d0a178ddd176faea94e6d629621920d203b2624550e68a" -X POST https://10.107.12.123/import_config curl --insecure -F "user_file=@C:/Users/402096/Desktop/dau_settings-123.conf" -H "Content-Type: application/json" -H "Authorization: Token 3f98d0a178ddd176faea94e6d629621920d203b2624550e68a" -X POST https://10.107.12.123/import_config Here is the my code which will be called to upload a file in django @api_view(["POST", "GET"]) @permission_classes((IsAuthenticated,)) @permission_required('dau_gui_app.execute_import_config') def import_config_view(request): if request.method == 'POST' and request.FILES['user_file']: user_file = request.FILES['user_file'] fs = FileSystemStorage() filename = fs.save( user_file.name, user_file) filePath = fs.location + "/" + filename print filePath message ="{\ \"command\":\"execute\",\ \"subcommand\":\"import_config\",\ \"args\": [{\"file_path\":\"" + filePath + "\"}]}" message.replace(" ", "") try: response = send_cmd(message) except: print("An exception occurred sending the message:") print(message) #end try fs.delete(filename) return HttpResponse(response, content_type='application/json') return render(request, 'dau_gui_app/import_config.html' ,{'title':"Import Configuration" }) NOTE: I am able to successfully upload a file using postman. When I looked at the cURL code that postman has used to upload/send a file, I see below cURL in postman. But when I typed same … -
When an object is created with an admin form, how can to create related objects?
When I create a PotatoBatch item via my admin form, I want many Potato objects to be created. Potato has a ForeignKey to PotatoBatch. I made a PotatoBatchCreateForm that has an extra field, "number_of_potatoes". When I save this form, I want it to generate the correct number of potatoes for this batch. I wanted to override my PotatoBatchCreateForm's save method like this : def save(self, commit=True): potato_batch = super().save() # save the potato_batch object in order to have an object id number_of_potatoes = self.cleaned_data['number_of_potatoes'] for i in range(number_of_potatoes): Potato.objects.create(potato_batch=potato_batch) return potato_batch But this fails with a 'PotatoBatchCreateForm' object has no attribute 'save_m2m' error. How can I resolve this ? -
Django Error: "You're using the staticfiles app without having set the required STATIC_URL setting"
django.core.exceptions.ImproperlyConfigured: You're using the staticfiles app without having set the required STATIC_URL setting. This is appearing in the command prompt. I'm not sure I understand -
Javascript formdata object doesn't send any key, pair value over to the django frame
Django framework isn't able to print the post data from the XMLHttpRequest I'm writing vanilla javascript by the way and not jquery, Please don't write a jquery answer . Thanks In Advance. BELOW IS MY HTML CODE <form action="{% url 'feed:update_comment' comment.id %}" method="POST" onsubmit="UpdateComment(event)" class="comment-update-form">{% csrf_token %} <div class="close-comment-box"onclick="this.parentElement.parentElement.classList.add('hide')"> <span>&times;</span> </div> <textarea name="body" id="post_body">{{comment.text}}</textarea> <div class="btn-div"> <button type="submit" class="button">Update</button> </div> </form> BELOW IS MY VANILLA JAVASCRIPT function UpdateComment(event){ event.preventDefault() let comment_field_to_update = event.target.parentElement.parentElement.parentElement.querySelector('.comment-text-div').querySelector('.feed_text_element') const data = new FormData(event.target); const xhttp = new XMLHttpRequest(); xhttp.onload = (response)=>{ console.log(response) } xhttp.open("POST",event.target.getAttribute("action","action"),true) xhttp.setRequestHeader("Content-Type",'application/x-www-formurlencoded') xhttp.setRequestHeader('X-CSRFToken',csrftoken) xhttp.send(data) } BELOW IS MY PYTHON DJANGO CODE from django.http import JsonResponse @login_required def updateComment(request,id): if request.method == "POST": response = {} try: comment = Comment.objects.get(id=id) if comment.author == request.user: comment.text = request.POST['body'] comment.save response['200'] = comment.text return JsonResponse(response) else: response['400'] = 'You Can"t Edit This Comment' return JsonResponse(response) except Comment.DoesNotExist: response['404'] = 'Comment Not Found' return JsonResponse(response) BELOW IS THE ERROR I'M GETTING FROM DJANGO System check identified no issues (0 silenced). August 29, 2020 - 17:23:54 Django version 2.2.14, using settings 'jumbo.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Internal Server Error: /update_comment&comment_identifier=/9/ Traceback (most recent call last): File "/usr/lib/python3/dist-packages/django/utils/datastructures.py", line 78, in … -
How to create a system tray popup message with Django? (Windows)
I have a web app, in Django, Azure. I want to click a button and send a notification to another users (user info stored in db). This has to appear on their notification bar when they are logged in. How can I initiate it? I know there are several ways to do it, please suggest the best option. -
JavaScript translates my "a" string to 'a'
I'm sending: short_names = ["a", "b"] as context through function view to JS. Then I'm using it in JS: let names = {{ short_names }}; But what i really got is: labels: [&#x27;a&#x27;, &#x27;b&#x27;] What's going on with this behaviour? How may omit it? -
Django : how to divide result from search
Assume I've created a search views with chain (multiple search from different app). I want to display my result at the same place: {% for object in object_list %} {% with object|class_name as klass %} {% if klass == 'Post' %} {{ object.title }} {% elif klass == 'Catego' %} {{ object.name }} {% elif klass == 'UserProfile' %} {{ object.user.username }} {% else %} {% endif %} {% endwith %} {% empty %} {% endfor %} Everything is ok. I got all of my result. Now, if I want to separate this result in different div (row and collapse class). If I try this: <div class="row collapse" id="collapseNutri"> {% for object in object_list %} {% with object|class_name as klass %} {% if klass == 'Post' %} {{ object.title }} {% endif %} {% endwith %} {% endfor %} </div> <div class="row collapse" id="collapseCatego"> {% for object in object_list %} {% with object|class_name as klass %} {% if klass == 'Catego' %} {{ object.name }} {% endif %} {% endwith %} {% endfor %} </div> <div class="row collapse" id="collapseUserProfile"> {% for object in object_list %} {% with object|class_name as klass %} {% if klass == 'UserProfile' %} {{ object.user.username }} … -
How can I load a module in a Django template with a variable for the module name?
I want to build some very similar apps in Django, but I want them to load different tag/filter modules. For this I want the html templates to be generic. For example, I would like to have something like {% load specific_tags %} and then I would like to define the variable specific_tags in a context processor for each app. But Django thinks that it should look for "specific_tags" in the installed apps in settings.py. How can I tell Django/Python to first evaluate the content of the variable from the context processor? Best regards -
Performing layer 7 health check with HAProxy and uWSGI in Django application
I'm using this uwsgi.ini to run a Django application. [uwsgi] http-socket = :8000 enable-proxy-protocol = true chdir = /usr/local/src/api module = api.wsgi uid = root gid = root pidfile = /var/run/api-uwsgi.pid master = true processes = 10 chmod-socket = 664 threaded-logger = true logto = /var/log/api/uwsgi.log log-maxsize = 10000000 logfile-chown = true vacuum = true die-on-term = true I've added an API url to perform database and cache health checks under the /health-check url. This API returns status code 200 if everything is fine. Now I want to be able to health check in layer 7 using this API with HAProxy but using option httpchk the response status code is 301, so the health check fails. Here is the backend part of my HAProxy config. backend http_server mode http balance leastconn option forwardfor http-request set-header X-Forwarded-Port %[dst_port] http-request add-header X-Forwarded-Proto https if { ssl_fc } option httpchk http-check send meth GET uri /health-check ver HTTP/1.1 hdr Accept application\json http-check expect rstatus 200 server app1 192.168.0.11:8000 check inter 500 downinter 5s fall 2 rise 3 server app2 192.168.0.12:8000 check inter 500 downinter 5s fall 2 rise 3 Here is the result of running the Django apps with uWSGI and HAProxy. Note … -
Sorl-thumbnail--> Image height is not equals to the given height
After implementing the below code when i see image on frontend width is 430 but height not equals to th given height(250) instead it is 100 {% load thumbnail %} {% thumbnail recipe.image "430x250" as thumb %} {% endthumbnail %} -
Custom permissions for Simple-JWT in Django Rest Framework
For my current system, I am using Simple-JWT as my user authentication. And also using Django REST Framework API Key. I am satisfied with Simple-JWT for its simplicity. However, I would like to add a permission where it requires my Api-Key to be able to view the token page. As for now, if I want to get a JWT Token, I can simply go to /project/api/token/ (To get access and refresh token) OR /project/api/refresh/ (To refresh the access token) In my settings.py file, I have set the DEFAULT_AUTHENTICATION_CLASSES and DEFAULT_PERMISSION_CLASSES. From my understanding, if I put 'HasAPIKey' as the default permission classes, all pages will require the Api-Key. REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework_api_key.permissions.HasAPIKey', ), } However both /token/ and /refresh/ can still be accessed without an Api-Key. Hence, my goal is to make sure those URLs require my Api-Key. (Note: I am fully satisfied with how 'simple-jwt' provides the token. It was easy to be implemented. I simply want to add the 'HasAPIKey' permission) -
Django modelformset_factory how to save form with request.user?
how to save modelformset_factory with request.user? error: Exception Type: AttributeError Exception Value: 'list' object has no attribute 'user' def pubblica_orari(request): TimeFormSet = modelformset_factory(Time, form=TimeForm) if request.method == "POST": formset = TimeFormSet(request.POST) if formset.is_valid(): instance = formset.save(commit=False) instance.user = request.user instance.save() messages.success(request, 'Salvato con successo!', extra_tags='alert alert-success alert-dismissible fade show') return redirect('pubblica_orari') else: formset = OrariFormSet() return render(request, 'attivita/pubblica_orari.html', {'formset': formset}) -
Best practice: Face Recognition Authentication
I am working on a django project and I build a login system with the face recognition library. I am concerned about security issues the way I build this and I wanted to ask how I could optimize it. In the template, I: capture the image with the webcam and draw it on canvas. save the canvas to image and post the image-data together with the username of somebody who wants to access his account. In the backend, I: serialize the login credentials and save them to the database. encode and compare the uploaded image using the face_recognition library with another image the user has uploaded when registering. login the user But this way anyone who has an image and the username of a person could access his account. Thank you for any suggestions -
Send mail from business email in smtp django
I have a business email and I want to send messages to other users from that email which is different from Gmail. How do I setup that?