Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can't make Telegram WebApp Validation work using python
I am unable to validate data that Telegram sent to my WebApp.. import hashlib import hmac import json import typing from urllib.parse import unquote def parse_init_data(init_data: str) -> typing.Dict: return dict(param.split("=") for param in init_data.split("&")) def parse_user_data(user_data: str) -> dict: return json.loads(unquote(user_data)) def _extract_hash_value(init_data: str) -> str: return parse_init_data(init_data)["hash"] def generate_secret_key(telegram_bot_token: str, c_str: str = "WebAppData") -> str: c_str_enc = c_str.encode() token_enc = telegram_bot_token.encode() return hmac.new(token_enc, c_str_enc, digestmod=hashlib.sha256).hexdigest() def validate(init_data: str, secret_key: str) -> bool: hash_ = _extract_hash_value(init_data) unquote_init_data = unquote(init_data) sorted_init_data = sorted( [chunk.split("=") for chunk in unquote_init_data.split("&") if chunk[: len("hash=")] != "hash="], key=lambda x: x[0], ) sorted_init_data_str = "\n".join([f"{key}={val}" for key, val in sorted_init_data]) init_data_enc = sorted_init_data_str.encode() secret_key_enc = secret_key.encode() data_check = hmac.new(init_data_enc, secret_key_enc, digestmod=hashlib.sha256).hexdigest() return hmac.compare_digest(hash_, data_check) this code is from github. It is intended to validate data coming from Telegram to my WebApp.. I have passed all necessary things.. extracting user data from Telegram Sent data is working. But validating that data is from Telegram failing. This is initData I got query_id=AAHkHFkqAAAAAOQcWSqv8eyu&user=%7B%22id%22%3A710483172%2C%22first_name%22%3A%22Ro%27zmat%22%2C%22last_name%22%3A%22Otajonov%22%2C%22username%22%3A%22OtajonovR%22%2C%22language_code%22%3A%22en%22%2C%22is_premium%22%3Atrue%2C%22allows_write_to_pm%22%3Atrue%7D&auth_date=1713215281&hash=c7907965154661f6f322d02e4a97086568e033980818396b623649ba3a062685 and this code is my django view that trying to validate using above functions: from django.shortcuts import render from .webapp_auth import parse_init_data, parse_user_data, validate, generate_secret_key from django.contrib.auth import get_user_model User = get_user_model() def business_settings_view(request): … -
Most Efficient Way To Add Email Field of Auth User Model From A ManyToMany Field When Sending Email
In the code below I would like to add the email of the user's email field directly into the recipient's variable below in the notification function. How would one achieve this? class Pass(models.Model): guest_name = models.CharField(max_length=128,blank=False,verbose_name="Guest") date = models.DateField(blank=False,null=False,verbose_name='Date') area = models.CharField(max_length=128,blank=False,verbose_name='Area(s)') member_name = models.CharField(max_length=128,blank=False,verbose_name="Member") member_number = models.IntegerField(blank=False) phone = models.CharField(max_length=14,blank=False,null=False) email = models.EmailField(max_length=128,blank=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='pass_users', blank=True, null=True, ) managers = models.ManyToManyField( settings.AUTH_USER_MODEL, related_name='passes', blank=True, limit_choices_to = {'is_active': True}) def __str__(self): return '%s' % (self.guest_name) def get_absolute_url(self): return reverse('guestpass:pass_detail', kwargs={'pk':self.pk}) @receiver(post_save, sender=Pass) def notification(sender, instance, **kwargs): if kwargs['created']: subject = 'New Guest Pass' message = '%s guest pass has been created.' %(instance.guest_name) sender = 'noreply@email.com' recipients = [?] send_mail( subject, message, sender, recipients, fail_silently=False, ) -
Should model fields be tested in Django?
class Author(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) date_of_birth = models.DateField(null=True, blank=True) date_of_death = models.DateField('Died', null=True, blank=True) MDN says: You don't need to explicitly test that first_name and last_name have been stored properly as CharField in the database because that is something defined by Django ... However you should check the text used for the labels (First name, Last name, Date of birth, Died), and the size of the field allocated for the text (100 chars), because these are part of your design and something that could be broken/changed in future. If I wanted to follow that advice, I would not write a test that tests that the field only accepts 100 characters, since that would mean testing Django's behavior. Instead, I would write a test that tests that max_length indeed equals 100. This test could look something like this: def test_max_length(self): self.assertEqual(models.Author._meta.get_field('first_name').max_length, 100) My feeling is that this test would basically be the same as testing that I wrote what I wrote. Of course, if a wrong max_length breaks some other piece of code, that should be tested, but it should be tested in that other piece of code. What are the best practices for testing Django model fields? … -
Django Python - What does _ do after a variable name
Sorry for my poor explanation but I'm reviewing my professor's code like this: user, _ = User.objects.get_or_create( name = serializer.data['name'], email = serializer.data['email'], password = make_password(serializer.data['password'])) when I remove the ", _" from that I can't access the objects (eg: name) of it. I was doing "user.name" but I cant without the ", _" can someone explain why that is. It's my first time here in in SO hehe I wanna access the name field through the user where I assigned the object I created -
Django HttpReponse: can't change file name (XMLHttpRequest)
I am trying to implement a file download feature via an XMLHttlpRequest. The response is formed as follows: response = HttpResponse(entries, content_type='application/text charset=utf-8') response['Content-Disposition'] = f'attachment; filename={self.title}.docx' So, the title should be something like 'Book.docx'. Instead, on every download I get a UUID-like title that is different, wrong, and has no extension, e.g. 'b691dac0-9498-414f-9c5b-a96223998b76'. Encoding the title with urlquote or .encode() doesn't help. -
Django - Need guidance on filtering data by keywords
In my web-app project, I have a page for advanced search. Initially, all the items from db should be displayed on front-end. From admin interface, for each item I have added keywords separated by comma. What I want to do is to filter the items on FE based on those keywords. Example: the wine has keywords like: red, dry . When I click on one of those options on front-end, the corresponding wines should be shown. I have created the template, added views and some javascript but now I'm stuck and I don't understand where the logic lacks. Here is the template piece: <div class="dropdown"> <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-bs-toggle="dropdown" aria-expanded="false"> Filter </button> <ul class="dropdown-menu" aria-labelledby="dropdownMenuButton" id="filterOptions"> <li><a class="dropdown-item" href="#" data-keyword="red">Red</a></li> <li><a class="dropdown-item" href="#" data-keyword="sparkling">Sparkling</a></li> <li><a class="dropdown-item" href="#" data-keyword="white">White</a></li> <li><a class="dropdown-item" href="#" data-keyword="sweet">Sweet</a></li> <li><a class="dropdown-item" href="#" data-keyword="dry">Dry</a></li> <li><a class="dropdown-item" href="#" data-keyword="citrus">Citrus</a></li> </ul> </div> <section class="products section-padding"> <div class="container"> <div class="row"> {% for wine in page_obj %} <div class="col-lg-4 col-12 mb-3"> <div class="product-thumb"> <a href="product-detail.html"> <img src="{{ MEDIA_URL }}{{ wine.image.url }}" class="img-fluid product-image" alt=""> </a> <div class="product-info d-flex"> <div> <h5 class="product-title mb-0"> <a href="product-detail.html" class="product-title-link">{{ wine.name }}</a> </h5> <p class="product-p">{{ wine.description }}</p> </div> </div> </div> </div> {% endfor %} … -
Django. 'GroupDetailView' object has no attribute 'object'
I try create AddMembersForm to Group in my app. 'GroupDetailView' object has no attribute 'object' class GroupDetailView(DetailView): model = Group context_object_name = 'group' template_name = 'rooms/group_detail.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['form'] = AddGroupMemberForm(group_id=self.object.id) context['members'] = GroupMembers.objects.filter(group=self.object) #Download all members return context def post(self, request, *args, **kwargs): form = AddGroupMemberForm(request.POST, group_id=self.object.id) if form.is_valid(): new_member = form.save(commit=False) new_member.group = self.get_object() new_member.save() return redirect(self.get_object().get_absolute_url()) else: return self.render_to_response(self.get_context_data(form=form)) ----------------------------------------------------------------------------------- class Group(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='creator_group', on_delete=models.CASCADE) name = models.TextField(max_length=50) description = models.TextField(max_length=500) def __str__(self): return self.name def get_absolute_url(self): return reverse('group_detail', kwargs={'pk': self.pk}) class GroupMembers(models.Model): group = models.ForeignKey(Group, on_delete=models.CASCADE, related_name='membership') user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='group_membership') role = models.TextField(max_length=30, default='Członek grupy') time_release = models.DateTimeField(default=timezone.now) def __str__(self): return f'{self.user.username} należy do {self.group.name}' I want to add users to my groups (the group founder will have this option). -
Issue with session authentication not being preserved across calls from React frontend to Django backend
I have the following code: LoginPage.js: import React from 'react'; import axios from 'axios'; import { useNavigate, Navigate } from 'react-router-dom'; import { Button, Grid, TextField } from '@mui/material' import DisplayAppBar from './DisplayAppBar'; export default function LoginPage() { const [username, setUsername] = React.useState(''); const [password, setPassword] = React.useState(''); const navigate = useNavigate(); const handleLogin = async (e) => { e.preventDefault(); try { axios.post('http://localhost:8000/login/', { username: username, password: password }).then((response) => { // navigate('/home'); // Navigate to home page axios.get("http://localhost:8000/check-login-status/") .then(response => { console.log(response.data); }) .catch(error => { console.log(error); // return <Navigate to="/" />; }) }).catch(error => { console.error(error); }); } catch (error) { console.error(error); } } return ( <div> <DisplayAppBar /> <Grid container direction="column" justifyContent="center" alignItems="center" spacing={2} > <Grid item> <TextField required label="Username" variant="outlined" id="usernameField" onChange={(e) => setUsername(e.target.value)}/> </Grid> <Grid item> <TextField required label="Password" variant="outlined" id="passwordField" onChange={(e) => setPassword(e.target.value)}/> </Grid> <Grid item> <Button variant="outlined" onClick={handleLogin}>Login</Button> </Grid> </Grid> </div> ) }; urls.py: from django.urls import path from rest_framework.urlpatterns import format_suffix_patterns from TeamData import views urlpatterns = [ path('club/', views.ClubListCreate.as_view()), path('club/<int:pk>/', views.ClubDetail.as_view()), path('swimmer/', views.SwimmerListCreate.as_view()), path('swimmer/<int:pk>/', views.SwimmerDetail.as_view()), path('user/', views.UserListCreate.as_view()), path('user/<int:pk>/', views.UserDetail.as_view()), path('login/', views.LoginView.as_view(), name='login'), path('logout/', views.LogoutView.as_view(), name='logout'), path('signup/', views.UserListCreate.as_view(), name='signup'), path('check-login-status/', views.CheckLoginStatus.as_view(), name='check-login-status'), ] urlpatterns = format_suffix_patterns(urlpatterns) views.py: from django.shortcuts import render from … -
What is the right way to run github actions for my django project on ec2?
I have a django project that's hosted on ec2. Everytime I want to update my application I have to push the code from vscode, pull it from my server, reload nginx, and restart uvicorn. I've been doing this every single time but I want to automate it with github actions. Am I supposed to have following commands in my yml fie or is there a better way to do this: cd myproject/myproject git pull origin main sudo systemctl reload nginx sudo systemctl restart uvicorn -
Efficient way to order Annotate field in DRF
I have three models in models.py, class AAA(models.Model): name = models.CharField(max_length=300, null=False, blank=False) class BBB(models.Model): aaa = models.ForeignKey(AAA, on_delete=models.CASCADE, null=False, blank=False) content = models.CharField(max_length=300, null=False, blank=False) class CCC(models.Model): aaa = models.ForeignKey(AAA, on_delete=models.CASCADE, null=False, blank=False) name = models.CharField(max_length=300, null=False, blank=False) and I want to order in views.py, class AAAListCreateView(generics.ListAPIView): class AAAPagination(CursorPagination): page_size = 2 queryset = ShortForm.objects.all().annotate( b_count=Count("bbb", distinct=True), c_count=Count("ccc", distinct=True), total=F('b_count')+('c_count') ) serializer_class = AAAListSerializer pagination_class = AAAPagination filter_backends = [DjangoFilterBackend, OrderingFilter] filterset_class = AAAListFilterSet ordering_fields = ['b_count', 'c_count', 'total'] ordering = 'b_count' The problems that I want to ask are... I want to descending all of my ordering_fields. Descending order without specifying -b_count or -c_count or -total. In views.py, I annotate all of my ordering_fields. But I think it is not efficient way because it fetches all sorting annotate fields. -
Django.core.exceptions.SuspiciousOperation when saving locally created csv file to s3 bucket
I need to create a csv report with django python and then save it to a FileField on a model. The filefield stores it to a secure amazon bucket. This is the logic I am using for the model: class MyModel(models.Model): created_on = models.DateTimeField(auto_now_add=True) the_file = models.FileField(blank=True,null=True,upload_to='some/dir/') def save(self, *args,**kwargs): super().save(*args,**kwargs) _access_key = settings.FINANCE_ACCESS _access_secret = settings.FINANCE_SECRET _access_bucket = settings.FINANCE_BUCKET s3 = boto3.client('s3', aws_access_key_id=_access_key, aws_secret_access_key=_access_secret) try: if self.the_file: _the_file_content = default_storage.open(self.the_file.name).read() s3.put_object(Body=_the_file_content,Bucket=_access_bucket,Key=self.the_file.name) except Exception as e: print(type(e),e) Using the admin site to upload a file, then everything works as expected. Things start to get tricky when I create the csv file and try to save the model programatically from the view. This is what I am doing: def create_and_save_the_file(): from tbkpayments.models import MyModel import os,csv,tempfile,sys _add_random_line = ['this','is','a','line'] csv_file_name='file.csv' csv_file_path = os.path.join(tempfile.gettempdir(), csv_file_name) csv_file = open(csv_file_path, 'w') csv_writer = csv.writer(csv_file) # add lines to the file csv_writer.writerow(_add_random_line) csv_writer.writerow(_add_random_line) csv_writer.writerow(_add_random_line) print(csv_file) print() csv_file.close() # We create the model to store the file _model=MyModel.objects.create() with open(csv_file_path, 'r') as f: data = f.read() _model.the_file.save(csv_file_path,data) f.close() //// And the exception that I am getting is: Traceback (most recent call last): File "<console>", line 1, in <module> File "<console>", line 20, in create_and_save_the_file File "/home/kenny/Projects/backend/virtenvs/venv/lib/python3.8/site-packages/django/db/models/fields/files.py", … -
im having trouble creating a dropdown navbar for my e-comm site using django
so my plan is to use a for loop to show all the possible categories instead of doing it manually used chatgpt but didnt help. nav_bar.html(manually): <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" id="navbarDropdown" href="#" role="button" data-bs-toggle="dropdown" aria-expanded="false">Shop</a> <ul class="dropdown-menu" aria-labelledby="navbarDropdown"> <li><a class="dropdown-item" href="{% url 'category_summary' %}">All Categories</a></li> <li><hr class="dropdown-divider" href=""/></li> <li><a class="dropdown-item" href="{% url 'category' 'books' %}">Books</a></li> </ul> </li> this is trying to use a for loop: <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" id="navbarDropdown" href="#" role="button" data-bs-toggle="dropdown" aria-expanded="false">Shop</a> <ul class="dropdown-menu" aria-labelledby="navbarDropdown"> <li><a class="dropdown-item" href="{% url 'category_summary' %}">All Categories</a></li> <li><hr class="dropdown-divider" href=""/></li> {% for category in categories %} <li><a class="dropdown-item" href="{% url 'category' category|slugify %}">{{ category }}</a></li> {% endfor %} </ul> </li> also created a view for the nav_bar.htlm page where i collect all the categories: def sent_data(request): categories = Category.objects.all() return render(request, 'nav_bar.html', {'categories': categories}) -
Containerize django rest framework server with django-auth-toolkit
I'm building an API for a condominium management app. Currently, I'm using Django OAuth Toolkit for user authentication. I've set up OAuth2 and the API server in the same place. My current workflow involves running the server and accessing /o/applications/ to register the app, then retrieving the client_id and client_secret and putting them into a .env file, and finally restarting the server. However, when I use Docker to containerize it, an issue arises because the container is already running and I can't access to edit the .env file anymore. I've been considering creating the app directly in the code and then storing the client_id and client_secret in Redis. If I separate OAuth2 and the API into two separate servers, my CustomUserModel would need to be in both servers. Do you have any suggestions for this scenario? -
How to filter foreign key for using ModelMultipleChoiceFilter in DRF?
I'm getting trouble with using ModelMultipleChoiceFilter in DRF. First, I have three models. # JUST STRUCTURE class A -> fields : [user:User] class B -> fields : [a:A(related_name="b"), c:C] class C -> fields : [name:string] And I want to filter with C's names (multiple choice) in class A. So... in views.py, class ShortFormListCreateView(generics.ListCreateAPIView): queryset = A.objects.all() filter_backends = [DjangoFilterBackend] filterset_class = AFilterSet and in filters.py, class AFilterSet(FilterSet): aa = filters.ModelMultipleChoiceFilter( field_name='b__c__name', to_field_name='name', lookup_expr='in', queryset=C.objects.all(), method='filter_cc', widget=CSVWidget, ) class Meta: model = ShortForm fields = ['aa'] def filter_cc(self, queryset, name, value): c_ids = [v.id for v in value] if value: queryset = queryset.filter(b__c__in=c_ids).distinct() return queryset It worked but I think it is not efficient way. Is there any solutions? -
How can I use nextjs with the Django
I started coding by using the python, When I surfed on internet, I get to know about Django. I used it very well and was easier to edit as this was generating pages dynamically. Now, I am Exploring about the nodejs and nextjs framework. I think it is good combination of both Django and Nextjs so that I can get speed as well as security. I want to know how can I integrate nextjs into Django. -
Router in router
I'm doing a project using Cookiecutter Django. I have urls and api_router.py in config. I want to add another url in 'api/' but I can't do that. I want to see the url in 'api/' like: { "users": "http://localhost:8000/api/users/" } I tried use registry but doesn't work. I have api_router.py: router = DefaultRouter() if settings.DEBUG else SimpleRouter() router.register("users", UserViewSet) router.registry.extend(product_router.registry) print(router.registry) app_name = "api" urlpatterns = router.urls and products/urls.py: router = SimpleRouter() router.register('products', ProductViewSet) urlpatterns = [ path('', include(router.urls)) ] and then, in the main urls: # API URLS urlpatterns += [ # API base url path("api/", include("config.api_router")), # DRF auth token path("auth-token/", obtain_auth_token), path("api/schema/", SpectacularAPIView.as_view(), name="api-schema"), path( "api/docs/", SpectacularSwaggerView.as_view(url_name="api-schema"), name="api-docs", ), ] So, I want to have different endpoints in localhost:8000/api/. -
Django - Downloading someone's images with an API
Hello i am developing a blog project in django. For each post there are images attached to it I want to share my project with some friends ( by them cloning the github repo ), but don't want them to download all the images. So i have made a new app on my project, an API with django-rest-framework that allow them to get the list of the images from my project Once someone get the list, it create new instances of Post and ImagePost in the DB, based on the json value They get the new instance in their DB, but they don't get the images, they only get the filepath I have no idea how to give them the images using the API, and make the images goes into their project. Thank you So for my models: class Post(models.Model): title = models.CharField(max_length=250) body = models.TextField() author = models.ForeignKey(User, related_name='blog_posts', on_delete=models.CASCADE) images = models.ManyToManyField(ImagePost, related_name='images', blank=True) class ImagePost(models.Model): image = models.ImageField(upload_to='blog_posts/', blank=True) And my API classes : class PostList(ListAPIView): queryset = Post.objects.filter(archived=False) serializer_class = PostSerializer class ImagePostList(ListAPIView): queryset = ImagePost.objects.all() serializer_class = ImagePostSerializer class ImagePostSerializer(ModelSerializer): class Meta: model = ImagePost fields = ["id", "image" ] The urls : path('post/list/', views.PostList.as_view(), … -
Troubleshooting AUTH_USER_MODEL Migration Error in Django App
I am working on a Django application where I've set up **AUTH_USER_MODEL **with the name **User **for authentication purposes. However, when I tried to run migrations, I encountered the following error: django.db.utils.OperationalError: (1005, 'Can't create table myAppDjango.django_admin_log (errno: 150 "Foreign key constraint is incorrectly formed")'). Could someone assist me in properly generating my model and Django migrations to resolve this issue? i used this commande to migrate model: python manage.py makemigrations python manage.py migrate -
How can i optimizate Djnago ORM request?
how can optimize the ORM request, getting the GDD takes a lot of time. I think problem with subquery, but through realation "commune__communemeteo" it takes even longer, (communemeteo about 1 million). communes = communes.filter( communeattribute__date__year=year, communeattribute__date__month=month, communeattribute__date__day__range=( days.get("start_date"), days.get("end_date"), ), ) gdd_subquery = ( CommuneMeteo.objects.filter( date__range=(start_date, end_date), commune_id=OuterRef("id") ) .values("commune_id") .annotate(gdd=Sum((F("temp_min") + F("temp_max")) / Value(2) - Value(TBASE))) .values("gdd")[:1] ) communes = communes.annotate( plant=Value(f"{plant}", output_field=CharField()), size=Sum(F("communeattribute__planted_area"), output_field=FloatField()), gdd=Subquery(gdd_subquery, output_field=FloatField()), ) ``` -
How to return the error in JSON format instead of HTML in REST framework?
I want to make an error handler exception to return the error 404 instead of this html. how can i do this ? i tried the following code but it didn't work for me from rest_framework.views import exception_handler from rest_framework.response import Response from rest_framework import status from django.http import Http404 def custom_exception_handler(exc, context): # Call the default exception handler first, # to get the standard error response. response = exception_handler(exc, context) # Now add the HTTP 404 handling if isinstance(exc, Http404): custom_response_data = { "error": "page not found" } return Response(custom_response_data, status=status.HTTP_404_NOT_FOUND) # Return the default response if the exception handled is not a Http404 return response -
testing nginx in github actions
I'm trying to test the deployment of a django app with github actions and I wanted to test if Nginx accepts request correctly on a certain url path with curl command. the actions yaml file is as follows: name: Test deployment on: push: jobs: automated_deployment: name: Deployment runs-on: ubuntu-latest steps: - name: Checkout code uses: actions/checkout@v2 - name: Execute auto-deployment run: | bash auto-deployment.bash nginx_test: name: Set up server IP and check Nginx needs: automated_deployment runs-on: ubuntu-latest steps: - name: Generate IP address and Check Nginx run: | # Generate the IP address EXTERNAL_IP=$(curl -s ifconfig.me) echo "External IP from script: $EXTERNAL_IP" # Use the EXTERNAL_IP variable # Check Nginx with curl curl -I "http://$EXTERNAL_IP/conectdb/" exit_code=$? if [ $exit_code -eq 0 ]; then echo "Nginx is running." else echo "Failed to connect to Nginx. Exit code: $exit_code" exit $exit_code fi In fact, the error generated in the run is curl: (28) Failed to connect to 20.57.44.37 port 80 after 134130 ms: Connection timed out Error: Process completed with exit code 28. which means the script generates the correct ip adress but cannot connect to it on port 80. I appreciate any advice about this subject because I'm not even sur … -
Celery and Celery Beat not reading Django Settings
I recently upgraded Django to 4.x from 3.x and all other deps as well. But since the upgrade celery and celery beat do not seem to recognize the settings that begin with CELERY_ and instead I had to provide broker URL as an ENV variable separately for celery to work. But now celery-beat is not picking the right scheduler setting from DJANGO Settings and defaults to a file based scheduler. Would appreciate any thoughts on this as been searching for an answer for a few days now. For Celery I was able to add ENV variable and move forward but still would prefer a way to read the settings from Django -
Django error: IntegrityError: UNIQUE constraint failed: auth_user.username
My views.py file is: from django.shortcuts import redirect, render from django.contrib.auth.models import User from django.contrib import messages def index(request): return render(request, "index.html") def signup(request): if request.method == "POST": username = request.POST['uname'] first_name = request.POST['fname'] last_name = request.POST['lname'] email = request.POST['email'] pass1 = request.POST['pass1'] pass2 = request.POST['pass2'] myuser = User.objects.create_user(username=username, password=pass1, email=email) myuser.first_name = first_name myuser.last_name = last_name myuser.save() messages.success(request, "Your account has been created successfully...") # function Name = 'login' return redirect('login') return render(request, "signup.html") def login(request): return render(request, "login.html") def signout(request): pass The error is: UNIQUE constraint failed: auth_user.username So whats the cause for it ? And How it can be resolved? -
Django: Adding unique together errors to one of the involved fields
Note: I asked this question on the Django forum, but since I did not receive any answers there, I'm asking here, too. I’m building an application with multi-tenancy, meaning that all data is associated to a tenant model. When creating models, I often want to validate uniqueness of e.g. the name field. However, the uniqueness is only required per tenant, not globally, which is why I’m using unique_together (or UniqueConstraint, found that too late, but will migrate). However, when the uniqueness is violated, a non_field_error is added. I would however prefer to add this error to the name field, as the tenant field is implicit and not visible to the user (the tenant is always the tenant of the logged in user, and can’t be chosen). Any hints on how I could achieve that, preferably in the model or alternatively in a form? I thought about first validating the model, and then moving the error from the non_field_errors to the name field, but that feels kind of wrong. Starting point would be this code: class Company(models.Model): tenant = models.ForeignKey(Tenant, on_delete=models.PROTECT) name = models.CharField(max_length=255) class Meta: unique_together = ('tenant', 'name') -
Django REST Framework: TypeError: 'ManyRelatedManager' object is not iterable for nested M2M serializer
I have two models: Recipe and Ingredient which are connected by ManyToMany through RecipeIngredient: class Recipe(models.Model): ... ingredients = models.ManyToManyField( 'Ingredient', through='RecipeIngredient', ) ... class Ingredient(models.Model): name = models.CharField( max_length=LENGTH_FOR_CHARFIELD ) measurement_unit = models.CharField( max_length=LENGTH_FOR_CHARFIELD ) class RecipeIngredient(models.Model): recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE) ingredient = models.ForeignKey(Ingredient, on_delete=models.CASCADE) amount = models.PositiveIntegerField() I also have a serializer class for Recipe with nested serializer for RecipeIngredient: class IngredientRecipeSerializerForWrite(serializers.ModelSerializer): class Meta: model = RecipeIngredient fields = ('ingredient_id', 'amount') def create(self, validated_data): recipe_ingredient = RecipeIngredient.objects.create(**self.initial_data) return recipe_ingredient class RecipeSerializerForWrite(serializers.ModelSerializer): ingredients = IngredientRecipeSerializerForWrite(many=True) class Meta: model = Recipe fields = ( ... 'ingredients', ... ) def validate(self, attrs): attrs['ingredients'] = self.initial_data['ingredients'] for item in attrs['ingredients']: item['ingredient_id'] = item.pop('id') return attrs def create(self, validated_data): tags = validated_data.pop('tags') ingredients = validated_data.pop('ingredients') recipe = Recipe.objects.create(**validated_data) recipe.tags.set(tags) for item in ingredients: item['recipe'] = recipe ingredients_serializer = IngredientRecipeSerializerForWrite( data=item ) ingredients_serializer.is_valid() ingredients_serializer.save() return recipe Data from request must come in a format: "ingredients": [ { "id": {{firstIndredientId}}, "amount": {{firstIngredientAmount}} }, { "id": {{secondIndredientId}}, "amount": {{secondIngredientAmount}} } I'm trying to pass the data to IngredientRecipeSerializerForWrite and create objects there, but i'm getting error TypeError: 'ManyRelatedManager' object is not iterable I'm using serializer for RecipeIngredient model because i need to pass amount value to …