Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
PyCharm Cannot load Django project after last update
I just opened PyCharm to work on a small side-project. A django app that does some stuff (I think irrelevant to the problem.) I am on Tumbleweed Operating System: openSUSE Tumbleweed 20240517 KDE Plasma Version: 6.0.4 KDE Frameworks Version: 6.2.0 Qt Version: 6.7.0 Kernel Version: 6.8.9-1-default (64-bit) Graphics Platform: Wayland Processors: 12 × 12th Gen Intel® Core™ i7-1255U Memory: 31.0 GiB of RAM Graphics Processor: Mesa Intel® Graphics Manufacturer: LENOVO Product Name: 21C1002HGE System Version: ThinkPad L14 Gen 3 and I don'T know, maybe it's related to "the big tumbleweed update with kde6 and changing to wayland" or whether it's a pyCharm problem: The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/kevin/PycharmProjects/VocabelTrainer/manage.py", line 22, in <module> main() File "/home/kevin/PycharmProjects/VocabelTrainer/manage.py", line 13, in main raise ImportError( ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? (venv) shouldN't pycharm automatically start the venv that I'm working in? is it normal that it cannot find django if the venv isn't running -
404 found error for post request at backend
I am unable to make post request to backend side using react. Here is my auth file and error file: I am expecting to make a request at http://localhost:8000/api/v1/user/register/ But the site is making the request at: http://localhost:5173/user/register/ (404) How to set the post request url correct? -
Is there a better way to update all relation rows with `ForegnKey` relation in `Django ORM`
I have two models, one like this: class PhysicalSensor(models.Model): name = models.CharField(unique=True, max_length=255) def __str__(self) -> str: return self.name class Sensor(models.Model): physical_sensor = models.ForeignKey(PhysicalSensor, on_delete=models.RESTRICT, null=True, blank=True) So, when I want to add a PhisycalSensor record, I want to set the Sensor records to that. Right now I handle this in my Serializer class: class PhysicalSensorSerializer(ModelSerializer): sensors = SensorSerialiazer(required=False, many=True) class Meta: fields = ("__all__") model = PhysicalSensor def create(self, validated_data): sensors = validated_data.pop("sensors") ph_sensor = super().create(validated_data) for sensor in sensors: s = Sensor.objects.get(sensor["id"]) s.physical_sensor = ph_sensor s.save() and for edit of PhysicalSensor, I use the same thing in .update() method of my Serializer. Is there any batter way of doing this or a best practice for this ? -
"'BillInvoice' instance needs to have a primary key value before this relationship can be used" Error
I'm experiencing an issue with my Django project where I'm trying to create a BillInvoice and its associated BillLineItem instances. The error I'm encountering is: "'BillInvoice' instance needs to have a primary key value before this relationship can be used" Context: I have a form view (CreateInvoiceView) that handles the creation of invoices and their line items using a formset. The relevant parts of my code are as follows: This is my model.py Userprofile class UserProfile(models.Model): ROLE = [ ('Select Role', 'Select Role'), ('Admin', 'Admin'), ('CBUMT', 'CBUMT'), ('Pharmacist', 'Pharmacist'), ('Doctor', 'Doctor'), ('Nurse', 'Nurse'), ('Referral Provider', 'Referral Provider'), ('Member', 'Memeber'), ('Dependent', 'Dependent'), ] GENDER = [ ('None', 'None'), ('Male', 'Male'), ('Female', 'Female'), ] user = models.OneToOneField(User, on_delete=models.CASCADE) id_number = models.CharField(max_length=30, blank=True, null=True) is_medical_staff = models.BooleanField(default=False) role = models.CharField(max_length=50, choices=ROLE, default='CBUMT') gender = models.CharField(max_length=20, choices=GENDER, default='None') date_of_birth = models.DateField(blank= False, null=False, default=timezone.now) phone = models.CharField(max_length=20, blank=True, null=True) qualification = models.CharField(max_length=100, blank=True, null=True) bio = models.TextField(blank=True, null=True) profile_pic = models.ImageField(null=True, blank=True, upload_to='images/', default='img/placeholder.jpg') @property def age(self): today = date.today() age = today.year - self.date_of_birth.year - ((today.month, today.day) < (self.date_of_birth.month, self.date_of_birth.day)) return age def __str__(self): return str(self.user) + ' | ' + self.role **BillInvoice** class BillInvoice(models.Model): TYPE_CHOICES = [ ('Medicine', 'Medicine'), ('Auxillary', 'Auxillary'), ('Mixed', … -
Django Use two db in one model
I use RDS. The db have different schemas for Users and Products class Product(models.Model): id = models.AutoField(primary_key=True) class User(models.Model): id = models.AutoField(primary_key=True) DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql", "OPTIONS": {"options": "-c search_path=public"}, "NAME": config("DB_NAME", default=""), "USER": config("DB_USER_NAME", default=""), "PASSWORD": config("DB_PASSWORD", default=""), "HOST": config("DB_HOST", default="db"), "PORT": config("DB_PORT", default=""), }, "data": { "ENGINE": "django.db.backends.postgresql", "OPTIONS": {"options": "-c search_path=products"}, "NAME": config("DB_NAME", default=""), "USER": config("DB_USER_NAME", default=""), "PASSWORD": config("DB_PASSWORD", default=""), "HOST": config("DB_HOST", default="db"), "PORT": config("DB_PORT", default=""), }, } Can I create relation between this two tables from different db schemas? Or only one decision move Product table to default db? -
Sorted serializer data by group DJANGO RESTFRAMEWORK
My model: class VariantCombination(models.Model): product = models.ForeignKey(Product, related_name='variant', on_delete=models.CASCADE, null=True, verbose_name="Продукт") variant = models.ForeignKey(Variant, on_delete=models.CASCADE, null=True, blank=False, verbose_name="Варианты") variant_value = models.ForeignKey(VariantValue, on_delete=models.CASCADE, null=True, blank=False, verbose_name="Значение варианты") price = models.FloatField(default=None, verbose_name="Цена", null=True, blank=False) class Meta: verbose_name = "Вариант" verbose_name_plural = "Варианты" def __str__(self): return self.product.name My serialer: # Variant Combination Serializer class VariantCombinationSerializer(serializers.ModelSerializer): variant_name_id = serializers.IntegerField(source="variant.id", read_only=True) variant_name = serializers.CharField(source="variant.name", read_only=True) variant_value = serializers.CharField(source="variant_value.value", read_only=True) product_id = serializers.IntegerField(source="product.id", read_only=True) category_id = serializers.IntegerField(source="product.category.id", read_only=True) class Meta: model = VariantCombination fields = ['id', 'variant_name_id', 'variant_name', 'variant_value', 'price', 'product_id', 'category_id'] # Product serializer class ProductSerializer(serializers.ModelSerializer): category_id = serializers.IntegerField(source="category.id", read_only=True) category_name = serializers.CharField(source="category.name", read_only=True) brand_id = serializers.IntegerField(source="brand.id", read_only=True) brand_name = serializers.CharField(source="brand.name", read_only=True) currency_id = serializers.CharField(source="currency.id", read_only=True) currency = serializers.CharField(source="currency.name", read_only=True) images = ProductsImageSerializer(many=True, read_only=True) uploaded_images = serializers.ListField( child=serializers.ImageField(allow_empty_file=False, use_url=False), write_only=True ) product_variant = ProductVariantSerializer(source="product", many=True) variants = VariantCombinationSerializer(source="variant", many=True) class Meta: model = Product fields = ['id', 'category_id', 'category_name', 'brand_id', 'brand_name', 'currency_id', 'currency', 'uploaded_images', 'name', 'description', 'is_available', 'create_time', 'update_time', 'image', 'images', 'product_variant', 'variants'] My result now: My result now I need result: I need result thanks Sorted serializer data by group DJANGO RESTFRAMEWORK I want to sort by group serialer data. I want to sort by group serialer data. I want to sort by group … -
I can't seem to load data from mysql to django's templates
I've been trying for hours, and i can't seem to get data from mysql to django. i've checked everything, views, urls, the html files, admin etc. I have a submission in 5 hours so it'll be great help if i chould get some help i Tried changing function names, changing the views, the admin.py. Looked up for hours but couldnt find anything class Bus(models.Model): name = models.CharField(max_length=50) bus_no = models.CharField(max_length=10, primary_key=True) class Meta: db_table = 'bus' def bus_detail(request): # Retrieve all buses with bus_no ranging from 1 to 7 buses = Bus.objects.filter(bus_no__range=(1, 7)) # Pass the retrieved buses to the template context return render(request, 'bus-timings.html', {'buses': buses}) <table> <thead> <tr> <th>Bus Name</th> <th>Bus Number</th> </tr> </thead> <tbody> <!-- Loop through each bus and display its details --> {% for bus in bus %} <tr> <td>{{ bus.name }}</td> <td>{{ bus.bus_no }}</td> </tr> {% endfor %} </tbody> </table> -
Custon user form conflict in variables
Trying to use custom forms to use info from models, for signup, login, etc. models.py from django.db import models from datetime import datetime from django.contrib.auth.models import AbstractUser # error is in CustomUser, next line class CustomUser(AbstractUser): username = models.CharField(max_length=32, blank=False) date = models.DateField(default=datetime.now) email = models.EmailField(max_length=32, unique=True, blank=False) password = models.CharField(max_length=32, blank=False) forms.py from django.contrib.auth.forms import UserCreationForm, UserChangeForm # UpdateView from django.views.generic import CreateView class CustomUserCreationForm(UserCreationForm): class Meta(UserCreationForm.Meta): model = CreateView fields = ('username', 'email') class CustomUserChangeForm(UserChangeForm): class Meta: model = CreateView fields = ('username', 'email') class UserAdmin(UserCreationForm): class Meta(UserCreationForm.Meta): model = CreateView fields = ('username', 'email') Error displayed after successfully running runserver.: ERRORS: antelope.CustomUser.groups: (fields.E304) Reverse accessor 'Group.user_set' for 'antelope.CustomUser.groups' clashes wit h reverse accessor for 'auth.User.groups'. ups'. HINT: Add or change a related_name argument to the definition for 'antelope.CustomUser.groups' or 'auth.User.gro antelope.CustomUser.user_permissions: (fields. E304) Reverse accessor 'Permission.user_set' for 'antelope.CustomUser.user _permissions' clashes with reverse accessor for 'auth.User.user_permissions'. HINT: Add or change a related_name argument to the definition for 'antelope. CustomUser.user_permissions' or 'aut h.User.user_permissions'. auth.User.groups: (fields. E304) Reverse accessor 'Group.user_set' for 'auth.User.groups' clashes with reverse accessor f or 'antelope.CustomUser.groups'. ups'. HINT: Add or change a related_name argument to the definition for 'auth.User.groups' or 'antelope. CustomUser.gro auth.User.user_permissions: (fields. E304) Reverse accessor … -
django class based views, follow system
I want to use If statement and I use class based views. the problem is I don't know how to implement if statement in class based views here is the view: class ProfileView(DetailView): model = CustomUser template_name = 'profile.html' def get_context_data(self, *args, **kwargs): users = CustomUser.objects.all() context = super(ProfileView, self).get_context_data(*args, **kwargs) page_user = get_object_or_404(CustomUser, slug=self.kwargs['slug']) context["page_user"] = page_user return context I tried many time and i didn't work -
How to upload and store multiple images in Django 4
Django 4 Need user to be able to upload either an archive of images or just a few images at a time. Then these pages are numbered according to the order in which the user has placed them and stored in the database. Thus, when you open a page with images, there will be all the images just uploaded for this page in the correct order UPD: I would also be grateful if you could tell me how to rename files, change their extension, for example from .png to .jpg and in the path of saving in the model, for example, poster = models.ImageField(upload_to=‘posters/’, blank=False, null=False, verbose_name=‘Posters’) in the attribute upload_to add a value depending on what page the images are uploaded to. For example, if the page is called ‘opera’, the image path would be ‘posters/opera/1.jpg’, ‘opera/2.jpg’, etc. For the ‘Romeo and Juliet’ page it would be ‘posters/Romeo-and-Juliet/1.jpg.’ -
why recognize my models in an other app in django how can i call models in other app
from product.models import Product CART_SESSION_ID = 'cart' class Cart: def __init__(self, request): self.session = request.session cart = self.session.get(CART_SESSION_ID) if not cart: cart = self.session[CART_SESSION_ID] = {} self.cart = cart def __iter__(self): cart = self.cart.copy() for item in cart.values(): item['product'] = Product.objects.get(id=int(item['id'])) item['total'] = int(item['price']) * int(item['quantity']) yield item def unique_id_generator(self, id, color, size): result = f"{id} - {color} - {size}" return result def add(self, product, quantity, color, size,): unique = self.unique_id_generator(product.id, color, size) if unique not in self.cart: self.cart[unique] = { 'quantity': 0, 'price': str(product.price), 'color': color, 'size': size, 'id': str(product.id), } self.cart[unique]['quantity'] += int(quantity) self.save() def save(self): self.session.modified = True hi every one i have problem in my site i will write code Cartmodule session base in django but i have problem in my model in the other app in the other app i have create models but i dont fetch in my other app my error like is : invalid literal for int() with base 10: 'black' how can i fix this error hi every one i have problem in my site i will write code Cartmodule session base in django but i have problem in my model in the other app in the other app i have … -
[Nginx][Django] Cannot access the media files in production via Nginx
I am trying to access the media files using Nginx. The file exists in the directory: /usr/src/app/backend/media/profile/c4ebe33d-7da1-4a62-bb17-8da254d69b36, where the part profile/c4ebe33d-7da1-4a62-bb17-8da254d69b36 is created dynamically. The media root is: /usr/src/app/backend/media. I know the file exists cause I am able to see it in the container. This is my nginx config: proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=STATIC:10m inactive=7d use_temp_path=off; upstream backend { server backend:8000; } upstream frontend { server frontend:3000; } server { listen 80 default_server; server_name _; server_tokens off; gzip on; gzip_proxied any; gzip_comp_level 4; gzip_types text/css application/javascript image/svg+xml; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection 'upgrade'; proxy_set_header Host $host; proxy_cache_bypass $http_upgrade; client_max_body_size 100M; location /_next/static { proxy_cache STATIC; proxy_pass http://frontend; } location /static { proxy_cache STATIC; proxy_ignore_headers Cache-Control; proxy_cache_valid 60m; proxy_pass http://frontend; } location /media/ { autoindex on; alias /usr/src/app/backend/media/; } location / { proxy_pass http://frontend; } location /api/ { proxy_pass http://backend; proxy_set_header Host $http_host; } } When trying to access the file I get 404. This is the link to file: http://localhost/media/profile/c4ebe33d-7da1-4a62-bb17-8da254d69b36/da258fe5-f57c-44d2-94cf-00bef250b86d.png I tried modifying nginx, cause I think this is the reason, but without success. -
when I console.log fetched data it appears as undefined but it appears when I refresh
I have this function in react to fetch the data from my django api: const [filterData, setFilterData] = useState([]); const fetchFilterData = async () => { const filter_url = 'http://127.0.0.1:8000/api/filters/' try { const response = await fetch(filter_url) const result = await response.json(); setFilterData(result) } catch (error) { console.error('error fetching data: ', error); } } and when I try to console.log the data it is show as undefined at first but if I change something in the code (like add a white space or a new line) and save the fetched data appears and everything works fine but the issue is that I can't render that data or pass it down as a prop to other components here's the react useEffect hook: useEffect(() => { fetchData(); fetchFilterData(); }, []); and I have tried logging the data in several ways but no use it always returns undefined at first here are several ways I have tried: inside fetchFilterData function: if (filterData) {console.log(filterData.all_blocks) } else { console.log("this data is undefinde") } *and this has return undefinde as well and I still don't know why * passing it down as a prop to another component: return ( {filterData && <DropDown items={filterData.all_blocks} /> } ); … -
Django Deployment failed during build process on railway
When I deploy my Django app on rail after adding nessary variables and updated file everything done unless this failed do u know why and how to fix it Build logs on railway;here the problem how can i fix it"#8 [4/5] RUN pip install -r requirements.txt #8 0.343 /bin/bash: line 1: pip: command not found #8 ERROR: process "/bin/bash -ol pipefail -c pip install -r requirements.txt" did not complete successfully: exit code: 127 [4/5] RUN pip install -r requirements.txt: 0.343 /bin/bash: line 1: pip: command not found Dockerfile:15 13 | # build phase 14 | COPY . /app/. 15 | >>> RUN pip install -r requirements.txt 16 | 17 | ERROR: failed to solve: process "/bin/bash -ol pipefail -c pip install -r requirements.txt" did not complete successfully: exit code: 127 Error: Docker build failed I should note that when I try to run this command locally on my project file “ py manage.py collectstatic” some css file failed is it because that ? If it not plz tell me how can fix it -
Nothing happens when transferring data to the database
I have a problem. I'm new to django. And so the error lies in the fact that nothing happens during the data transfer. The database is not being updated. I will be very grateful for your help! this is code: registration/urls.py: from django.contrib.auth import views as auth_views from django.urls import path from . import views urlpatterns = [ path('/register', views.register, name='register'), ] registration/views.py: from django.shortcuts import render from django.contrib.auth import login, authenticate from django.shortcuts import render, redirect from .forms import RegistrationForm from django.shortcuts import render, redirect def sign_up(request): if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): user = form.save() login(request, user) return redirect('home') else: form = RegistrationForm() return render(request, 'registration/register.html', {'form': form}) def register(): print("hello!") urls.py(In the project itself): from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static from django.contrib.auth import views as auth_views from django.urls import path urlpatterns = [ path('admin/', admin.site.urls), path('', include('main.urls')), path('news/', include('news.urls')), path('accounts/', include('django.contrib.auth.urls')), ] urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) register.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Регистрация</title> </head> <body> <h1>Регистрация</h1> <form method="post" action="{% url 'register' %}"> {% csrf_token %} {{ form.email }} {{ form.password1 }} {{ form.password2 }} <button type="submit">Зарегистрироваться</button> </form> </body> </html> forms.py: from … -
Data Flow in Django Rest Framework?
I have recently started learning Django Rest Framework, and hit a little roadblock trying to understand the data flow in DRF. From what I understand, views take in a web request and return a web response, so they are the first component in the DRF data flow right? (after the urls). Then what's the second step? Views generally refer to a serializer, so does our serializer get executed next. If so, why not our model because serializer is used to convert complex data types such as model instances into JSON. I have this and a couple of related questions after going through the DRF docs tutorial part-4. CONTEXT: In the docs we are creating code snippets and now we want to associate users with the snippets they created. We follow the steps below in the following order to achieve this: Below in the tutorial, we are creating a serializer to represent a user. How does a serializer help in representing a user, aren't serializers used to convert data? 1 Adding endpoints for our User models Now that we've got some users to work with, we'd better add representations of those users to our API. class UserSerializer(serializers.ModelSerializer): snippets = serializers.PrimaryKeyRelatedField(many=True, queryset=Snippet.objects.all()) … -
Django Model Form, seems like there is an anomaly where my user creation form's clean_username method is not throwing a ValidationError when it should
Background I have a custom User model that I have extended from BaseUserManager and AbstractBaseUser. Similarly, I have a custom sign-up form that I've extended from UserCreationForm (all these custom items are extended from django.contrib.auth). The custom UserCreationForm I've made has a method called clean_username() that checks for usernames that do not have any alpha-numerical characters (-@, --_, +@-_, etc.) and throws a ValidationError if that is the case (aside: the method also checks for usernames that, when slugified, would result in non-unique slugs). Problem When I test the aforementioned ValidationError, it still is somehow returning the form as valid, which causes the rest of my view's logic to run, which causes the User Model's clean() method to run, and in the User Model's clean() method, I have the same checks I have in the form's clean_username() method (for User's created without using this particular form). These checks throw a ValueError, which is not ideal because I need the form to be re-rendered with the proper ValidationError message so that users can fix what's wrong and still sign up. None of this makes sense. I've put print messages in my clean_username() method so that I know for sure the branch … -
Cant run django-admin in windows11
I was trying to start a new project in django and ran into this error.enter image description here i already created venv and installed django with venv activated.But even after successfull installlation of django i can't run django-admin command (it gives above error). OS: Windows 11. python: 3.13.0a6 Django: 5.0.6 i was expecting to create a new django project using django-admin startproject ... -
I want to add CMS feature in my current website, which lib would you recommend?
Curretly, I want to add CMS feature in my current website, which lib would you recommend? Hi, I already using Django build a simple website, but don't have CMS feature yet. Recently, I want to add CMS feature in the website. Following is my search result, which would you recommend me to use? Thanks a lot. Wagtail 2.django CMS 3.Mezzanine 4.FeinCMS 5.Django Suit Thanks a lot. If you can share the experience, I will very appreciate. -
Displaying images from static folder in Django
We have a problem with displaying images on html pages. We create graph, save it and then pass it's url to html page via context, but django can't find the picture (Error 404 Not Found). There's no model to store urls as there's no need to access them later. Here's our views.py: def simple_upload(request): if request.method == 'POST' and request.FILES['file']: myfile = request.FILES['file'] fs = FileSystemStorage() filename = fs.save(myfile.name, myfile) uploaded_file_url = fs.url(filename) forecast, clean_df, graph_url = data_processing(myfile, filename) forecast = forecast.reset_index() cols_fc = forecast.columns.tolist() forecast[cols_fc[0]] = forecast[cols_fc[0]].dt.date forecast = forecast.values.tolist() clean_df = clean_df.reset_index() cols_df = clean_df.columns.tolist() clean_df[cols_df[0]] = clean_df[cols_df[0]].dt.date clean_df = clean_df.values.tolist() context = { 'filename': filename, 'cols_fc': cols_fc, 'forecast': forecast, 'cols_df': cols_df, 'clean_df': clean_df, 'graph_url': graph_url, } return render(request, 'project/results.html', context) return render(request,'project/example.html') Html document (result.html): <body> {% load static %} <p>{{ filename }}</p> <p>------------------------------------------------------</p> <div>{{ graph_url }}</div> <img src="{% static '{{ graph_url }}' %}"> <p style="color:red"> ------------ VALUES -----------</p> <p>{{ cols_df }}</p> {% for c in clean_df %} <p>{{ c.0 }} || {{ c.1 }}</p> {% endfor %} <p style="color:blue">------------- FORECAST -------------</p> <p>{{ cols_fc }}</p> {% for f in forecast %} <p>{{ f.0 }} || {{ f.1 }}</p> {% endfor %} </body> Function that creates, saves the … -
Mock patching an endpoint unittest that makes several requests to third party
I have a single endpoint written using django ninja. This endpoint executes a crawler that performs several requests. The sequence of requests has 3 different routines depending on whether or not the crawler already has valid login credentials in its session. I want to write e2e tests for these 3 routines and each of the possible exceptions that might be raised. The problem is there are up to 6 different requests in one sequence to a few different pages with a few different payloads. All I can think to do is patch each of these requests individually for each test but that is going to get ugly. My other thought is that I should just be satisfied with sufficient unit test coverage of the individual components of my crawler controller. Here is simplified code illustrating my issue api.py # This is what I want to test @api.get("/data/{data_id}") def get_data(request, data_id): controller = SearchController(crawler=Crawler, scraper=Scraper) response_data = controller.get_data(data_id) return api.create_response(request=request, data=response_data, status=200) # I have 5 of these right now and more to come @api.exception_handler(ChangePasswordError) def password_change_error_handler(request): data = { "error": "Failed to login", "message": "Provider is demanding a new password be set.", } return api.create_response(request=request, data=data, status=500) crawler.py Crawler(BaseAPI): def … -
KeyError error at /registration/register/ 'email'
I have a problem. When clicking on the link http://127.0.0.1:8000/accounts/register / returns the KeyError error at /accounts/register/ 'email'. I program in django in pycharm. I want to point out that there is a specific 'email' error here! this is code: registration/urls.py: from django.contrib.auth import views as auth_views from django.urls import path from . import views urlpatterns = [ path('/register', views.register, name='register'), ] registration/views.py: from django.shortcuts import render from django.contrib.auth import login, authenticate from django.shortcuts import render, redirect from .forms import RegistrationForm from django.shortcuts import render, redirect def sign_up(request): if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): user = form.save() login(request, user) return redirect('home') else: form = RegistrationForm() return render(request, 'registration/register.html', {'form': form}) def register(): print("hello!") urls.py(In the project itself): from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static from django.contrib.auth import views as auth_views from django.urls import path urlpatterns = [ path('admin/', admin.site.urls), path('', include('main.urls')), path('news/', include('news.urls')), path('accounts/', include('django.contrib.auth.urls')), ] urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) register.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Регистрация</title> </head> <body> <h1>Регистрация</h1> <form method="post" action="{% url 'register' %}"> {% csrf_token %} {{ form.email }} {{ form.password1 }} {{ form.password2 }} <button type="submit">Зарегистрироваться</button> </form> </body> </html> forms.py: from … -
How to reverse a URL in format namespace:view:endpoint?
I have a Django project with the following urlpattern defined on project level: urlpatterns = [ path('', include(('ws_shopify.urls', 'ws_shopify'), namespace='shopify')), ] The file ws_shopify.urls defines the following urlpatterns: urlpatterns = [ path('api/shopify/', ShopifyWebhookAPIView.as_view(), name='webhook'), ] The class ShopifyWebhookAPIView defines the following endpoint: from rest_framework.views import APIView class ShopifyWebhookAPIView(APIView): @action(detail=False, methods=['post'], url_path='(?P<webshop_name>.+)/order_created', name='order-created') def order_created(self, request: Request, webshop_name=None): return Response({'message': f'Order created for {webshop_name}'}) My question is: What is the correct name of this endpoint to be used in a test case using reverse()? I am trying this now: class WebhookTestCase(TestCase): def test_that_url_resolves(self): url = reverse('shopify:webhook:order-created', kwargs={'webshop_name': 'my-shop'}) self.assertEqual(url, '/api/shopify/my-shop/order_created') But this fails with the following error message: django.urls.exceptions.NoReverseMatch: 'webhook' is not a registered namespace inside 'shopify' Not sure if it's relevant or not, this is how ws_shopify.apps looks like: from django.apps import AppConfig class ShopifyConfig(AppConfig): name = 'ws_shopify' -
django admin causing latency to load instances , the models have a related hierarcy
Case: I have relationships: 1 Distributor:M resellers, 1 reseller: M customers, 1customer: M domains, 1 Domain: M mailboxes. The model admin panel is taking a long time to load the objects for all the model admin. Does the default django return queryset return all the instances or load only that required in page 1 and then page2 on click etc. Why is there latency? Checked the pagination related document. But where does it say that all the objects in the queryset are retrieved at a time or only relevant to that page at a time? -
Django: How to use CURSOR .. WITH HOLD in Django ORM
In Django orm we have queryset.iterator https://docs.djangoproject.com/en/5.0/ref/models/querysets/#iterator that uses under the hood Postgres cursor www.postgresql.org/docs/current/sql-declare.html in case we using Postgres as a database of course. By default Django uses it with WITHOUT HOLD setting, which is default in Postgres, that why it is also default in Django. Question is - is it possibe to use django iterator() with WITH HOLD setting (not default) without switching to raw SQL somehow? Thank u