Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to pass choises from views.py in forms.ChoiceField?
I want to make a form for online tests, but I can't figure out how to make radio buttons (forms.ChoiceField or similar) with the transfer of the selection value not from forms, but from views. Why can't you get from models directly in the form? because I do not know in advance which pk is needed. Please tell me an option that will help you create a form for online testing. I ask with examples to make it easier to understand. Thanks in advance. -
Reverse for 'bans' with keyword arguments '{'user': 1}' not found. 1 pattern(s) tried: ['bans/(?P<pk>[0-9]+)/$']
I am building a GroupApp and I am trying to add some group members in premium_members(ManyToManyField). In Brief :- I made a Group model for group creation and adding members and I made another GroupPosts with ForeignKey of Group for post creation in the particular Group with id or pk. It means i am accessing all the groups in one page and when someone opens a group then blogposts are showing of the clicked group, Like group_1 has 6 posts and group_2 has 2 posts. AND I am trying to add post_creater in premium_members which is a instance in Group Model. The Problem :- BUT When i click on add_premium_member in the group's post's User. Then post creater is not adding in premium_members. No error is showing. BUT NOT ADDING. models.py # For Group Creation class Group(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=30,default='') premium_members = models.ManyToManyField(User, related_name='premium_members', blank=True) def get_absolute_url(self): return reverse('group_detail_view',kwargs={'pk':self.pk}) # For Post Creation in Particular Group class GroupPosts(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) group = models.ForeignKey(Group,on_delete=models.CASCADE) post_title = models.CharField(max_length=30,default='') views.py # For show the group details and posts in one page (group_detail_view) def group_detail_view(request,pk): data = get_object_or_404(Group,pk=pk) posts = GroupPost.objects.filter(group=data) context = {'data':data,'posts':posts} return render(request, 'group_detail_view.html',context) # … -
How to access a legacy database without creating a new table in it in Django
I was given access to a database to use on one of my Django projects. I set everything up and went to migrate the new models and I got an error. "Unable to create the django_migrations table ((1142, "CREATE command denied to user 'MyDatabaseName' for table 'django_migrations'"))" After looking into it, I see its because Django is trying to create a new table in that database. I don't have write access and I do not want it because I am pretty new at this and do not want to mess anything up. I am also not sure the owner would give it to me. Is there a way to get to use the legacy database without having to create a new table in it? -
how to make requirements.txt work while using circle ci with django
I have the following configuration crashing using CIRCLE CI / DJANGO FOLDER STRUCTURE .circleci |____ config.yml djangoproject |____ djangoproject |____________ settings.py ...etc |____ manage.py Circle CI config.yml file jobs: build: working_directory: ~/someproject docker: - image: circleci/python:3.8 auth: username: mydockerhub-user password: $DOCKERHUB_PASSWORD environment: PIPENV_VENV_IN_PROJECT: true DATABASE_URL: postgresql://root@localhost/circle_test - image: circleci/postgres auth: username: mydockerhub-user password: $DOCKERHUB_PASSWORD environment: POSTGRES_USER: admin POSTGRES_DB: $POSTGRES_DB POSTGRES_PASSWORD: $POSTGRES_PASSWORD steps: - checkout - run: sudo chown -R circleci:circleci /usr/local/bin - run: sudo chown -R circleci:circleci /usr/local/lib/python3.8/site-packages - restore_cache: key: deps9-{{ .Branch }}-{{ checksum "requirements.txt" }} - run: name: Wait for db to run command: dockerize -wait tcp://localhost:5432 -timeout 1m - run: name: Install Python Dependencies command: | pip3 install virtualenv python3 -m venv env . env/bin/activate pip3 install -r requirements.txt - save_cache: key: deps9-{{ .Branch }}-{{ checksum "requirements.txt" }} paths: - "env" - "/usr/local/bin" - "/usr/local/lib/python3.8/site-packages" - run: name: run tests command: | . env/bin/activate pytest -s -v mkdir test-results pytest --junitxml=test-results/junit.xml --html=test-results/pytest_results.html --self-contained-html - store_test_results: path: test-results - store_artifacts: path: test-results workflows: build_and_test: jobs: - build When i push a change to github, Circle CI crash with the following error: #!/bin/bash -eo pipefail pip3 install virtualenv python3 -m venv env . env/bin/activate pip3 install -r requirements.txt Requirement … -
Django - filtering on foreign key usin an attribut
i have 2 foreingkey , one from the User and the other one from Device. class checkn(models.Model): user = models.ForeignKey(User, null=True,on_delete= models.SET_NULL) devices = models.ForeignKey(Device, null=True,on_delete= models.SET_NULL) date_created = models.DateTimeField(auto_now_add=True, null=True) ch = models.CharField(max_length=1000, null=True) he's using the Device ID for the search and i want to use the IP adresse : this is the device model : class Device(models.Model): hostname = models.CharField(max_length=200, null=True) password = models.CharField(max_length=200, null=True) type = models.CharField(max_length=200,choices=dtype, null=True) ipadress = models.CharField(max_length=200, null=True) date_created = models.DateTimeField(auto_now_add=True, null=True) any advices ? -
Customizing model fields by user
I am making a CRM, and I ran into one task: I want to make a “Client” model, with all possible fields, and give an opportunity for users to “enable” only those “Client” fields that he needs. I have little experience and unfortunately I have not been able to find a solution for this for a long time. I would be grateful if someone can show me an example of how this is done (or a link to a repository with a similar method). -
Setting Up Logins For Users with Django
I am trying to use Django's built in user authentication for login/allowing users to create an account and login. I think there's something wrong with my urls or where files are placed in the project. Can anyone help? I know the login.html file is supposed to be inside a folder called 'registration.' I think the fact that my templates are then in a sub folder called 'capstone' might be causing issues. I just don't know how to point to the right file when someone clicks to login. In urls.py under 'weather' I have the following. In two tutorials I saw it should say 'accounts/' but I'm a bit confused as to why. urlpatterns = [ path('admin/', admin.site.urls), path('', include('capstone.urls')), # medium site says to do this path('accounts/', include('django.contrib.auth.urls')), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) This is how my files are set up in Visual Studio Code: -
Django how to add admin page without using model
I needed to create a admin page which is not associated with any model. I have followed the below documentation. https://docs.djangoproject.com/en/3.2/ref/contrib/admin/#django.contrib.admin.ModelAdmin.get_urls So my admin.py looks like this, class MyModelAdmin(admin.ModelAdmin): def get_urls(self): urls = super().get_urls() my_urls = [ path('statistic/', self.my_custom_view), ] return my_urls + urls def my_custom_view(request): . . . return HttpResponse(html) When I login to admin site, I am not able to see the link for this view. Then I added below line to the above code, admin.site.register(MyModelAdmin) It is not working. Please advise what I am doing wrong. -
Request deleting an appointment?
I'm trying to build an appointment system. If a user decided to delete his appointment it must be through request where the admin decides to accept/reject his deleting request. after that the user will receive an email that his deleting request got approved/rejected.. how do I implement that? Where should I start reading about it? Any help is appreciated! -
Docker: Unable to send task from Django to Celery
I have been working recently with Docker and I was able to set up certain services to be able to use Async functions but when I try to send a task to Celery from Django using RabbitMQ it never reachs. When I run the code outside Docker by running several commands on console everything runs perfectly. Not sure whats going on. Any help would appreciated. version: "3.7" services: rabbit: hostname: rabbit container_name: rabbitmq image: 'rabbitmq:3.7-management' environment: RABBITMQ_ERLANG_COOKIE: "SWQOKODSQALRPCLNMEQG" RABBITMQ_DEFAULT_USER: admin RABBITMQ_DEFAULT_PASS: admin RABBITMQ_DEFAULT_VHOST: "/" RABBITMQ_VM_MEMORY_HIGH_WATERMARK: 0.5 CELERY_BROKER_URL: "amqp://admin:admin@172.23.240.1:5672" ports: - "15672:15672" - "5672:5672" expose: - "5672" restart: on-failure networks: rabbitmq_net: aliases: - rabbitmq_host custom_app: build: . container_name: custom_app command: python manage.py runserver 0.0.0.0:8000 volumes: - static:/code/static - .:/code depends_on: - rabbit environment: - CELERY_BROKER='amqp://admin:admin@172.23.240.1:5672' - CELERY_BACKEND='amqp://admin:admin@172.23.240.1:5672' networks: - rabbitmq_net links: - rabbit nginx: image: nginx:1.13 container_name: nginx ports: - 8000:80 volumes: - ./config/nginx/conf.d:/etc/nginx/conf.d - static:/code/static volumes_from: - custom_app depends_on: - custom_app networks: - rabbitmq_net celery: build: . container_name: celery command: celery -A djangoapp worker --loglevel=info -P eventlet debug volumes: - .:/code depends_on: - rabbit networks: - rabbitmq_net volumes: .: postgres_data: static: networks: rabbitmq_net: name: rabbitmq_network driver: bridge -
Django CKEditor - youtube embeded video disappear after saving at admin panel
There is no problem with uploading. But when I lookup to the article for editing then I can't see youtube video Before saving: After Saving: But actually the iframe block at there. The problem is I can't see it at admin panel again settings.py CKEDITOR_CONFIGS = { 'default': { 'toolbar': 'CMS', 'width': '100%', 'toolbar_CMS': [ ['Format', 'Styles', 'FontSize'], [ 'Bold', 'Italic', 'Underline', 'Strike', 'Subscript', 'Superscript'], ['TextColor', 'BGColor'], ['Link', 'Unlink'], ['JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock'], ['Undo', 'Redo'], ['Copy', 'Paste', 'PasteText', 'PasteFromWord'], ['SelectAll', 'Find', 'Replace'], ['NumberedList', 'BulletedList'], ['Outdent', 'Indent'], ['Smiley', 'SpecialChar', 'Blockquote', 'HorizontalRule'], ['Table', 'Image', 'Youtube'], ['ShowBlocks', 'Source', 'About'] ], 'extraPlugins': 'youtube', 'contentsCss': ( '/staticfiles/ckeditor/customization-files/style.css', '/staticfiles/ckeditor/customization-files/bootstrap.css', ), }, } CKEDITOR_UPLOAD_PATH = 'content/ckeditor/' models.py class Article(models.Model): title = models.CharField(max_length=200) content = RichTextField( extra_plugins=['youtube'], null = False, blank=False, external_plugin_resources=[( 'youtube', '/staticfiles/ckeditor/extra_plugins/youtube/', 'plugin.js', )], ) updated = models.DateField(auto_now=True) created = models.DateField(auto_now_add=True) Django version: 3.2.3 django-ckeditor version: 6.1.0 Additionaly detail: When I click to "See HTML source" and save article then even the current video removing from database -
Django Form only show when i press Submit Button
my form is hide, its onlye display submit button, and when i click it the forms show. Crear Tarea= Create task. Its basically a crud for create task. Here are my Views: class Crear_Tarea(View): def get(self, request,*args,**kwargs): context = { 'form': TareaForm() } return render(request, "crear_tarea.html", context) def post(self, request,*args,**kwargs): context = { 'form': TareaForm() } formulario = TareaForm(request.POST or None) if formulario.is_valid(): formulario.save() messages.success(request, 'Tablero seleccionado con éxito!') context['crear_tarea']= formulario return render(request, "crear_tarea.html", context) My forms: class TareaForm(forms.ModelForm): class Meta: model = Tarea fields = ('nombre','descripcion','fecha_creacion','fecha_termino','user', 'id_columna' ,'id_tipo','detalle','id_documento','estado','estado_avance','posicion') def save(self, commit=True): user = super().save(commit=False) user.id = self.cleaned_data['user'] if commit: user.save() return user and my Models.py class Tarea(models.Model): id_tarea = models.AutoField(primary_key=True) nombre = models.CharField(max_length=99) descripcion = models.CharField(max_length=99) fecha_creacion = models.DateTimeField(null=True, blank=True) fecha_termino = models.DateTimeField(null=True, blank=True) user = models.ForeignKey(Usuario, on_delete=models.CASCADE) id_columna = models.ForeignKey('Columna', on_delete=models.CASCADE) id_tipo = models.ForeignKey('Tarea_tipo', on_delete=models.CASCADE) detalle = models.CharField(max_length=255) id_documento = models.ForeignKey('Documento', on_delete=models.CASCADE) estado = models.IntegerField(blank=True, null=True) estado_avance = models.IntegerField(blank=True, null=True) posicion = models.IntegerField(blank=False, null=False) def __str__(self): return self.nombre crear_tarea.html {% extends "base.html" %} {% load static %} <!doctype html> <html lang="en"> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <title>{% block title %}Crear Tarea Ari-J{% endblock %}</title> {% block content %} <div class="container-fluid"> <div class="row mt-5"> <div class="col-12 my-5"> … -
How to change edges (lines) color when filtering by a drop down menu javascript
I have a folim map drawing by a python code.I have a drop down menu on the left of the map. When selecting the Lane (input) value : all edgs associated to a Lanes value=1 should be colored as "#FF0000" all edgs associated to a Lane value=2 should be colored as "#FFF933" Could you please help me? {% load static %} {% block content %} <div class="row h-100"> <div class="col-md-2" id="destinationDiv"> </div> <div class="col-md-10"> {% include 'visualization/visualization.html' %} </div> <div class="form-group w-75 mx-auto"> <label for="linkSelector" class="sr-only">Links</label> <select id="linkSelector" class="form-control"> <option value="none">Links...</option> <option value="lanes">Lanes (input)</option> <option value="length">Length (input)</option> </select> </div> </div> <script src="{% static '/js/api/changeMapData.js' %}"></script> {% endblock %} My Javascript code which will fetch the data from the api. function changeMapData(){ fetch("http://127.0.0.1:8000/api/edges/") .then(response => { return response.json() }) .then((data) => { var linkSelector = document.getElementById('linkSelector') switch (linkSelector.value) { case "Lanes(input)": if($(edges.lanes)==1){ // Set all edges color = "#FF0000" with number of lanes=1 edges.setStyle ({ 'fillColor': "#FF0000", 'color': "#FF0000" }); } if($(edges.lanes)==2){ // Set all edges color = "#FFF933", with number of lanes=2 edges.setStyle ({ 'fillColor': "#FFF933", 'color': "#FFF933" }); } } }); } My html page containing the map. -
How can i create / Check permission using Django ? Real example
I'm working on a small project using Django / Rest Framework, and now i try to add Groups / Permissions options i don't know from where to start to do permissions checking. I surfed a lot on Google and here, i can't find any tutorial that explain how to use Groups and Permissions ( programmatically ), now I arrived to create a group / permission. like that : from django.contrib.auth.models import Group, Permission from django.contrib.contenttypes.models import ContentType from api.models import Project new_group, created = Group.objects.get_or_create(name='new_group') # Code to add permission to group ??? ct = ContentType.objects.get_for_model(Project) # Now what - Say I want to add 'Can add project' permission to new_group? permission = Permission.objects.create(codename='can_add_project', name='Can add project', content_type=ct) new_group.permissions.add(permission) Now how can i check if the user has X Permission or no ? where must i do this Logic ? also i heared some thing about default permission that any user has called ( Django Model Permission ) how can i use that ? my Goal is to create a Group and add user to a group, check if the user has the right permissions like any normal applciation can someone give me a small real example ? Thank you -
Get dynamic Form Value from Django Forms
I'm trying to get the totalPrice value from the changing value of the form field through JavaScript. My view part: if request.method == "POST": if (not closed): form = BookingForm(request.POST) if form.is_valid(): booking = form.save(commit=False) booking.author = user booking.hotelName = hotel.name booking.save() success = "Success!" else: return render(request, "hotels/hotel.html", { "form": form }) messages.info(request, success) return HttpResponseRedirect(reverse("hotel", args=(hotel.id,))) else: return render(request, "hotels/hotel.html", { "hotel": hotel, "closed": closed, "message": message, "form": BookingForm() }) My HTML + JS Code: {% if not closed %} <div class="container login"> <h2>Book Now!</h2> <form method="POST"> {% csrf_token %} <div class="form-group"> {{ form.as_p }} </div> <div class="form-group"> <input type="submit" name="button" id="submit" value="Book"> </div> </form> </div> {% endif %} <script> let price = 0; const check = (id) => { if(document.querySelector(`#${id}`).checked) { price += 300; document.querySelector('#totalPrice').value = `${price}`; } if(!document.querySelector(`#${id}`).checked) { if (!price <= 0) { price -= 300; document.querySelector('#totalPrice').value = `${price}`; } } } document.addEventListener('DOMContentLoaded', function() { document.querySelector("#breakfast").addEventListener('click', () => check("breakfast")); document.querySelector("#dinner").addEventListener('click', () => check("dinner")); }) </script> And, my form (through ModelForm): class BookingForm(ModelForm): class Meta: model = Booking fields = ['includeBreakfast', 'includeDinner', 'totalPrice'] labels = { 'includeBreakfast': 'Include Breakfast', 'includeDinner': 'Include Dinner', 'totalPrice': 'Total Price (in USD)' } #Visual stuff the totalPrice is a FloatField in … -
i am getting an error while i am trying to add a user to a defined group while registration in django
#views.py def sign_up(request): if request.method == "POST": fm= SignUpForm(request.POST) if fm.is_valid(): messages.success(request,'account created') fm.save() group = Group.objects.get(name='groupname') User.groups.add(group) else: fm = SignUpForm() return render(request,'signup.html',{'form':fm}) and,i am getting AttributeError like this below:- Django Version: 3.2.3 Exception Type: AttributeError Exception Value: 'ManyToManyDescriptor' object has no attribute 'add' -
How can I convert/export HTML code returned by django-ckeditor's RichTextUploadingField to a docx file?
I want to convert html received from django-ckeditor Field to a docx file, for which I'm using htmldocx. The html code returned by ckeditor uses a css file which contains styles like background-color. So htmldocx is able to recognise bold, italics and alignment but it is not recognising the highlight color. contents of views.py: def home(request): if request.method == 'POST': htd = HtmlToDocx() document = Document() htd.add_html_to_document(request.POST.get('file'), document=document) document.save(settings.MEDIA_ROOT+'TEST.docx') form = File() return render(request, 'home.html', {'form': form}) else: form = File() return render(request, 'home.html', {'form': form}) contents of models.py: class Document(models.Model): file = RichTextUploadingField(blank=True,null=True) For example: for submitted text "Hello World" , where say 'World' is both, highlighted and in italics, the html code returned is: <p>Hello <em><span class="marker">World</span></em></p> #styles of marker class are defined in a separate css file by ckeditor but upon converting the html to docx, the document loses highlight color. Is there any workaround to this issue? Also, ckeditor provides an export to word feature but only through npm. If somehow I could use that feature in django-ckeditor, things would become much easier. How can I implement that feature in django-ckeditor? -
Why do I get an 404 Error in part 4 of the Django tutorial "Writing you first Django app"
I am trying to complete the Django tutorial: Writing your first Django app. I am currently stuck on part 4. After updating my template polls/templates/polls/detail.html, rewriting my polls/views.py and creating a results.html located at polls/templates/polls/results.html, I ran the server and tried to go to http://127.0.0.1:8000/polls/1/, but I get this Error: Page not found (404) No Question matches the given query. Request Method: GET Request URL: http://127.0.0.1:8000/polls/1/ Raised by: polls.views.detail Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: polls/ [name='index'] polls/ <int:question_id>/ [name='detail'] The current path, polls/1/, matched the last one. You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. I see that the error is raised by the html-file detail wich looks like this: <form action="{ url 'polls:vote' question.id }" method="post"> { csrf_token } <fieldset> <legend><h1>{{ question.question_text }}</h1></legend> { if error_message }<p><strong>{{ error_message }}</strong></p>{ endif } { for choice in question.choice_set.all } <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}"> <label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br> { endfor } </fieldset> <input type="submit" value="Vote"> </form> My other two templates (html-files) index and result looks like this: … -
Django form validation fails when dynamically creating form by overwriting __init__
I'm writing a prediction app in Django. At a basic level it pulls matches from an API, populates the database, and finally allows users to make predictions on matches that have not yet been played. As I don't know how many matches will be in a tournament before the fact, I wanted to create a form that dynamically adds as many fields as is required. I currently have a "working" version but it would create issues further down the line. Here's the working version: (Fair warning, this is me testing, so excuse the naming conventions) views.py def ftest(request, contest_id): matches_list = Matches.objects.filter( matches_contest_pk__id = contest_id ).filter( matches_complete = False ).order_by( '-matches_start_time' ) matches = [ f'{match.matches_team_1} vs. {match.matches_team_2}' for match in matches_list ] if request.method == 'POST': form = TestForm(form_fields = matches, data=request.POST) if form.is_valid(): return HttpResponseRedirect('/thanks/') else: print(form.errors) else: form = TestForm(form_fields = matches) context = { 'form': form, } return render(request, 'predictions/test.html', context) forms.py from django import forms from .models import Matches class TestForm(forms.Form): def __init__(self, *args, **kwargs): form_fields = kwargs.pop('form_fields', None) super(TestForm, self).__init__(*args, **kwargs) for field in form_fields: self.fields[field] = forms.CharField(label = f'{field}', max_length = 100) As I said, this works but I would, ideally, like to … -
open html file and add data into it with iteration
I have a html file for Invoice. and i want to display some data from my database which can be in multiple rows of a table. how can i use iteration to show the data in my Invoice. for example: In an organisation 3 people used a coupon to do a payment. and when invoice would generate all of the three people's name with date and amount i want to display. <thead> <tr> <th class="col-4 border-0"><strong>Sites</strong></th> <th class="col-4 border-0"><span><strong>Mode</strong></span></th> <th class="col-4 border-0"><span><strong>Amount</strong></span></th> </tr> </thead> <tbody> <tbody> ---for loop here--- <tr> <td class="col-4 text-1 border-0"> {var 1} </td> <td class="col-4 border-0"><span> {var 2} </span></td> <td class="col-4 border-0"><span> {var 3} </span></td> </tr> </tbody> </table> The way i am passing data from views is: my_dict=[{'var1':'my site', 'var2': 'DIY', 'var3':'111'}, {'var1':'my site2', 'var2': 'DIY', 'var3':'222'}] with open(BACKEND_TEMPLATE + 'Invoice_base.html') as inf: txt = inf.read() val = txt.format(date=today, invoice_id=str(identity), domain=FRONTEND_DOMAIN, customer_name=(obj.customer.first_name + " " + obj.customer.last_name), company=obj.customer.company_name, contact=obj.customer.phone_number, my_dict=my_dict) how can i achieve that. The html file is not supporting template tags or may be i am not using it correctly. if there is an easy solution please help me out! -
sliding key in Django how to
i am fairly new to python programing language and this year i challenged myself to build our project's app. We want the app to display certain features. To start with, this is our pseudo code : ' Inputs: Desired Max Temperature Tmax Intensity (in %) On or Off Tsurface Outputs LED0 LED1 LED2 LED3 LEDRED Relay1 Relay2 When Settings are changed If device is at 0% Power (0W) LED1, LED2, and LED3 are off If device is at 0 to 39% power (2.5 W) LED 1 is on, LED2 and LED3 are off If device is at 40 to 79% power (5 W) LED 1 and LED2 are on, LED3 is off If device is at 80 to 100% power (7.5 W) LED 1, LED2 and LED3 are on Ton = Tcycle * Intensity / 100% Continuously happen with timing signals If Tsurface >Tmax Relay1, Relay2 are off LEDRED is on Else At t=0+Ton/2 Turn Relay1 off At t=Tcycle-Ton/2 Turn Relay 1 on At t=Tcycle/2 - Ton/2 Turn Relay 2 on At t=Tcycle/2 + Ton/2 Turn Relay 2 off ' Python code ' from django.contrib import admin from django.urls import path, include from .views import (home,led_off,led_on, increase_temp,decrease_temp) urlpatterns = [ … -
Django Displaying Each User's Profile
I am building a website where there is a table at the homepage, and in that table there are people's names, numbers, their categories, the city they reside in, etc. I would like to create a link, that when a visitor clicks on any of the users' name, the visitor gets directed to that specific user's profile page. Right now, my code works partially. When I click any user, I get redirected to http://127.0.0.1:8000/profile/7/. That user ID number of "7" is the logged in user's ID. So no matter which user I click on, I get redirected to the profile page of the logged in user. Also, when I log out of the current user I am logged in to, I get this error message: "NoReverseMatch at / Reverse for 'profile_pk' with keyword arguments '{'pk': None}' not found. 1 pattern(s) tried: ['profile/(?P[0-9]+)/$']" Here is what I have done with my code so far: views.py def ustaprofil(request, pk=None): if pk: user = get_object_or_404(User, pk=pk) else: user = request.user args = {'user': user} return render(request, 'user.html', args) urls.py path('profile/<int:pk>/', views.ustaprofil, name='profile_pk'), models.py class Usta(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) gizlilik_sozlesmesi = models.BooleanField("Gizlilik Sozlesmesini Okudum Onayliyorum*" , null=True) sartlar_sozlesmesi = models.BooleanField("Sartlar ve Kosullar … -
Best way to store heavily related values in relational database
I am trying to efficiently store heavily related data in a relational database. Table A stores the field names. Table B stores the type and Table C stores the values. I came up with the structure and the mappings as shown in this figure: Now when I want to query data from this table, we have to perform 2 hits for each relation. Also, for every insert I need to hit DB thrice(one for each table). Is there a better way to store this kind of structure? Is there a standard way to save this in Django models? -
Django path converter raises SynchronousOnlyOperation
I'm migrating an existing WSGI server to ASGI and I'm running into a problem where ORM usage in path converters raises a SynchronousOnlyOperation exception. My converter code is something like this class ModelPkConverter: regex = r'\d+' model = MyModel def to_python(self, primary_key): try: return self.model.objects.get(pk=primary_key) except self.model.DoesNotExist: raise ValueError def to_url(self, instance): return f'{instance.pk}' So when I go to a URL like /myapp/<MyModel:my_model>/ I get django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async. Where exactly am I supposed to put sync_to_async? If I do it in the converter like this @sync_to_async def to_python(self, primary_key): ... The converter outputs a coroutine object instead of a MyModel instance so I get AttributeError when I attempt to use it. AttributeError: 'coroutine' object has no attribute 'my_attribute' Am I supposed to await it in the view? That would defeat the purpose of using converters. I can just do get_object_or_404 instead. Is there a solution that doesn't involve setting DJANGO_ALLOW_ASYNC_UNSAFE to True? At this point, I'm considering refactoring everything away from the converters and using <int:mymodel_id> everywhere instead. Is there another way? -
how to make list of group by clickable django
i made a group by list of items based on two fields class Product(models.Model): type_of_product = models.CharField(max_length=30,default="electric) made_in = models.CharField(max_length=10,choices=countries,default="UK") product= models.CharField(max_length=30) views.py def categories(request): lists = Product.objects.values('type_of_product ', 'made_in').annotate( total=Count('pk') ).order_by('type_of_product ', 'made_in') return render(request,'shop/categories.html',{'lists':lists}) it returns something like this type_of_product : electric , made_in:UK , total:20 type_of_product : accessory , made_in:USA , total:23 and so on i want to make lists of categories clickable , when i click on one of them , it takes me to all products with the same features , for example i click on type_of_product : accessory , made_in:USA , total:23 it shows a list of products (23) item which made in from USA and type of product is accessory <div class="grid grid-cols-1 gap-6 pt-3 pt-8 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 "> {% for i in lists %} <a href="{% url 'the link to products list' %}" class="transition transform cursor-pointer duration-400 hover:scale-105 hover:shadow-xl"> <div class="h-32 overflow-hidden rounded-tl-2xl rounded-tr-2xl room"></div> <div class="items-center p-2 rounded-bl-xl rounded-br-xl bglightpurple"> <div class="text-center rounded-lg" style="background: #534e70;"> <p class="inline textorange "><i class="bi bi-columns-gap"></i></p> <p class="inline text-white">{{i.type_of_product}}</p> </div> <div class="flex flex-wrap items-center justify-between mt-4 text-white"> <div class="text-sm"> <p class="inline ">{{i.product}}</p> <p class="inline px-1 text-sm bg-yellow-500 rounded-lg">{{i.total}}</p> </div> <div class="text-sm"> <p class="inline px-1 text-sm …