Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Save Duplicate Data when refresh the browser
Basically, I am writing a Django application where I am calling third-party free API. After fetch the data from API, I am trying to save the data into Django Model. I am created a model for storing API data. After saving data in Django SQLITE DB, when I refresh the browser, exact same data again save in the SQLITE database table. How can i prevent this issue? One logic in my mind: if data is exist then no need to insert otherwise insert but i can't apply this logic in Django view because don't know how? Models.py from django.db import models # Create your models here. class DogFacts(models.Model): fact = models.CharField(max_length=100) def __str__(self): return self.fact views.py def api(request): url = 'https://dog-facts-api.herokuapp.com/api/v1/resources/dogs/all' response = requests.get(url) json_response = response.json() # save all dog facts in the db for i in json_response: dog_facts = DogFacts(fact= i.get("fact")) dog_facts.save() return redirect('api') Thanks. -
How to implement a public chat app using Flutter with Django backend?
I'm trying to implement a chat app in Flutter with Django database. I'm quite new to this and this would be my first project of the kind. I found out that using a RESTapi would not be a good option for this specific use case but I'm still confused on how to implement this. I read it could be done through websockets or XMPP but I'm not really sure on how to go about the entire process and especially unsure about how could I connect that to my Flutter frontend. Any help/resources/advice is appreciated. Thanks! -
Why Django rest framework is restful?
I'm now writing my engineering thesis about REST and REST APIs, mostly focusing on Django REST framework as it was the framework we used in our engineering project. I just finished writing about the guidelines for API to be RESTful stated by Roy Fielding and I wanted to start section with implementations of REST architecture in Django REST Framework, but then I realized I don't really know why this framework is RESTful. I know what main paradigms are for API to be RESTful, but I don't know what specific parts of framwork inplements for example that our service is stateless or layered. Maybe someone can pinpoint what parts of django rest framework corresponds to specified guidelines for service to be RESTful ? If It's wrong site to ask this type of question then I'm sorry, but any help would be greatly appreciated. -
Django CSRF "Referer Malformed"... but it isn't
I'm trying to test a deployment config for a Django setup that works fine in development mode. I have name-based routing via Nginx's ssl_preread module on a load balancer, and SSL terminates at another Nginx instance on the server itself where the requests are proxied to uwsgi by socket. server { server_name dev.domain.net; listen 80 proxy_protocol; listen [::]:80 proxy_protocol; location / { return 301 https://$host$request_uri; } } server { server_name dev.domain.net; listen 443 ssl http2 proxy_protocol; listen [::]:443 ssl http2 proxy_protocol; location / { include uwsgi_params; uwsgi_pass unix:/run/uwsgi/website.sock; } location /favicon.ico { access_log off; log_not_found off; } } I have uwsgi set to log %(host) and %(referer), they match in the logs. In my uwsgi_params I'm passing $host and $referer like so, since I'm using name-based routing I pick up the $server_name variable that triggered the Nginx response... uwsgi_param HTTP_REFERER $server_name; uwsgi_param HTTP_HOST $host; Adding (or taking away) protocols and ports to these makes no difference. Taking them away predictably generates a Django ALLOWED_HOSTS debug error. I've confirmed that my ALLOWED_HOSTS includes the $host. I've tried adding CSRF_TRUSTED_ORIGINS for the same $host variable. I've tried setting CSRF_COOKIE_DOMAIN for the same $host variable. I have CSRF_COOKIE_SECURE set to True per the … -
how to pass chunk of audio files to Mozilla DeepSpeech web socket?
when a live speech is going on, I want to separate it into a chunk of short mp3 files and send it to a Mozilla DeepSpeech WebSocket for transcribing (speech is conducted using the device microphone) -
how can i add group in model django
i had created a group name "company" with some permissions. i want to add group while creating model. models.py class ComapnyUser(auth.models.User,auth.models.PermissionsMixin): myshowroom=models.CharField(max_length=20,default='') slug=models.SlugField(allow_unicode=True,unique=True,null=True) contact=models.IntegerField() address=models.TextField(blank=False,default='') def save(self,*args,**kwargs): self.slug=slugify(self.username) super().save(*args,**kwargs) def __str__(self): return self.username -
Django Reverse for 'index' not found. 'index' is not a valid view function or pattern name
I've been having this error for hours and I can't seem to fix it! URL.PY: from django.urls import path from . import views app_name = "learning_logg" urlpatterns = [ #Home Page path('', views.index, name="index"), ] VIEWS.PY: from django.shortcuts import render # Create your views here. def index(request): return render(request, "index.html") INDEX.HTML: {% extends "learning_logs/base.html" %} {% block content %} <p> Learning Log </p> <p> Learning Log helps you keep track of your learning, for any topic you're learning about gay </p> {% endblock content %} BASE.HTML: <p> <a> href = "{% url "index" %}"> Learning Log</a> </p> {% block content%} {% endblock content %} I'm trying to make base.html the main framework and then putting index.html inside it, does anyone know how to fix the error? It says the error is in line 2: 1 2 href = "{% url "index" %}"> Learning Log 3 4 5 6 {% block content%} {% endblock content %} 7 -
Get the src attribute of an <img> element from html template to work with it in django view
I need to get the src attribute of an element from the html template to my django view Any idea how to do it guys ? -
(Django REST Framework) Basic authentication doesn't work when app is served through NGINX
I'm building an API and I finally got it working to serve it through Gunicorn and NGINX. Nginx proxies incoming requests to a socket binded to Gunicorn. The problem is this: When I try to access the API directly by running the 'gunicorn command or by using the builtin 'runserver' command from Django, and having configured Django REST Framework's BasicAuthentication as the default authentication class in the settings.py-file, everything works fine. Each time I try to access an endpoint, it asks me for a valid username/password-combo, just like you would expect. However, when I try to access the API through NGINX, which has a proxy_pass configured to the unix socket which Gunicorn is bound to, BasicAuthentication doesn't work anymore. All requests are granted, without providing a username and password. I know basic authentication should be avoided, but it's a requirement for a project I'm working on. Does anyone know why this happens and how to solve this? settings.py: REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.BasicAuthentication', ), } nginx.conf: http { log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; access_log /var/log/nginx/access.log main; sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 2048; include /etc/nginx/mime.types; default_type application/octet-stream; … -
Django How to use filter when the column database has strings and foreign key?
I have class named Person, and Person have a attribute named car. In the past car was an string attribute. Now, my desire is to change car to a FK, since I've create a class named Car. I addition, I have the following filter: class PersonFilterHeatmapSet(filters.FilterSet): class Meta: model = Person fields = { 'car': ['exact'], } how can I make these changes without broken my filter? Since currently my column database is populated with string values instead FK's. -
Python Regex in URL Django
I want a function which should run with or without a parameter. This is my views.py @api_view(['GET', 'POST']) def enable_boards(request, board_ids=None): ``` This is my urls.py path('enable_boards', views.enable_boards) path('enable_boards/<str:boards_ids>', views.enable_boards) Now I know I have to write re_path but I don't know how to write regex for this particular case. What should be the proper url in this case ? -
Read csv file and save content to database using Graphql and Django framework
I am trying to use bulk import, to import data from a csv file and populate an inherited model from a separate module, I was able to get the data and loop through all the data in the csv file by checking for the csv file path reading the datas from the file and looping through each rows, now I am trying to insert the gotten data to the database using graphql and Django framework, I need the data to populate an inherited module model table called insuree, using the below code, i am unable to send the data to database which is stopping the table from populating. Here is my mutation code ''' import graphene from core import prefix_filterset, ExtendedConnection, filter_validity, Q, assert_string_length from core.schema import TinyInt, SmallInt, OpenIMISMutation, OrderedDjangoFilterConnectionField from insuree import models as insuree_models from django.contrib.auth.models import AnonymousUser from django.core.exceptions import ValidationError, PermissionDenied from django.utils.translation import gettext as _ from graphene import InputObjectType import csv class BulkImportInputType(OpenIMISMutation.Input): file_path =graphene.String(required=True) def set_import_insuree_data(data, user): data_list = [] col_list = [] all_data = [] file_path = data['file_path'] with open(file_path, newline='') as csvfile: data = csv.reader(csvfile, delimiter=' ', quotechar='|') for row in data: data_list.append(row) for col in data_list[0]: for column in … -
nginx ingress host app to master ip not working
Attaching the desctiption below. I need to host the app in 192.168.5.91 which is the master ip of the kubetnet cluster. All these are running in private space. It can be accesed throgh localhost:30239. But i need to acces it via 192.168.5.51 (master.example.com) -added in /etc/hosts $kubectl describe service -n ingress-nginx ingress-nginx Name: ingress-nginx-controller Namespace: ingress-nginx Labels: app.kubernetes.io/component=controller app.kubernetes.io/instance=ingress-nginx app.kubernetes.io/managed-by=Helm app.kubernetes.io/name=ingress-nginx app.kubernetes.io/version=0.46.0 helm.sh/chart=ingress-nginx-3.30.0 Annotations: service.beta.kubernetes.io/do-loadbalancer-enable-proxy-protocol: true service.beta.kubernetes.io/do-loadbalancer-hostname: master-kmrl.example.com Selector: app.kubernetes.io/component=controller,app.kubernetes.io/instance=ingress-nginx,app.kubernetes.io/name=metrodash-ingress Type: ClusterIP IP Family Policy: SingleStack IP Families: IPv4 IP: 10.98.115.20 IPs: 10.98.115.20 External IPs: 192.168.9.51 Port: http 80/TCP TargetPort: http/TCP Endpoints: <none> Port: https 443/TCP TargetPort: https/TCP Endpoints: <none> Session Affinity: None Events: <none> Name: ingress-nginx-controller-admission Namespace: ingress-nginx Labels: app.kubernetes.io/component=controller app.kubernetes.io/instance=ingress-nginx app.kubernetes.io/managed-by=Helm app.kubernetes.io/name=ingress-nginx app.kubernetes.io/version=0.46.0 helm.sh/chart=ingress-nginx-3.30.0 Annotations: <none> Selector: app.kubernetes.io/component=controller,app.kubernetes.io/instance=ingress-nginx,app.kubernetes.io/name=ingress-nginx Type: ClusterIP IP Family Policy: SingleStack IP Families: IPv4 IP: 10.101.116.78 IPs: 10.101.116.78 Port: https-webhook 443/TCP TargetPort: webhook/TCP Endpoints: 192.168.79.191:8443 Session Affinity: None Events: <none> The service files attached here $kubectl get service --all-namespaces NAMESPACE NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE cert-manager cert-manager ClusterIP 10.97.7.155 <none> 9402/TCP 2d1h cert-manager cert-manager-webhook ClusterIP 10.102.27.254 <none> 443/TCP 2d1h default kubernetes ClusterIP 10.96.0.1 <none> 443/TCP 10d ingress-nginx ingress-nginx-controller LoadBalancer 10.104.163.193 192.168.9.51 80:31152/TCP,443:31291/TCP 7m24s ingress-nginx ingress-nginx-controller-admission ClusterIP 10.101.116.78 <none> 443/TCP 8d ingress-nginx metrodash-service NodePort 10.107.176.33 … -
Celery PID file command errors
I use Django Celery Beats in my system and I just updated the celery to version 5. I had initially used this command to start the service: celery --pidfile= -A ExactEstate beat -l info --scheduler django_celery_beat.schedulers:DatabaseScheduler But now I am getting errors that --pidfile is not a valid arg. What can I change it to now? -
Nginx add subdirectory to proxy_pass respnse?
I am having an issue with my Nginx configuration and I could use a little help since I feel I am so close. I am trying to configure Nginx to host multiple applications and routing the traffic based on an applications subdirectory as shown here. server { listen 80; location /something / { proxy_set_header Host $host; rewrite /something/(.*)$ /$1 break; proxy_pass http://django_application_upstream1; } location /another_something/ / { proxy_set_header Host $host; rewrite /another_something /(.*)$ /$1 break; proxy_pass http://django_application_upstream2; } } This set up works great for directing traffic to the respective applications but when a user clicks on a href with an absolute URL everything goes wrong. For example: http://django_application_upstream1/something/ -> Landing page (perfect) user clicks landing page href=’/’ -> 404 not found (should return user to http://django_application_upstream1/something/) Even when I add the subdirectory to the href (‘/something/’) within the application html the subdirectory is removed somewhere along the way and I still end back up at the root url. Is it possible to rewrite a proxy_pass response so I can add back the subdirectory that I removed with the previous rewrite? This would mean all responses from the proxy have the subdirectory added back even if an absolute href was … -
Django is not returning Language Model in forms
I am working on Django Tutorial by MDN on local library I got no error returned in admin site for Language Model, where I have to select language for books. But there is error reflected by Language model on user site while rendering books detail. Error: Language: catalog.Language.none Code and model details are as follows models.py for class Language class Language(models.Model): name = models.CharField(max_length=200, help_text='Enter a book language(e.g. English)') def __str__(self): return self.name models.py for class Book class Book(models.Model): """Model representing a book (but not a specific copy of a book).""" title = models.CharField(max_length=200) author = models.ForeignKey('Author', on_delete=models.SET_NULL, null=True) summary = models.TextField( max_length=1000, help_text='Enter a brief description of the book') isbn = models.CharField('ISBN', max_length=13, unique=True, help_text='13 Character <a href="https://www.isbn-international.org/content/what-isbn">ISBN number</a>') genre = models.ManyToManyField( Genre, help_text='Select a genre for this book') language = models.ManyToManyField( Language, help_text='Select Language for this book') def get_language(self): return ', '.join(language.name for language in self.language.all()) get_language.short_description = 'Language' class Meta: ordering = ['title', 'author'] def __str__(self): return self.title def get_absolute_url(self): return reverse('book-detail', kwargs= {'pk': str(self.id)}) def display_genre(self): return ', '.join(genre.name for genre in self.genre.all()[:3]) display_genre.short_description = 'Genre' Book List View Model class BookListView(ListView): model = Book Book Detail View Model class BookDetailView(DetailView): model = Book HTML for … -
How many model fields are too much in a single model django
well I have a doubt, in general you will have many models in a models.py , and that model would have many fields under it(Charfield, foreign key etc...) How many model object are too much in a single model file, for eg if I have 50 model object is it too much? Pls comment your thought on limit for the model object and what's the solution.... -
Django: Handeling data without models
Is there a way to manage data in Django without models? I want to make an app 'Settings' where I can make "global" settings for the webapp. (e.g. Upload a new logo or defining text) But since there would only be one "entry", a model would be excessive. I need to be able to access the data via the REST framework in order to use it in my React frontend. -
I wanted to do a post request with django using ajax
I want to make a request with the method post using ajax. But my django server returns a Forbidden error (CSRF token missing or incorrect.): / Post / it asks me for the csrf token here is my code: -
How to optimize call to database with OneToOneField?
According to the documentation, to optimize the db access : If you only need a foreign key value, use the foreign key value that is already on the object you’ve got, rather than getting the whole related object and taking its primary key. i.e. do: entry.blog_id No problem to use with a ForeignKey and it works as intended. But if I want to do the same with OneToOneField, it is not working : Class CustomUser(Model): ... class Profile(Model): user = models.OneToOneField( CustomUser, on_delete=models.CASCADE, ) Then, if I try to use the same tip as described in the documentation, in a view for example : request.user.profile_id I got the followig error : AttributeError: 'CustomUser' object has no attribute 'profile_id' Of course, it works with request.user.profile.uid but it is not the point here because there is an additional query to the DB. Is it intended ? Is it a con to using OneToOneField ? -
How to validate a paypal webhook json response?
I am integrating paypal subscriptions in a Django project with the webhook method. I got it working well but I'm thinking that is possible that someone malicious can simulate a webhook call and get a free subscription. Currently I have no way to verify if the webhook really comes from Paypal. In other payment with similarities I could set a secret word in the call(from the service provider) and then in the app server validate the call through the secret word. I analysed multiple paypal subscriptions json responses and there seems to be no reference to validate the veracity of the webhook. Anyone experienced on this one? Thanks -
Django LogoutView doesn't logout but redirects to login page
I am new to Django. I have this problem that The auth LoginView works perfectly well but the LogoutView doesnt. It only redirects to login page. from django.contrib.auth import views as auth_views path('user/login/', auth_views.LoginView.as_view(template_name='login.html'), name='login'), path('user/logout/', auth_views.LogoutView.as_view(template_name='logout.html'), name='logout'), Please does anyone know why this could be happening. Is it possible that the default auth LoginView could be working and the default auth Logoutview is not working. Or am I doing something wrong?. Thank you for your answers. -
Group base permission rest api in Django
i am using Django rest framework for my login api. Now i want to login only certain group user through api. I have created group and assigned user to the group.I have created a permission class and used to APIView but it's show ""Authentication credentials were not provided." Here is my permissions.py class from rest_framework.permissions import BasePermission class FanOnlyPermission(BasePermission): def has_permission(self, request, view): if request.user and request.user.groups.filter(name='fan'): return True return False Here is my view.py from rest_framework import views, permissions, status, generics class UserLoginApiView(generics.GenericAPIView): """ User Login Api View """ permission_classes = (FanOnlyPermission, ) def post(self, request): """ Handle POST request :param request: :return: """ serializer = UserLoginSerializer(data=request.data) if serializer.is_valid(raise_exception=True): return Response(serializer.data, status=status.HTTP_200_OK) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) I have tried through postman. when i print request.user from permission.py it shoed "Anonymous user". -
How to display an array of data in python
I am trying to display the data of this array in django: [('abdo', 'daou', 'charbel', 'hankach', datetime.date(2021, 5, 19), 40000, 30000, 10000),('abdo', 'daou', 'charbel', 'hankach', datetime.date(2021, 5, 19), 40000, 30000, 10000)] This array is given by this python code: def getConsultations(request): con=mysql.connector.connect(host="localhost",user="root",password="",database="djangohospital") mycursor=con.cursor() mycursor.execute(some query) res=mycursor.fetchall() print(res) return render(request,'consultations.html',{'consultations':res}) The sql query is: select ( select firstname from hospitalmanagementwebsite_doctors where hospitalmanagementwebsite_doctors.id = hospitalmanagementwebsite_consultations.doctor_id_id ) as doctor_firstname, ( select lastname from hospitalmanagementwebsite_doctors where hospitalmanagementwebsite_doctors.id = hospitalmanagementwebsite_consultations.doctor_id_id ) as doctor_lastname, ( select firstname from hospitalmanagementwebsite_patients where hospitalmanagementwebsite_patients.id = hospitalmanagementwebsite_consultations.patient_id_id ) as patient_firstname, ( select lastname from hospitalmanagementwebsite_patients where hospitalmanagementwebsite_patients.id = hospitalmanagementwebsite_consultations.patient_id_id ) as patient_lastname, consultation_date, total, paid, leftt from hospitalmanagementwebsite_consultations I want to display these data in html,and i am trying it like this: {% for cons in consultations %} <tr> <td>{{cons[0]}} {{cons[1]}}</td> <td>{{cons[2]}} {{cons[3]}}</td> <td>{{cons[4]}}</td> <td>{{cons[5]}}</td> <td>{{cons[6]}}</td> <td> <a href="/editdoctor/{{doctor.id}}"><span class="btn btn-success">Edit</span></a> <a href="/deletedoctor/{{doctor.id}}" class="btn btn-danger">Delete</a> </td> </tr> {% endfor %} but it is giving me this error: Could not parse the remainder: '[0]' from 'cons[0]' -
When saving PDF via PyPDF2 it's making hidden layers visible
while saving via PDFFileWriter() of PyPDF2 the output file has all previously hidden layers visible. Is there a possibility to delete them from file or at least still hide them? with open(self.file.path,"rb") as f: inputpdf = PdfFileReader(f) output = PdfFileWriter() output.addPage(inputpdf.getPage(pagenumber)) output.write(outputStream) Otherwise, is there another library which supports hidden layers? best regards