Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Calling a function from another html template
So I have a base.html template and a review_result.html template that extends the base.html template. The base.html template has a script tag with lots of function. I am going to move a function called format from a script tag in the review_result.html to the base.html file. How do I then call the format function in review_result.html from base.html? -
Creating Django application inside of the project directory hierarchy?
In django rest framework quick start it creates the application inside of parent project directory instead of the top-level hierarchy for the sake of preventing conflicts with other packages. I'm asking is there any other benefit to this approach or on the other hand it will add overhead to the performance because of extra nesting? -
How to create users using Faker in Django Rest Framework
I am trying to create a fake user using faker and although the user instance is created I can't log in with its credentials. This is what my faker command looks like: from django.core.management.base import BaseCommand from faker import Faker from users.models import NewUser import random class Command(BaseCommand): help = "Command Information" def handle(self, *args, **kwargs): fake = Faker(["tl_PH"]) fname = fake.unique.first_name() lname = fake.unique.last_name() uname = "%s%s%d" % (fname.lower(), lname.lower(), random.randint(1000, 9999)) email = fake.unique.ascii_safe_email() password = "QaxSf96H" about = fake.sentence() newuser = NewUser.objects.create_user( first_name=fname, last_name=lname, username=uname, email=email, password=password, about=about ) newuser.save() -
Django - Error: NoReverseMatch at /post/.../ . Reverse for 'post_remove' not found
I'm working on my project "my-first-blog" and I'm totally stuck right now. I'm creating a blog with information about me for my portfolio. I've followed the Django tutorial and checked the code a hundred times but obviously there is something I'm missing. I'm creaing Delete Post. I'm getting an error when click on Title one of the blog: "Reverse for 'post_remove' not found. 'post_remove' is not a valid view function or pattern name." Can anybody see what I'm missing? Here you can see the full code https://github.com/valeriamilshtein/my-first-blog post_remove.html {% extends 'blog/base.html' %} {% block content %} <h1>Delete Post</h1> <form method="POST" class="post-form">{% csrf_token %} {{ form.as_p }} <button class="btn btn-secondary">Delete</button> </form> {% endblock %} post_detail.html {% extends 'blog/base.html' %} {% block content %} <div class="post"> {% if post.published_date %} <div class="date"> {{ post.published_date }} </div> {% endif %} <a class="btn btn-default" href="{% url 'post_edit' pk=post.pk %}"><span class="glyphicon glyphicon-pencil"></span></a> <a class="btn btn-default" href="{% url 'post_remove' pk=post.pk %}"><span class="glyphicon glyphicon-remove"></span></a> <h1>{{ post.title }}</h1> <p>{{ post.text|linebreaks }}</p> </div> {% endblock %} urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.post_list, name='post_list'), url(r'^post/(?P<pk>[0-9]+)/$', views.post_detail, name='post_detail'), url(r'^post/new/$', views.post_new, name='post_new'), url(r'^post/(?P<pk>[0-9]+)/edit/$', views.post_edit, name='post_edit'), url(r'^post/(?P<pk>[0-9]+)/remove/$', views.post_remove, name='post_remove'), ] views.py from django.shortcuts import render … -
django custome aggregate function in MySQL
Trying to create custom aggregate function to calculate median price in my tables, my code look like this: from django.db.models import Aggregate, FloatField class Median(Aggregate): function = "percentile_cont" output_field = FloatField() template = "%(function)s(%(expressions)s)" but if i run this in my query i get 1305, 'FUNCTION DATABASE.percentile_cont does not exist') Some one can help me with this? I use MySQL server, not mariadb -
How do I use retrieve database data using a Django GET Form?
I am having a bit of trouble understanding how forms work in Django. I would like to retrieve information from my database and display it in a dropdown menu. When the user selects one of the items and submits their choice, the following page should display the contents of that item. In my example I have 'Workouts' that contain 'Exercises'. After selecting a Workout, the Exercises of that Workout should be displayed. The error I am receiving is this: NoReverseMatch at /routines/ Reverse for 'routine' with arguments '('',)' not found. 1 pattern(s) tried: ['routines/(?P<workout_id>[0-9]+)/$'] And here is where I believe the issue lays: routines.html <form action="{% url 'routine_workouts_app:routine' workout.id %}" method="get"> {% csrf_token %} {{ form.as_p }} <button name="submit">Make Workout</button> </form> I am having an issue with the action of the form. The error says that it can't find the routine.html template (which I have double checked and it is spelt correct and exists). I think this is because whatever I'm doing with 'workout.id' is incorrect but I don't know why. Below, I will show the corresponding url and view. If more information, such as the form.py file, is needed I will provide. views.py def routines(request): #as it is, there … -
How to see the common runserver log from django in heroku?
I am running a Django app on Heroku, and I am getting an error that I am not getting on my local machine. I am getting a 500 error. Normally, I just see the log Django outputs on the CMD, but I can't see it in Heroku. How can I do this? BTW, it is not a dependency cause I just pip freeze > requirements.txt. Thanks! -
compress with pyminizip and return to response
I am trying to compress data with pyminizip and return the data as response in a Django project as follows def get_csv_file(request): response = HttpResponse(content_type='application/zip') response['Content-Disposition'] = 'attachment; filename="member.zip"' users = User.objects.all() file_path = os.path.join(tempfile.gettempdir(), 'member.csv') f = open(file_path, 'w') file_writer = csv.writer(f, quotechar='"', quoting=csv.QUOTE_MINIMAL) for user in users: file_writer.writerow([user.username, user.email]) f.close() pyminizip.compress(file_path, "members", response, "pass", int(1)) return response getting this error ValueError at /get_csv_file/ expected arguments are compress(srcfile, prefix, zipfile, password, compress_level) -
Problem passing dictionary to API via requests.post()
As noted below, I am trying to pass the dictionary data to the API. def create_flow_and_phases(request): data = { "name": "name_example", "description":"description_example", "category": 2, "precedents": [2,3], "users": [1], "phases": [{ "name": "phase_name", "description": "description name", "sequence_number": 1, "precedents": [1] }] } # Making a POST request to save flow_and_phases url = API_HOST + "/api/flows/save_flow_and_phases/" answer = requests.post(url, data=data, headers={'Authorization': 'Token ' + request.session['user_token']}) if not answer.ok: raise Exception("An error occurred while creating flow.") Below, you can see that the dictionary data format is the same one passed in Insomnia to the API and that it works perfectly. { "name": "Testando criação de fluxo pelo Insomnia", "description": "Fluxo teste simulando informações de trato e colheita de café na fazendo fictícia Quipo", "category": 2, "precedents": [2, 3], "users": [1], "phases": [ { "name": "Trato anual", "description": "Descrição teste fase 1.", "sequence_number": 1, "precedents": [] }, { "name": "Trato anual 2", "description": "Descrição teste fase 2.", "sequence_number": 2, "precedents": [1] } ] } The backend receives data as below flow_data = dict(data) # data is passed as parameter But when I go to run the debub, the data referring to phases are not passed to the API as shown in the screenshot below … -
Nginx is not passing Authentication to gunicorn socket
So I've basically set up my basic backend. Locally the api runs like butter but whenever I deploy the application to production, the API responds always with: "detail": "Authentication credentials were not provided." I think nginx is not passing the header correctly to my socket running gunicorn. But I don't know how I would pass the Header to the socket. The Authorization is a basic JWT Token, so: AUthorization: Bearer bla-blubb-i-am-a-token-420-69 This is my nginx setup: server { listen 80; server_name dev.website.com; location = /favicon.ico { access_log off; log_not_found off; } location /static { alias /home/ubuntu/platform/backend/static; } auth_basic "Admin Login"; auth_basic_user_file /etc/nginx/.htpasswd; location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } What am I missing? -
How to.limit a users conten upload in django
Hello guys I want to restrict user, my I am working on a project in django where I have a producer model so I want to restrict the producer from uploading contents based on the particular package they're currently running on... Let's say if they subscribe to a pro package they can't upload more that 5 contents.. -
How to make a table only visible to a specific user in Django
So, I was studying Django and started doing some projects to fixate what I learned. I'm building a contact book like website and want to make each user have a unique Contacts table. I've tried putting this on models.py: class UserContatos(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) class Contato(models.Model): nome = models.CharField(max_length=255) sobrenome = models.CharField(max_length=255, blank=True) telefone = models.CharField(max_length=255) email = models.CharField(max_length=255, blank=True) data_criacao = models.DateTimeField( default=timezone.now) descricao = models.TextField(blank=True) categoria = models.ForeignKey(Categoria, on_delete=models.DO_NOTHING) mostrar = models.BooleanField(default=True) foto = models.ImageField(blank=True, upload_to='fotos/%y/%m/%d') def __str__(self): return self.nome contatos = Contato() class ContatoForm(forms.ModelForm): class Meta: model = UserContatos.Contato exclude = ('',) When I use this form to create a contact, it doesn't "go to the user". -
Export MUI components or style to use outside of React app
I'm facing a use case I'm not familiar with. I'm currently using MUI for a React application, but the authentication part is handled on another server, a Django application that includes Django OIDC Provider lib and which mostly consists in a sign in form that redirects the user to the React client upon sign in. The ultimate goal would be to have the same look and feel across both applications to provide a better user experience, I'm wondering what is the best solution for this: embed a full React application into the Django project and share the MUI theme across both application, seems to be the best choice for consistency but will be costly in term of development time and bundle size of the authentication app (basically loading React + MUI just for one page) trying to mimic the MUI components (mostly text fields, checkbox, buttons) with a pure CSS solution like https://github.com/finnhvman/matter which looks very nice, but it will take time to reproduce the main React app MUI theme, it will be harder to maintain and it will be hard to provide the exact same interactivity somehow find a way to export pure CSS with MUI theme style or … -
Django - Storing total API request from user, Limit and Filter it [Django Ninja]
I'm new to django, i'm currently working with API using Django Ninja Rest Framework. in this example, users will have a unique APIKey each time i create new APIKey from this model and attach it to selected user. this is my APIKey model : ### NOTE - This is just for testing, Not a real model, see the link below class APIKey(models.Model): key = models.CharField(max_length=64) # i know this should be unique, just for demo :) user = models.ForeignKey(get_user_model(), related_name='free_key', on_delete=models.CASCADE) label = models.CharField(max_length=40) revoked = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) expires_at = models.DateTimeField(null=True, blank=True) This model is just for testing purposes, I actually use this for my project and modify it. So, My API endpoints need an API key for authentication (the API key that i have created that correspond to a specific user), so i implement and follow the steps here and it works normally My questions are : Each user has a unique API key. How to count and store the total request from a user each time user makes a request to an endpoint ? Should i add request_total field to my APIKey model or create a new Model ? Should i use custom middleware? or should … -
Django + nginx (with docker): erratic /admin redirects
So, I have a project that features a Docker deployment of a website with Nginx, Django served with Gunicorn + static files, and a Vue.js frontend (compiles to static files). The problem: When I try to access Django's admin interface, at http://localhost:8100/admin, I am redirected to https://localhost/admin/, which obviously fails. What I really want: First, for this to work. But I don't want to hardcode a website name (because it's an open source project), I don't want to force SSL, because I have a server where I'm going to deploy this behind another reverse proxy so that the website will be some subdomain on my server, under my certificates. So I want for both the Nginx and the Django layer to be as "dumb" as possible. To help debugging: docker-compose.yaml: version: "3" services: reverse-proxy: image: nginx:stable ports: - 8100:80 volumes: - frontend_data:/frontend/ - backend_data:/backend/ - ./nginx:/etc/nginx/conf.d depends_on: - backend frontend: # .... backend: build: context: ./backend dockerfile: Dockerfile entrypoint: ./entrypoint.sh stop_signal: SIGINT depends_on: - db volumes: - backend_data:/backend/ db: image: postgres:13-bullseye volumes: - postgres_data:/var/lib/postgresql/data/ volumes: # ... Nginx's config: upstream backend_server { server backend:8000; } server { listen 80; location /api { proxy_pass http://backend_server/api; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; … -
AssertionError: Cannot apply DjangoModelPermissionsOrAnonReadOnly
I have a problem with (I think) permissions. When I try to send post request via postman, I get following error: AssertionError: Cannot apply DjangoModelPermissionsOrAnonReadOnly on a view that does not set .queryset or have a .get_queryset() method. [29/Nov/2021 20:21:21] "POST /api/blog/category HTTP/1.1" 500 101581 Here are my views.py and category class. Also, I noticed that for some reason in def post(self, request, format=None) request is not being called ("request" is not accessed Pylance). I think the problem is somewhere here, but can't figure it out. Thank you in advance. class BlogPostCategoryView(APIView): serializer_class = BlogPostSerializer permissions_classes = (permissions.AllowAny, ) def post(self, request, format=None): data = self.request.data category = data['category'] queryset = BlogPost.objects.order_by('-date_created').filter(category__iexact=category) serializer = BlogPostSerializer(queryset, many=True) return Response(serializer.data) -
Where does a Django generic view class call the database?
I can inherit from a class based generic view from generic.ListView as in class BookListView(generic.ListView): model = Book Supposedly the .as_view() function gets called when the Django app starts up to create an instance of this view. I find the definition of get_queryset in MultipleObjectMixin but what I dont find is, from where is this method called from? -
How to send data to running django management command?
I have a custom django management command that is constantly running through the supervisor (keep alive) I need under certain circumstances (for example, a signal in the project, or a change in the database) the django management process reacted to these changes. Tried looking for something similar but can't seem to find a simple implementation. -
Data returned by view is not recognized by Chart.JS chart
I return a dictionary within my view which should be used as data input for a basic Chart.JS bar chart. However, the chart doesn't recognize the data. # .js const ctx = document.getElementById('balances-chart').getContext('2d'); const myChart = new Chart(ctx, { type: 'bar', data: balances_dict, options: { scales: { y: { beginAtZero: true } }, indexAxis: 'y', } }); # views.py ... balances_dict = {} for balance in balances: if not balance['asset_type'] == 'native': balances_dict[balance['asset_code']] = balance['balance'] context = { 'dashboard_site': dashboard_site, 'user': user, 'cashpool': cashpool, 'payments': payments, 'balances_dict': balances_dict } return render(request, 'dashboard/dashboard_overview.html', context) returns dashboard_overview.js:6 Uncaught ReferenceError: balances_dict is not defined Is there anything special to consider when using ChartJS with Django? -
DJANGO JWT - CANT LOGIN ( HTTP 401 Unauthorized ) PROBLEM
"HTTP 401 Unauthorized" I HAVE BEEN TRYING TO FIX THIS ERROR SINCE 3 DAYS My LoginAPIView class LoginAPIView(generics.GenericAPIView): serializer_class=LoginSerializer #permission_classes = (permissions.IsAuthenticated) def post(self,request): serializer=self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) return Response(serializer.data,status=status.HTTP_200_OK) and My LoginSerializer class LoginSerializer(serializers.ModelSerializer): email=serializers.EmailField( max_length=255,min_length=3)#not matter password=serializers.CharField( max_length=68,min_length=5,write_only=True) username= serializers.CharField( max_length=255, min_length=3,read_only=True) tokens = serializers.CharField( max_length=255, min_length=6, read_only=True) class Meta: model=User fields=[ "email", "password", "username", "tokens" ] def validate(self, attrs): email= attrs.get("email", "") password = attrs.get("password", "") # Kimlik doğrulama hatası verdi bunun sebebi... ################################################ user = auth.authenticate(email=email, password=password) """ debug için örneğin, kullanıcı gelip gelmediğini buradan görebilriiz. bunu yazdığımız yer debug çalıştırır. """ """ import pdb pdb.set_trace() """ if not user: raise AuthenticationFailed('Geçerli Kimlik bilgileri giriniz!') if not user.is_active: raise AuthenticationFailed('Hesabınız aktif değildir, lütfen admin ile iletişime geçiniz.!') if not user.is_verified: raise AuthenticationFailed(' E-mailiniz doğrulanmadı, lütfen sizlere göndermiş olduğumuz doğrulama baplantısını onaylanıyınız!') return { 'email':user.email, 'username':user.username, 'tokens':user.tokens, } return super().validate(attrs) So, I used """ import pdb pdb.set_trace()""" ı checked my cmd, There was a problem like that, Unauthorized: /auth/login/ [29/Nov/2021 22:13:35] "POST /auth/login/?next=/ HTTP/1.1" 401 7638 I have an account on my system, ı trying to login in my system with my exites account, but throwig that problem ı couldnt fix it, Thak u so much for ur help -
How to use inputs to do calculations with mathfilters in Django?
I am using mathfilters in Django, I want to do a multiplication between quantity and unit_price and reflect it in total_price. I already followed the documentation from here mathfilters and when implementing it as it says and filling those 2 inputs with numbers, the result is not reflected anywhere Maybe I am not implementing it well but when I search I see that there is very little information to use mathfilters <td> {{presupuestosparteform.quantity}} </td> <td> {{presupuestosparteform.unit_price}} </td> <td> <li>{{ presupuestosparteform.quantity|mul:presupuestosparteform.unit_price }}</li> </td> -
ModelChoiceField - get request.user.username
I need to choose User to form by the request.user.username and save into the database. Here I have a code of forms.py class Send(forms.ModelForm): sender = forms.ModelChoiceField(queryset=User.objects.order_by('username') Here is the models.py, where I am going to save the data about the user: class SendM(models.Model): sender = models.ForeignKey(User, null=True, blank=False, on_delete=models.CASCADE) And here is views.py, where I get the data def form_create(request): if not request.user.is_anonymous: form = Send(request.POST or None, initial={'sender': request.user.username}) if request.method == "POST": if form.is_valid(): send = SendM(sender=User.objects.get(username=form.cleaned_data['sender'])) send.save() return redirect("/") To understand I want to pre-filled the array with the user found in database. Thank you very much!! -
implementing oauth2 for google calendar api with django
Can anybody direct me to a complete example of implementing oauth2 with django? From the older posts, I found some bits and pieces, or work-arounds, but I am not yet experienced enough to put the pieces together. I want to integrate into an web app creating, updating, deleting events. Followed the quickstart in the documentation, it works fine. I need to switch to a web app flow, instead of the installed app flow, here I got stuck, on authorizing the app and on receiving the approval of the resource owners to access their calendars. Thank you for your support. -
Django send events via websocket to all clients
I want to send events (json strings) via websocket to all clients (to all who established connection via websocket). My code: I think that asgi and routing are ok asgi.py os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'base_app.settings') django.setup() application = ProtocolTypeRouter({ "http": get_asgi_application(), "websocket": AuthMiddlewareStack( URLRouter( websocket_urlpatterns ) ), }) routing.py from api_producer.consumers import EventWebSocket websocket_urlpatterns = [ url('ws/start/', EventWebSocket.as_asgi()), ] The problematic point: Some function generates events and I want to send these events to the clients from api_producer.consumers import EventWebSocket def event_producer(): my_socket = EventWebSocket() my_socket.receive("Some_text") consumers.py class EventWebSocket(WebsocketConsumer): def connect(self): self.channel_name = "CHANNEL_1" print("ZZZ_") async_to_sync(self.channel_layer.group_add)("chat", self.channel_name) def disconnect(self, close_code): async_to_sync(self.channel_layer.group_discard)("chat", self.channel_name) def receive(self, text_data): async_to_sync(self.channel_layer.group_send)( # 'EventWebSocket' object has no attribute 'channel_layer "chat", { "type": "chat.message", "text": text_data, }, ) def chat_message(self, event): self.send(text_data=event["text"]) My actions: 1 Go to websocketKing and send request ws://127.0.0.1:8000/ws/start/. Log output: WebSocket HANDSHAKING /ws/start/ [127.0.0.1:37476] WebSocket HANDSHAKING /ws/start/ [127.0.0.1:37476] ZZZ_ WebSocket DISCONNECT /ws/start/ [127.0.0.1:37476] WebSocket DISCONNECT /ws/start/ [127.0.0.1:37476] 2 Run function event_producer() I don't see any output (guess because WebSocket DISCONNECT) What is the proper way to send events? -
How can I get Django inside a docker compose network to recognize the postgres service name while using PyCharm?
I've been fiddling with my Dockerfile and Docker Compose to try and get PyCharm to be able to run and debug my django application. I've identified that I need all services to be on the same network, and have put them on the same network, but when I go to execute the runserver command through my PyCharm configuration, I get an error that django.db.utils.OperationalError: could not translate host name "postgres" to address: Name or service not known I've tried adjusting the Dockerfile to expose environment variables inside of it, instead of in the compose file. As well as grouping all the services into the same network. I'm at a bit of a loss as to where to go from here, as most other StackOverflow questions relating to this tell me to do things I've already tried. docker-compose.yml version: "2" services: redis: image: redis:latest # redis restart: always logging: driver: "none" networks: - integration postgres: image: postgres:latest restart: always ports: - "5400:5399" volumes: - /usr/lib/postgresql - ./tmp:/dmp:ro - ./load.sh:/usr/app/load.sh environment: POSTGRES_USER: vagrant POSTGRES_PASSWORD: vagrant POSTGRES_HOST_AUTH_METHOD: trust logging: driver: none networks: - integration django: build: . command: "/bin/bash" working_dir: /usr/app/ stdin_open: true tty: true volumes: - ./tmp:/tmp - ./:/usr/app - ~/.ssh:/root/.ssh:ro links: …