Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to implement login with Axios for multiple types of users?
I am building a web application ( with VueJs) that allows multiple types of users to login (e.g., regular users and administrators). I am using Axios to handle HTTP requests, but I am not sure how to implement login for multiple types of users. Certainly, here is the code with the provided section added to it: async submitForm() { const formData = { email: this.email, password: this.password } axios.defaults.headers.common["Authorization"] = ""; localStorage.removeItem("token"); await axios .post('http://127.0.0.1:8000/login', formData) .then(response => { console.log('response :', response.data) const token = response.data.auth_token this.$store.commit('setToken', token); axios.defaults.headers.common["Authorization"] = "Token " + token; localStorage.setItem('token', token); const toPath = this.$route.query.to || '/admin'; this.$router.push(toPath); }) .catch(error => { if (error.response) { for(const property in error.response.data) { this.errors.push(`${property}: ${error.response.data[property]}`); } } else { this.errors.push('Something went wrong. Please try again'); console.log(JSON.stringify(error.response.data)); } console.log(this.errors); }) }, Can someone provide guidance on how to achieve this with Axios? Any examples or code snippets would be greatly appreciated. Thank you! -
'Search' object has no attribute 'get'
I'm trying to create a search by last name, but it gives an error. Maybe I'm not comparing something correctly or taking the wrong value? forms.py from django import forms class CouponApplyForm(forms.Form): code = forms.CharField() views.py class Search(Coupon): def get_queryset(self): return Coupon.objects.order_by(fio=self.request.fio.get('q')) def get_context_date(self, *args, **kwargs): context = super().get_context_date(*args, **kwargs) context["q"]=self.request.GET.get("q") return context(context, "main/coupons.html") coupons.html <form action="{% url 'search' %}" method="get" class="form-control me-2"> <input type="search" placeholder="1" name="q" class="form-control me-2" required=""> <button type="submit" class="btn1 btn"> <span class="fa fa-search" aria-hidden="true"></span> </button> </form> I can’t understand, I display the search by last name, compare it with the request and give an error -
Why django-rest-framework-simplejwt integrated with my existing code is accepting uuid instead of username? [closed]
I am trying to integrate djangorestframework-simplejwt module in my existing Django project according to official document. The APIs is published but the fields its accepting is uuid and password instead of username and password. Although, I am passing the correct uuid and password but the api is not working by not authenticating and giving back JWT token. Versions I am using: django 3.2.12 djangorestframework 3.13.1 djangorestframework-simplejwt 5.2.2 Swagger view of token api: The user model: -
Why form return error "inactive user" in generic.View
I am writing a site on Django and faced the problem that when users are authorized, the form returns the error "This user account is inactive" in any case. Although I did this before and everything was fine This is my views.py file: template_name = 'users_logic/user_login.html' form_class = UserLoginForm success_url = reverse_lazy('main_page') def get(self, request): form = self.form_class return render(request, 'users_logic/user_login.html', {'form': form}) def post(self, request): form = self.form_class(request.POST) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(username=username, password=password, backend=settings.AUTHENTICATION_BACKEND) print(user) if user is not None: login(request, user) print(user) messages.success(request, 'Ви успішно авторизувались') return redirect('main_page') else: messages.error(request, 'Помилка авторизації') else: messages.error(request, 'Неправильний логін або пароль') print(form.error_messages) form = self.form_class() return render(request, 'users_logic/user_login.html', {'form': form}) this is my register view: class SignUp(generic.CreateView): template_name = 'users_logic/user_register.html' form_class = UserRegisterForm success_url = reverse_lazy('user_login') success_message = "Реєстрація пройшла успішно" my login_form: class UserLoginForm(AuthenticationForm): class Meta: model = user_form fields = ('username', 'password1') username = forms.CharField(label='Ваш логін', widget=forms.TextInput(attrs={'class': 'form-control'})) password = forms.CharField(label='Ваш пароль', widget=forms.PasswordInput(attrs={'class': 'form-control'})) How can it be fixed? -
Django model admin hooks order
I am trying to find the model admin hooks ordering for a request, I need to inject a LogEntry into an inline model and I am tring to find the correct hook points for addition, modified and delete actions on the form. I know that the log will be created under the modelAdmin in which the inline sits but I need to add one. Is there any documenttation on the modelAdmin hook paths ? Thanks -
Django book details with different form and html template
i have some question about a DJANGO framework book blog details example .My problem is i have a book list in Django template using something like this {% url 'book_details' value.slug_title %}.My problem is for different book details i have a different Django form and different HTML template .i build a snippet code and work fine ,but i dont like this code way ,i would like to propose a different code way to take correct results. here the code : def blog_details(request,slug): data = get_object_or_404(app_descript, slug_title=slug) if str(data.title) == 'name 1': if request.method=='POST': ....................... return render(request, 'details/name1.html', {'data': data}) elif str(data.title) == 'name 2': if request.method=='POST': ............................... return render(request, 'details/name2.html', {'data': data}) elif str(data.title) == 'name 3': if request.method=='POST': ................. return render(request, 'details/name3.html', {'data': data}) -
Optimize Django query in reverse lookup
I have 2 models class Chassis(models.Model): number = models.CharField(max_length=10, unique=True) class Eir(models.Model): chassis = models.ForeignKey( 'management.Chassis', null=True, blank=True, related_name='eir', on_delete=models.SET_NULL ) number = models.IntegerField(unique=True, default=0) I tested via Django CLI >>> chassis = Chassis.objects.prefetch_related('eir') >>> chassis >>> chassis.first().eir.all() I tried the commands above and it still did a query with the eir table as shown below: # produced from ">>> chassis" {"Time":[2023-03-07 08:25:42 UTC], Host:10.116.1.165} LOG: duration: 0.238 ms statement: SELECT "management_chassis"."id", "management_chassis"."number" FROM "management_chassis" LIMIT 21 {"Time":[2023-03-07 08:25:42 UTC], Host:10.116.1.165} LOG: duration: 0.777 ms statement: SELECT "rental_eir"."id", "rental_eir"."number", "rental_eir"."chassis_id" FROM "rental_eir" WHERE "rental_eir"."chassis_id" IN (1292, 104) # produced from ">>> chassis.first().eir.all()" {"Time":[2023-03-07 08:25:59 UTC], Host:10.116.1.165} LOG: duration: 0.239 ms statement: SELECT "rental_eir"."id", "rental_eir"."number", "rental_eir"."chassis_id" FROM "rental_eir" WHERE "rental_eir"."chassis_id" IN (80) I was expecting that there will be no 3rd query anymore as the data will be stored in memory. My real purpose is related to Django REST Framework manipulating the returned data in def to_representation where a reverse lookup is done like ret['eir'] = instance.eir.all().last().id where instance is Chassis model -
Django API file name issue
When i tried to upload a file with filename in arabic , in database it stored as the arabic filename .But when the API calls, the filename '%D8%B3%D8%A7%D9%82_%D8%A7%D9%84%D8%A8%D8%A7%D9%85%D8%A8%D9%88_UP8kxN2.pdf' like this . Can anyone know how to solve the issue? I want to get the filename as Arabic text of filename, -
how to merge to query sets with using keyword values
I am get two query sets, users: {{'username': 'muthu12', 'user id': 25, 'code': 'GKUPDY'} and multiple dict} , 2) deposit history: {{'amount': 16.0, 'user_id':25} and multiple dict..} My expected answer below type of queryset, users = {'username': 'muthu12', 'user_id': 25, 'referrel_code': 'GKUPDY', 'amount': 16,'date_joined': datetime.datetime(2023, 3, 2, 8, 47, 6, 582087)} -
I'm trying to apply css style file but Django not recognizing it
this is the base.html <!DOCTYPE html> {%load static%} <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>{% block page_title %}my challenges{% endblock %}</title> <link rel="stylesheet" href="{% static "style.css"%}"> {%block css_files%} {%endblock%} </head> <body> {% block content %} {% endblock %} </body> </html> challenges.css ul{ list-style: circle; margin: 2rem auto; width: 90% ; max-width: 50rem; box-shadow: 0 2px 8px rgba(0, 0, 0, 0.26); padding: 1rem; border-radius: 1px; } index.html {% extends 'base.html' %} {% load static %} {%block css_files%} <link rel="stylesheet" href="{% static "challenges/challenges.css" %}"> {%endblock%} {%block page_title%} All chalenges {%endblock%} {%block content%} {% include "challenges/includes/header.html" %} <ul> {% for month in months%} <li><a href="{% url "month-challenge" month %}">{{month|title}}</a></li> {% endfor %} </ul> {%endblock%} [path is here in the image[][1]][1] [1]: https://i.stack.imgur.com/2qqmC.png [see the image styles are not applying ][2] [2]: https://i.stack.imgur.com/h9agu.png please help me on this I've already added the path and everything on setting.py also STATIC_URL = "static/" STATICFILES_DIRS = [ BASE_DIR / "static" ] -
how can I merge grpc client and http request?
I want to merge http request and grpc client that means: I have a request for create some object. my service is gateway that means it sends data in celery task and grpc client sends a request and receive stream responses. when should i run this client? should i run the client in same function that sends data in celery task or not? I am really confused. -
Django - How to redirect back to search page and include query terms?
My pages/views are structured as follows: index.html => search_results.html => object_details.html, in which user can make a POST request in object_details.html. I am trying to redirect back to search_results.html after the POST request, but also keep both query strings. The url of search results shows as follows, and can have 1 or both queries made: www.example.com/search-results/?search_post=xxxxx&search_author=xxxxx The closest I am able to get what I want is using: return redirect(reverse('search-results') + '?' + 'search_post={{search_post}}'+'&'+'search_author={{search_author}}') however this would actually show "{{search_post}}" and "{{search_author}}" in each of the 2 fields of the search form in search_results.html Also, my search_results view has the following: search_post = request.GET.get('search_post') search_author = request.GET.get('search_author') How can I do this? Thank you -
Django admin panel model in main page
I have few admin models, how can I display one of the admin models in the admin panel main page so the fields of such model show without having to click on the model in admin panel homepage. Similar to the image below, a model field inside a box showing in the main admin page is what I need. -
WebSocket connection to 'ws://127.0.0.1:8000/ws/iphone/' failed:
Whenever I'm visiting http://127.0.0.1:8000/rooms/iphone/, I'm getting the below error: WebSocket connection to 'ws://127.0.0.1:8000/ws/iphone/' failed: I'm developing a DJango chat web application but facing this issue from past many days but didn't got any solution, if anyone has some knowledge in this domain, then please help me to get out of this issue. index.html <h1>List of Rooms</h1> {% for chatroom in chatrooms %} <a href="{% url 'chatroom' chatroom.slug %}">{{ chatroom.name }}</a> </br> {% endfor %} consumers.py from channels.generic.websocket import AsyncWebsocketConsumer import json from asgiref.sync import sync_to_async class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name=self.scope['url_route']['kwargs']['room_name'] self.room_group_name= 'chat_%s' % self.room_name await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() async def disconnect(self): await self.channel_layer.group_discard( self.channel_layer, self.room_group_name ) room.html {{ chatroom.name }} <form method="post"> {%csrf_token%} <input type="text" name="message" placeholders="Enter message"> <button type="submit">Send</button> </form> {{ chatroom.slug|json_script:"json-chatroomname" }} <script> const chatRoomName = JSON.parse(document.getElementById('json-chatroomname').textContent) console.log(chatRoomName) const chatSocket = new WebSocket( 'ws://' +window.location.host +'/ws/' +chatRoomName +'/' ) console.log(chatSocket) chatSocket.onmessage= function(e){ console.log('This is a message') } chatSocket.onclose = function(e){ console.log('Socket closed' + " " + e) } </script> routing.py from django.urls import path from .import consumers websocket_urlpatterns=[ path('ws/<str:room_name>',consumers.ChatConsumer.as_asgi()), ] I tried a lot to solve this problem but didn't got the solution from past few days. Plz help me to solve this issue. … -
Chatbot Frontend for Django Backend API
I made a simple backend API using Django REST and I wanted to make a chatbot using React js. I asked ChatGPT (lol) for an overview of how I could do that and it recommended making a separate Github repository for the React.Js environment as it could mess with my Django Virtual environment. I'd rather not use 2 repositories because this is a project for my resume and I wanted everything on one repository just for simplicity. Is that still possible or should I listen to Chat GPT? Thank you -
Chrome browser can't get csrf from cookie
I copy the code from Django official site to get csrftoken from cookie. function getCookie(name) { let cookieValue = null; if (document.cookie && document.cookie !== '') { const cookies = document.cookie.split(';'); for (let i = 0; i < cookies.length; i++) { const cookie = cookies[i].trim(); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } csrftoken = getCookie('csrftoken'); It originally works well, but in some days it can't work for Chrome anymore. But it still works for Firefox. -
NoReverseMatch at /food/1/ Reverse for 'delete_item' with arguments '('',)' not found. 1 pattern(s) tried: ['food/delete/(?P<id>[^/]+)/\\Z']
[enter image description here](https://i[enter image description here](https://i.stack.imgur.com/SYkkd.png).stack.imgur.com/eGkw2.png) so im getting error in noreverse match found -
Pass a .zip file to a Docker container using python
I am using the Docker SDK to try and push a file from a Django web request method of POST to a Docker container. In my use case, the .zip file cannot touch the local machines file directory or load into memory. The file must go straight to the Docker container. This is the code I have so far but I cannot seem to find a way to get a file to passthrough to the container and get back command output from the commands I am running. Any help would be greatly appreciated. import docker client = docker.from_env() # start the container container = client.containers.run( image='myimage:latest', command='mkdir /tmp/upload', remove=True, detach=True, network_mode='none', ) try: # write the uploaded file to the container's file system container_id = container.id container_exec_command = f'cat > /tmp/upload/{zipfile.name}' _, stream = container.exec_run(cmd=container_exec_command, stream=True) with zipfile as f: for chunk in f.chunks(): stream.write(chunk) # perform the rest of the processing inside the container container_exec_command = f""" cd /tmp/upload # unzip the file echo y | unzip -P {filePassword} {zipfile.name} # get the filename of the other file in the directory filename=$(find . -maxdepth 1 -type f ! -name '*.zip' -printf "%f\n") # run sha256 sum against it, then … -
Pass an argument to a url with hx-get
I'm using HTMX to render different partial templates in a 'group-detail' page. The get requests are triggered by click event, and rendered in a tag. However, I'm trying to pass the group information so I can render the correct information in the partial template, but the data isn't being rendered. <li><a hx-trigger="click" hx-get="{% url 'groups:info' group.slug %}" hx-target="#group-content" class="btn btn-outline btn-rounded btn-tertiary btn-with-arrow mb-2">Info<span><i class="fas fa-chevron-right"></i></span></a></li> Here I'm passing the slug argument so it can know which group data render. This is the partial view: def group_info(request, slug): group = Group.objects.filter(slug=slug) context = { 'group' : group } return render(request, 'groups/partials/info.html', context) And I'm trying to render {{group.name}} in the info.html template for example, but nothing gets shown (the correct slug is being passed, the correct template is being rendered, but not the {{}} tags). Not getting any error neither. Am I missing something on passing URL arguments with htmx? -
Creating an event driven architecture using Django
I would like to create an event driven architecture in Django. Every time a database record is created, updated or deleted, i would like to create and event, posting it to a queue ( like kafka, sqs, or something similiar). I know that Django has a post_save method, that I could use to capture the record and post it in a queue, but I suppose that I could suffer for a dual write problem, i.e., update the database, but fails to post message in the queue. Does Django have any different mecanism? Does Django retry the post_save method? Should I use a outbox pattern or process database bin log instead? -
Why is timezone.now showing a future date when being applied as a default value to DateField in django
Here are the relevant settings in my project: settings.py TIME_ZONE = "US/Mountain" USE_TZ = True models.py (using timezone.now) class Submission(models.Model): date_created = models.DateField( default=timezone.now, blank=True, ) datetime_created = models.DateTimeField( default=timezone.now, ) If I create a Submission at 5PM MST on 03/01/2023 these are the values I get: date_created: "2023-03-02" datetime_created: "2023-03-01 17:00:00-07:00" Why would date_created be using the date of the following date? -
Using Django DecimalField with Select Widget
I'm not sure if there is something special I should be doing but I have a model and form similar to the following; # models.py from django.db import models class ObjectModel(models.Model): object = models.DecimalField(max_digits=10, decimal_places=2) # my_settings.py from decimal import Decimal object_choices = [ (Decimal('1'),'1'), (Decimal('1.5'),'1.5'), (Decimal('2'),'2'), (Decimal('2.5'),'2.5'), (Decimal('3'),'2.5'), ] # forms.py from django import forms from my_settings import object_choices from models import ObjectModel class ObjectForm(forms.ModelForm): object = forms.ChoiceField(choices = object_choices) class Meta: model = ObjectModel fields = ['object'] The form renders fine, and saves the object without any problem. I can see in the Django Admin that the value I select on the form gets saved to the model, and all the other fields (not shown above) render and work fine. When I load a form to edit the model rather than create a new one, e.g views.py from forms import ObjectForm ... form = ObjectForm(instance = obj) ... The select widget which renders doesn't have an initial value. If I delete the definition for 'object' in the form definition and let it render with the default text input, everything works as expected and I can see the correct value, the same as I can see in the Django … -
Remote desktop as a website host (VPN access only)
Networking is not a strong skill of mine and I'm currently working on making an internal website for my company and I don't want to make this website available publicly. Basically, we have a remote desktop that we can solely access via VPN and I wonder if it's possible to make that remote desktop as the website host so that no one can access the website except for the ones who are in the VPN? I'll be building the site via Django and python and any guidance would be much appreciated. -
stylesheet only rending for my 'core' app, and not for the rest of my apps in the same directory
For some reason, my stylesheet isn't loading for my other apps. . When I GET http://127.0.0.1:8000/static/style.css, it returns .container { width: 50vw; margin: 50px auto; padding: 25px 10px; background-color: #ffffff; border-radius: 3px; text-align: center; box-shadow: 0 19px 38px rgba(0,0,0,0.30), 0 15px 12px rgba(0, 0, 0, 0.22); } I loaded this for all my templates: {% load static %} <link rel="stylesheet" href="{% static 'style.css' %}"> This loads fine for all my templates in website (this was the first app i created, not sure if that changes anything) When I try to do this for my other apps (chat/friend/accounts) it doesn't apply at all. Does anyone know why this is happening? I don't get any console error for the stylesheet on my other pages.. settings.py: # static STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) -
Referencing more than one field on a Django Model
I am trying to reference 2 fields from a particular django model but it keeps giving me error. The models are displayed below, i want to reference 'building_type' and 'location' from property table to client table class Property(models.Model): location = models.CharField(choices=Property_Location, max_length=120) building_type= models.CharField(choices=Property_Type, max_length=120) initial_quantity= models.IntegerField(null= False, blank= False) quantity_in_stock= models.IntegerField( null= False, blank= False) quantity_sold = models.IntegerField( null= False, blank= False) def __str__(self): return self.location class Client(models.Model): first_name = models.CharField(max_length=120) last_name = models.CharField(max_length=120) phone = models.IntegerField() email = models.EmailField(max_length=130) building_type= models.ForeignKey(Property,null= False, blank= False, on_delete=models.CASCADE) location= models.ForeignKey(Property, null= False, blank= False, on_delete=models.CASCADE) def __str__(self): return self.first_name + ' '+ self.last_name