Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Passing HTML value to django view returning NoReverseMatch error
I want to pass a pk value from my html to my django view. My button: <a href="{% url 'acceptdonation' pk=donation.pk %}" >Accept</a> The problem is that I am getting an error saying NoReverseMatch at /donations/73/ Reverse for 'acceptdonation' with keyword arguments '{'pk': 73}' not found. 1 pattern(s) tried: ['acceptdonation/$'] But if I remove the part where I pass a pk into my view, the code works fine. Why is this? I want to be able to pass a pk from my HTML into my django view. My view is down bellow (Basically I am deleting the Donation by the pk) def acceptdonation(request, pk): #add pk after request deleteitem = Donation.objects.filter(id = pk) deleteitem.delete() return redirect('/dashboard/') -
How do I host my django rest framework app on plesk
I have a django rest framework application. I want to host that on Plesk Obsidian 18.0.37, os:Ubuntu 20.04.2 can anyone help me to configure the plesk panel , beside the django app? thanks in advance -
Django display HTML content in templates with CK editor
I'm working on a project using Python(3.9) and Django 3 in which I have a model for Blog posts with the content field of type RichTextUploadingField for CKeditor upload. Here's the model: From models.py: class PostModel(models.Model): title = models.CharField(max_length=120) author = models.ForeignKey(User, on_delete=models.CASCADE) content = RichTextUploadingField(blank=True, null=True, config_name='default',) slug = models.SlugField(blank=True, max_length=120) photo = models.FileField(upload_to='blog_images') created_at = models.DateTimeField(auto_now=timezone.now()) category = models.CharField(choices=CAT_CHOICES, max_length=100, blank=False, default='Default') read_time = models.IntegerField(blank=False) Now in the template, I want to display the content using the following HTML: <div class="post-rich-text w-richtext"> {{ object.content|striptags|make_list|slice:'1:'|join:'' }} </div> When I place my content from the admin panel, the content is in multiple p tags along with other HTML tags, but when It displays in the browses everything goes under without the p tag. Here's how content looks in admin: And Here's how content looks in the browser: I want to display all the tags as we placed them from the admin. What can be wrong here? -
Django sort posts by comments count
I have created two Django models namely Post and Comment. class Post(models.Model): title = models.CharField(max_length=255) post = models.TextField() class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) comment = models.TextField() I would like to show all the posts on the homepage and order them by comments count. please help to achieve it. -
Django how to get input value by it's ID (not input name)
I have an input like <div class="input-group mb-3"> <input value="0" type="number" class="form-control summand" id="id_name" name="another_name"> </div> I know that if I use request.GET.get('another_name') I will get the value of the input, but how can I get the value of the input using its id, and not the name. Is there really no such way to get the value of input by id? Following code doesn't work. if request.method == 'GET': value = request.GET.get('id_name') -
how to return the values of a django page as a global variable in a python file?
So here I would like to take values on my django page to pass them in several python functions but I can't do it ideas? here I need to take the month and the region to apply some filter and and calculation with pandas for visualization <select id="dropdown"> {% for i in list_region %} <option value="{{ i }}">{{ i }}</option> {% endfor %} </select> <select id="month"> {% for j in list_mois %} <option value="{{ j }}">{{ j }}</option> {% endfor %} </select> <input type="submit" value="Select"> the function in file.py : def visualize(region,mois): data = df.loc[( df['region'] == region )] # ... return data -
python Azure webapp linux container not starting
I am trying to deploy this application from Azure repos. https://github.com/pointerness/Check I have cloned this into my companies Azure repo. This is a simple Python Django Hello World app. I have deployed this code on my personal Azure account many times and it works. I deployed this app via vscode into Azure and it works. However when I created a pipeline, It failed. I have used the same yml as available in the git. Just changed the names as per my organization. I get the error Container XXX for site XXX has exited, failing site start Things I have tried. Reset Publish Profile Tried with and without startup commands setting environment variables The docker logs has not been of much use. Any suggestions how I can debug -
Handle multiple post request in Django (Python)
Have created one web application using Django and Python. I am passing some inputs to the pickle model and getting prediction value(on the web page) based on the input data passed to the ML model present in pickle format. I want the web to handle multiple requests parallelly using Django. i.e if multiple users are passing inputs on the web page and wanting prediction values at the same time. How to manage the above scenario. Please provide me high-level scenarios like how to handle this case. You can provide links, videos e.t.c. Django Version: 3.0.2 Python Version: 3.7 -
NGINX filter requests to lan IP
I have received several requests via NGINX that appear to be to my LAN IP 192.168.0.1 as follows: nginx.vhost.access.log: 192.227.134.73 - - [29/Jul/2021:10:33:47 +0000] "POST /GponForm/diag_Form?style/ HTTP/1.1" 400 154 "-" "curl/7.3.2" and from Django: Invalid HTTP_HOST header: '192.168.0.1:443'. You may need to add '192.168.0.1' to ALLOWED_HOSTS. My NGINX configurations as follows: upstream django_server { server 127.0.0.1:8000; } # Catch all requests with an invalid HOST header server { server_name ""; listen 80; return 301 https://backoffice.example.com$request_uri; } server { listen 80; # Redirect www to https server_name www.backoffice.example.com; modsecurity on; modsecurity_rules_file /some_directory/nginx/modsec/modsec_includes.conf; add_header Strict-Transport-Security "max-age=63072000; includeSubdomains;" always; add_header X-Frame-Options "deny" always; add_header X-XSS-Protection "1; mode=block" always; add_header X-Content-Type-Options "nosniff" always; #add_header Content-Security-Policy "script-src 'self' https://example.com https://backoffice.example.com https://fonts.gstatic.com https://code.jquery.com"; add_header Referrer-Policy "strict-origin-when-cross-origin" always; return 301 https://backoffice.example.com$request_uri; } server { listen 443 ssl http2; server_name www.backoffice.example.com backoffice.example.com; modsecurity on; modsecurity_rules_file /some_directory/nginx/modsec/modsec_includes.conf; add_header Strict-Transport-Security "max-age=63072000; includeSubdomains;" always; add_header X-Frame-Options "deny" always; add_header X-XSS-Protection "1; mode=block" always; add_header X-Content-Type-Options "nosniff" always; #add_header Content-Security-Policy "script-src 'self' https://example.com https://backoffice.example.com https://fonts.gstatic.com https://code.jquery.com"; add_header Referrer-Policy "strict-origin-when-cross-origin"; ssl_certificate /etc/ssl/nginx-ssl/backofficebundle.crt; ssl_certificate_key /etc/ssl/nginx-ssl/backoffice.key; access_log /some_directory/nginx/nginx.vhost.access.log; error_log /some_directory/nginx/nginx.vhost.error.log; location / { proxy_pass http://localhost:8000; proxy_pass_header Server; proxy_redirect off; proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Scheme $scheme; proxy_set_header REMOTE_ADDR $remote_addr; } location /media/ { … -
Django: Why wrong user is associated after login via social auth?
I am trying to implement social auth in Django. The idea is that first user has to login in Django and then can login in google or facebook to further request data. But for some reason, Django associates all social logins in "User social auths" table with admin. Vue is used on frontend, Django on backend. My views.py @api_view(('GET',)) def test_login(request): permission_classes = [IsAuthenticated, ] user = request.user print(user) #prints the right user print(user.id) return render(request, 'connectors/registration/login-popup-url.html') My urls.py path('test_login', views.test_login, name="test_login"), connectors/registration/login-popup-url.html template The url will be renderen in a new window generated by Vue function. HTML templates Vue rejects to open. {% block content %}{% url 'social:begin' 'google-oauth2' %}{% endblock %} Vue function for Google login testLogin: function() { var that = this; console.log(that.accessTokenJWT); //Django simplejwt token fetch('http://localhost:8000/test_login', { method: 'GET', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + that.accessTokenJWT }}) .then(function(response) { console.log(response); return response.text(); }).then( function(response) { console.log(response); console.log('http://localhost:8000' + response); window.open('http://localhost:8000' + response, "", "_blank"); //open // social auth in a new window } ); } Vue function for Django login loginDjango: function() { var that = this; fetch('http://localhost:8000/users/login', { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, body: JSON.stringify({ username: that.django.username, … -
How to render the DateField on a page in django
Hello I just started learning django and I am having problems rending the content the way I want to. Ideally I want to manage a system of tickets and have the ticket number, start-date, end-date and status appear on the page. Similar to the below format ticket #123456 2021-07-30 2021-08-05 In Progress pages.models.py from django.db import models # Create your models here. class CR(models.Model): STATUS = ( ('N','Not Started'), ('I','In Progress'), ('C','Closed'), ) cr_number = models.CharField(max_length=250) start_date = models.DateField(null=True,blank=True) end_date = models.DateField(null=True,blank=True) status = models.CharField(max_length=20,choices=STATUS) def __str__(self): return self.cr_number pages.models.py from django.shortcuts import render from .models import CR # Create your views here. def crlistview(request): crs = CR.objects.all() context = {'crs':crs} return render(request,'cr_list.html',context) pages.urls.py from django.urls import path,include from .views import crlistview urlpatterns = [ path('',crlistview,name='crlist'), ] From what I have in my views file the only thing being displayed when i view it in my web browser is only the ticket number. Any help would be appreciated. -
Related to Jenkins, Docker
I am a beginner to DevOps and I have created a new Jenkins project which should build a docker image of a Django project and pushes it to the Docker Hub, then pulls back the image from the Docker Hub and runs it . But when I performed this, getting error as "Value Error: Dependency on app with no migrations: website". And when I pulled the image directly from Docker Hub (without using Jenkins) also I am getting the same error. I understood that it is because of not performing migrations while dockerizing , Kindly help me to perform migrations task and pushes the image to hub and then pulls back and to run it -
ssl installing error nginx service. error no such file
this my nginx conf file server { listen 8001; } server { server_name my_domain; listen 443 ssl; # ssl on; ssl_certificate /ect/ssl/my_cert.crt; ssl_certificate_key /etc/ssl/my_key.key; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/ubuntu/myproject; } location / { include proxy_params; proxy_pass http://unix:/home/ubuntu/myproject/myproject.sock; } } and here is the error I am getting nginx: [emerg] cannot load certificate "/ect/ssl/my_cert.crt": BIO_new_file() failed (SSL: error:02001002:system library:fopen:No such file or directory:fopen('/ect/ssl/my_cert.crt','r') error:2006D080:BIO routines:BIO_new_file:no such file) nginx: configuration file /etc/nginx/nginx.conf test failed If I restart the service it throws the error code mentioned above. ssl folder exists for sure. I do not know where I am doing wrong. I searched for the answer but I could not find can anyone help me with this, please? -
My server is not responding, it is hanging up, did not returning anything
I have a docker image successfully built on my mac. I am running this image by typing docker run -p 8000:8000 . Django server is up and ready to accept requests. but when I request to given URL via postman I am getting an error: socket hangs up. Here is my docker file. FROM python:3.6-slim-stretch ENV PYTHONUNBUFFERED 1 WORKDIR /app COPY requirements.txt requirements.txt RUN apt-get -y update RUN apt-get install -y --fix-missing \ build-essential \ cmake \ gfortran \ git \ wget \ curl \ graphicsmagick \ libgraphicsmagick1-dev \ libatlas-base-dev \ libavcodec-dev \ libavformat-dev \ libgtk2.0-dev \ libjpeg-dev \ liblapack-dev \ libswscale-dev \ pkg-config \ python3-dev \ python3-numpy \ software-properties-common \ zip \ && apt-get clean && rm -rf /tmp/* /var/tmp/* RUN cd ~ && \ mkdir -p dlib && \ git clone -b 'v19.9' --single-branch https://github.com/davisking/dlib.git dlib/ && \ cd dlib/ && \ python3 setup.py install --yes USE_AVX_INSTRUCTIONS RUN pip3 install --default-timeout=100 future RUN pip3 install -r requirements.txt COPY . . CMD python3 manage.py makemigrations face && python3 manage.py migrate && python3 manage.py runserver The browser also responding by the server didn't send data. Please help me. -
Django REST Framework Delete Method Request receives Forbidden 403
views.py class DeviceView(viewsets.ModelViewSet): serializer_class = DevicesSerializer queryset = Devices.objects.all() permission_classes = [permissions.IsAuthenticated] Axios Request axios.delete(`api/devices/${data.id}/`, {}, { headers: {'X-CSRFToken': csrftoken } }) .then((response) => { console.log(response); }).catch((error) => { console.log(error); }); When I carry out this request on my front-end, I get a response of :"DELETE http://localhost:3000/api/devices/4/ 403 (Forbidden)". Where 4 is the ID belonging to the record I would like to delete. I am currently using Session Authentication in Django and I have passed in my CSRF Token value into the header of my request. When I use other methods like PUT and POST on forms, they work fine. But, not DELETE What am I doing wrong to receive this error? -
Is there any good way to make string from list of dictionary in python? [duplicate]
I have an idea to convert from list of dictionary to string in python. for example: d_list = [{name:"a", age:26},{name:"b", age:22},{name:"c", age:20}] str_l = "[{ 'name':'a', 'age':'26'},{'name':'b', 'age':'22'},{'name':'c', 'age':'20'}]" like this. When input list of dictionary to db table, I need it. So for this, I have done like this. str_l= "[" for user in d_list: str_l += "{" for attr in user: str += "'" + attr + "':'" + user[attr] + "'," str_l = str_l[:-1] + "}," str_l = str_l[:-1] + "]" But it is not good. So if you have any good idea, please share for me. Thank you. -
How to make a Django application send money to its users using PayPal
I have a Django app for online cockfights. Users can bet if their accounts on the site have balance. They do that by first buying a digital product "Online Sabong Cash-In" through PayPal. The money is sent to the website's PayPal business account. I believe, this kind of transaction is called user-to-website transaction, and I've made this work using django-paypal library. I've followed this tutorial for that simple transaction: https://overiq.com/django-paypal-integration-with-django-paypal/ . Now, I want to give the website the feature where users can cash-out or like withdraw their money if they want. I want to have the website-to-user transaction. How can I do that, please? I've searched on Google a lot and all I see are articles for user-to-website transaction. I've found one way but I don't know how to do it using django-paypal library:https://developer.paypal.com/docs/checkout/integration-features/pay-another-account/. -
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xbb in position 0: invalid start byte
I have a custom field below, recently upgraded from py 2.7 to 3.8. The encryption doesn't work anymore and fails with the error above. I have gone through all related posts still no solution, Any ideas? class EncryptedCharField(models.CharField): SALT_SIZE = 8 def __init__(self, *args, **kwargs): self.widget = forms.TextInput super(EncryptedCharField, self).__init__(*args, **kwargs) def get_internal_type(self): return 'TextField' def to_python(self, value): if not value: return None if isinstance(value, str): if value.startswith(PREFIX): return self.decrypt(value) else: return value else: raise ValidationError('Failed to encrypt %s.' % value) def from_db_value(self, value, expression, connection, context): return self.to_python(value) def get_db_prep_value(self, value, connection, prepared=False): return self.encrypt(value) def value_to_string(self, instance): encriptado = getattr(instance, self.name) return self.decrypt(encriptado) if encriptado else None @staticmethod def encrypt(plaintext): plaintext = str(plaintext) salt = urandom(EncryptedCharField.SALT_SIZE) #type bytes arc4 = ARC4.new(salt + settings.ENCRYPT_FIELD_KEY.encode()) plaintext = "%3d%s%s" % (len(plaintext), plaintext, b64encode(urandom(256-len(plaintext)))) return PREFIX + "%s$%s" % (b64encode(salt), b64encode(arc4.encrypt(plaintext.encode('utf-8-sig')))) @staticmethod def decrypt(ciphertext): salt, ciphertext = list(map(b64decode, ciphertext[1:].split('$'))) arc4 = ARC4.new(salt + settings.ENCRYPT_FIELD_KEY.encode()) plaintext = arc4.decrypt(ciphertext).decode('utf-8-sig') return plaintext[3:3+int(plaintext[:3].strip())] -
Reusable progress bar
I'm new in django and web applications. I'm trying to create a reusable progress bar template that will change links depending on section ID's on the current tab. index.html <section> {% include 'progress_navbar.html' %} </section> <section id="1"> <section> <section id="2"> <section> <section id="3"> <section> <section id="4"> <section> page2.html <section> {% include 'progress_navbar.html' %} </section> <section id="A"> <section> <section id="B"> <section> <section id="C"> <section> <section id="D"> <section> progress_bar.html <nav> <ul> <li> <a href="#var">1 or A</a> </li> <li> <a href="#var">2 or B</a> </li> <li> <a href="#var">3 or C</a> </li> <li> <a href="#var">4 or D</a> </li> (...) </ul> </nav> -
Why it seem that for Clour Run Default Service Account cannot be replaced?
I am currently deploying a Django application to GCP Cloud Run. I have replaced Cloud Run Default Service Account (....compute@developer.gserviceaccount.com) with a custom one. But I get an error message: AttributeError: you need a private key to sign credentials.the credentials you are currently using <class 'google.auth.compute_engine.credentials.Credentials'> just contains a token. ... This bit is confusing me: <class 'google.auth.compute_engine.credentials.Credentials'> The error reported of the context of Django Storages which I use to store files. Is this message means the service account which is used by Cloud Run is still the default one (GOOGLE_APPLICATION_CREDENTIALS is set as Compute Engine)? Why not the Custom Service Account is used as an Identity for the Cloud Run? Why Cloud Run still checking the Default one I expected I replaced it with te Custome Service Account? I am a bit new with the IAM, but if somebody could explian why it is happeing would be appriciated. -
Django Query - Instances with single count
I have the following classes: class Company(Model): name = models.CharField(max_length=250) class Group(Model): name = models.CharField(max_length=250) company = models.ForeignKey('Company', on_delete=models.CASCADE) country = CountryField(default='US') There are instances where a company can have multiple groups in a single country. I want to fetch all the company groups that are just the only ones in their respective countries. Please help. Thanks -
Is it ok to calling save method multiple times in same method for django model object?
Say, there is a method creates an model object and adds values to model objects fields. def main_method(): obj, created = ModelA.objects.get_or_create(a="asd", b=1) Some imported data will be append to relevant fields: obj.c = "qwe" obj.d = 2 ... sub_method_1(obj) sub_method_2(obj) Also, there are 2 or more sub methods creates new model objects and link to primary object as foreign key. def sub_method_1(obj): obj_new, created = ModelB.objects.get_or_create(...) obj.e = new_obj obj.save() def sub_method_2(obj): obj_new, created = ModelC.objects.get_or_create(...) obj.f = new_obj obj.save() But than, when sub methods are done and return back to main method, there are also several save method calls available. def main_method(): .... obj.g = "ert" obj.h = 3 obj.save() Is this approach OK in practice, or there should be only one save at the end of the main method with returning new objects from sub methods and assign objects to foreign key fields before saving the main object? -
requests.get() returns an invalid JSON
I am using Django's rest_framework to create a simple API to be called from the front end. This API is supposed to be getting JSON data from openapi.etsy.com, and I am using 'requests' to achieve that. @api_view() @permission_classes((IsAuthenticated, )) def getListings(request): data = request.query_params if data.get('shopCode') == 'etsy': url = 'https://openapi.etsy.com/v2/listings/active' params = dict( keywords=data.get('keywords'), limit=data.get('pageSize'), page=data.get('page'), includes='Images:1', api_key='placeholderApiKey', ) response = requests.get(url=url, params=params) return Response(response) When I try this either by using Postman or from the browser by going to https://openapi.etsy.com/v2/listings/active?keywords=placeholder&limit=placeholder&page=placeholder&includes=Images:1&api_key=placeholder, it simply returns exactly what it's supposed to return: a valid JSON with all the data I need. But the Python function above does not. Instead, it returns something like this: ["{\"count\":45929,\"results\":[{\"listing_id\":979511780,\"state\":\"active\",\"user_id\":68094968,\"category_id\":null,\"title\":\"Pers... I'm not sure what exactly it is, it seems like an array containing a single string that contains the entire JSON but where every double quote has been escaped. Either way, it is definitely not a valid JSON. Reading the docs, it seems like I should be able to get exactly what the API returns by returning Response(response.text), but instead it just returns the thing above but without being inside an array. I thought to try Response(response.json()) as well, even though I'm not 100% sure how … -
Python Django Post Detail Class Based View
I am trying to create a DetailView for my Django blog, I have created one using function based views but to keep my code consistent I want to translate it to a class based view. The main issue I am having is that I am trying to integrate a comment form on the same page and I am unsure how I can do this in a class based view I will attach my code below # views.py @login_required def post_detail(request, slug): template_name = "cubs/post_detail.html" post = get_object_or_404(Post, slug=slug) articles = Article.objects.filter(status=1).order_by('-date_posted')[:2] comments = post.cubs_blog_comments.filter(active=True).order_by('-date_posted') new_comment = None # Comment posted if request.method == "POST": comment_form = CommentForm(data=request.POST) if comment_form.is_valid(): # Create Comment object but don't save to database yet new_comment = comment_form.save(commit=False) # Assign the current post to the comment new_comment.post = post # Save the comment to the database new_comment.save() else: comment_form = CommentForm() return render( request, template_name, { "post": post, "articles": articles, "comments": comments, "new_comment": new_comment, "comment_form": comment_form, "title": 'Post Details', }, ) # models.py class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='cubs_blog_comments') name = models.CharField(max_length=80) email = models.EmailField() comment = models.TextField() date_posted = models.DateTimeField(default=timezone.now) active = models.BooleanField(default=False) class Meta: ordering = ['date_posted'] def get_absolute_url(self): return reverse("cubs_blog_post_detail", kwargs={"slug": str(self.slug)}) … -
How to auto-reload django admin page when some async jobs are making changes in the database?
In my django application, there are multiple async tasks running in the background and when those tasks make some db changes then I'm reloading the admin page manually to see the changes on the gui. How can I automate this feature to make the django admin page live? P.S.- I tried django-livereload-server but that will auto reload when any changes are made in the code. It doesn't take background tasks into consideration.