Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
form post function is not working django python
am new to python and starting with Django Blog project, with admin area the blog post submit successfully, trying to design a page outside admin control area with limited functionality. so far i try with this code View.py from blog.forms import BlogPostForm def new_post(request): if request.method == 'POST': form = BlogPostForm(data=request.POST, files=request.FILES) if form.is_valid(): blgpstfrm = form.save(commit=False) blgpstfrm.author = request.user blgpstfrm.slug = f"{(blgpstfrm.title)}" blgpstfrm.save() obj = form.instance return render(request, "blog/in/new_post.html", {'obj':obj}) else: form = BlogPostForm() return render(request, "blog/in/new_post.html", {'form':form}) Forms.py class BlogPostForm(forms.ModelForm): body = forms.CharField(widget=CKEditorUploadingWidget()) class Meta : model = BlogPost fields = {'title', 'slug', 'body', 'features_image','tags'} New_post.html <form method="POST">{% csrf_token %} <h1>Add New Blog</h1> {{form.media}} <div class="new-post-title">{{form.title}}</div> <div class="sidebar"> <div class="new-post-feature-image">{{form.features_image}}</div> <div class="new-post-tags">{{form.tags}}</div> </div> <div class="new-post-content">{{form.body}}<br/>{{form.slug}} </div> <button type="submit" class="button">publish</button> </form> </div> their is no error in terminal or pages after submit. but when checking in post page no post present other then the admin area posts. -
cropping image only works by triggering second time save method
I have a django application. And I try to crop an high resolution image to a smaller resolution image. The problem I am facing is that cropping the image only works when the save method is triggered for the second time. So not the first time when I trigger the save method. So in models.py I have an image property: images = models.ImageField( upload_to="media/photos/animals", blank=True, null=True, verbose_name="Foto") And the save method looks like: def save(self, *args, **kwargs): self.slug = slugify(self.name) if self.pk is not None: orig = Animal.objects.get(pk=self.pk) if self.images: if orig.images != self.images: # Perform the crop if the image is updated with a different image im = Image.open(self.images) # To standardize your color space if not already RGB im = im.convert("RGB") exif = None if 'exif' in im.info: # Exif data records orientation, among other things exif = im.info['exif'] output = BytesIO() square = 200 # Set the dimension x_final, y_final = square, square # Get image dimensions width = im.size[0] height = im.size[1] if width > height: # crop the largest square out of the center of a landscape image and resize x1 = (float(width/2)-float(height/2)) y1 = (height - height) x2 = ((float(float(width/2)-float(height/2))) + height) y2 = … -
How to make a proxy model's relationships return proxy models themselves
I've got a simple model relationship: class Author(models.Model): ... class Book(models.Model): author = models.ForeignKey(Author) ... but I've also got some proxy models building on top of those models: class ProxyAuthor(Author): class Meta: proxy = True class ProxyBook(Book): class Meta: proxy = True Is there a way to get ProxyAuthor.objects.get(pk=123).books() to return ProxyBook objects rather than Book objects? -
accesing request.user in a tabularinline
I have a ModelForm with multiple TabularInlines that I want to use in the admin. I want to know which user changed something using the inlines. class ResourceForm(forms.ModelForm): resource = forms.FileField(widget=CustomImageFile, ...) class Meta: model = Resource fields = ["resource"] def __init__(self, *args, **kwargs): self.user = kwargs.pop("user") super().__init__(*args, **kwargs) self.fields["resource"].widget.form_instance = self def clean(self): # i need the request.user here class ResourceTabularInline(TabularInline): model = Resource form = ResourceForm def get_formset(self, request, obj=None, **kwargs): formset = super().get_formset(request, obj, **kwargs) formset.user = request.user # <-- I hoped this would be in the kwargs later on return formset class FooAdmin(admin.ModelAdmin): inlines = [ResourceTabularInline,] unfortunately the key user is not in the kwargs of the __init__() method this way -> KeyError. How can I access the user -
Filter queryset based on values in the other queryset
I have the following model in django: class EmailSubscriber(BaseSubscriber): email = models.EmailField() name = models.CharField() Now let's say I made a queryset from EmailSubscriber Like below: queryset1 = EmailSubscriber.objects.all() Now I create another queryset like below: queryset2 = EmailSubscriber.objects.filter(some filters) I want to exclude those fields in queryset1 that have their email and name in queryset2. I mean, if a record in queryset1 has {"email": "john@gmail.com", "name": "john"} and there is a record in queryset2 with {"email": "john@gmail.com", "name": "john"}, the record in queryset1 must be excluded. So they must be unique together. How can I do that in an efficient way? Thanks in advance -
Django Beanstalk connection refused Error 502 no module named application
Ive been going back and forth with this. Like many in this context, I followed this guide. It worked when creating a skeleton django app but when applied to my existing local app, Im getting this error ModuleNotFoundError: No module named 'application' platform: Python 3.9 running on 64bit Amazon Linux 2023 this is my working directory pytrade .(Project Directory) ├── .ebextensions │ └── django.config ├── .elasticbeanstalk │ ├── config.yml │ ├── .gitignore ├── README.md ├── api (created app) │ ├── __init__.py │ ├── admin.py │ ├── apps.py │ ├── dataMethods │ ├── migrations │ ├── models.py │ ├── questrade_api │ ├── serializers.py │ ├── tests.py │ ├── urls.py │ └── views.py ├── db.sqlite3 ├── manage.py ├── pytrade │ ├── __init__.py │ ├── asgi.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py └── requirements.txt wsgi.py """ For more information on this file, see https://docs.djangoproject.com/en/4.2/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'pytrade.settings') application = get_wsgi_application() django.config option_settings: aws:elasticbeanstalk:container:python: WSGIPath: pytrade.wsgi:application The WSGIpath is pointing to the right directory and file as far as I can tell. -
celery task not running when an object is declared , I am using def save_model function to call celery task as per requirement upon save
[2024-01-29 07:23:52,962: ERROR/MainProcess] Process 'ForkPoolWorker-16' pid:2871 exited with 'signal 11 (SIGSEGV)' [2024-01-29 07:23:54,730: ERROR/MainProcess] Task handler raised error: WorkerLostError('Worker exited prematurely: signal 11 (SIGSEGV) Job: 0.') Traceback (most recent call last): File "/Users/asim/Django/Practice-tool-ai-backend/ptenv/lib/python3.12/site-packages/billiard/pool.py", line 1264, in mark_as_worker_lost raise WorkerLostError( billiard.einfo.ExceptionWithTraceback: """ Traceback (most recent call last): File "/Users/asim/Django/Practice-tool-ai-backend/ptenv/lib/python3.12/site-packages/billiard/pool.py", line 1264, in mark_as_worker_lost raise WorkerLostError( billiard.exceptions.WorkerLostError: Worker exited prematurely: signal 11 (SIGSEGV) Job: 0. """ The above mentioned is an error I am getting in celery task I have a requirement to call openai API in django admin save_model function So when an admin user adds a listening task , I retrieve the transcript and pass it to the openai API to generate questions and store them in database. Which was previously workin perfectly fine , since openai takes a lot of time to return response I put that part of the code in the celery background task to save admin time .. but ran into that issue More over if i remove that code #tasks.py @shared_task def sleeptime(time, obj_id): sleep(time) try: obj = ListeningTask.objects.get(id=obj_id) # Continue with processing using the retrieved object transcript = obj.transcript print(transcript) except ObjectDoesNotExist: print(f"Object with ID {obj_id} does not exist.") and just leave the function … -
Python Django custom 404 page not working
I have essentially tried 2 solutions here. The first one: Created 404.html inside root templates directory which was supposed to be recognized by django. By the way have defined it in settings.py: 'DIRS': [BASE_DIR / 'templates'], The second solution i have tried: In urls.py: from django.conf.urls import handler404 handler404 = 'pdfapp.views.not_found' in views.py: def not_found(request, exception): return render(request, 'partials/not_found.html', status = 404) None of these solutions have worked. Neither youtube videos nor the other forms could help my case. -
SyntaxError: invalid syntax in manage.py in django and python project
I run python program in Django framework that showed error below it. File "manage.py", line 26 ) from exc ^ SyntaxError: invalid syntax command is python manage.py test. manage.py: """Django's command-line utility for administrative tasks.""" import os import sys import io from django.db.backends.mysql.schema import DatabaseSchemaEditor sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8') def main(): os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'xxxxx.settings') DatabaseSchemaEditor.sql_create_table += " ROW_FORMAT=DYNAMIC" try: from django.core.management import execute_from_command_line except ImportError as exc: raise 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?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': main() -
Unable to retreive data for profile page (possible authentication problem)
When I login, and then use the nav bar to go to profile page, it does not retreive any information. I am only trying to retreive the user's username for now to simplify the problem. Errors after clicking on 'Profile': GET http://localhost:8000/accounts/login/?next=/profile/ 404 (Not Found) UserProfile.vue:37 Error fetching user profile: Error: HTTP error! status: 404 at fetchUserProfile (UserProfile.vue:30:17) On the network tab, there are 2 names present for the profile: "profile/" has status code of 302 Found and "login/?next=/profile/" has status code of 404 Not Found. "profile/" preview tab shows this: "login/?next=/profile/" preview tab shows this: Here are the relevant parts of my code: views.py from django.contrib.auth import authenticate, login from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework import status from .serializers import CustomUserSerializer from django.views.decorators.csrf import csrf_exempt from django.contrib.auth.decorators import login_required from django.http import JsonResponse @api_view(['POST']) def signup_view(request): if request.method == 'POST': serializer = CustomUserSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response({ 'response': "Successfully registered a new user.", 'username': serializer.data.get('username') }) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) @api_view(['POST']) def login_view(request): if request.method == 'POST': username = request.data.get('username') password = request.data.get('password') user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return Response({ 'response': "Successfully logged in.", 'username': username }) … -
AttributeError at /blog/tag/security/. 'TaggableManager' object has no attribute 'get_reverse_joining_fields'
when I run the code i get 'TaggableManager' object has no attribute 'get_reverse_joining_fields'. I have read django documentation it suggests doing it in the same way but I have no idea what went wrong. I would really appreciate any help. *models.py * from taggit.managers import TaggableManager class Post(models.Model): tags = TaggableManager() title = models.CharField(max_length=200) body = models.TextField(max_length=200) publish = models.DateTimeField(default=timezone.now) slug = models.SlugField(blank = True, max_length=200) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name="author_post")``` *admin.py* from .models import Comment, Post # Register your models here. @admin.register(Post) class PostAdmin(admin.ModelAdmin): list_display = ('title','slug','body', 'slug','author', 'created', 'publish','updated','status') search_fields = ('author__username','title') list_filter = ('title','author__username','created') search_help_text="Search by author username or title" prepopulated_fields = {'slug':('title',)} raw_id_fields = ['author'] *views.py* def post_list(request, tag_slug=None): post_list = Post.objects.filter(status=Post.Status.PUBLISH) tag = None if tag_slug: tag = get_object_or_404(Tag, slug = tag_slug) post_list = post_list.filter(tags__name__in=[tag]) paginator = Paginator(post_list, 100) page_number = request.GET.get('page',1) try: posts=paginator.page(page_number) except EmptyPage: posts=paginator.page(paginator.num_pages) except PageNotAnInteger: posts = paginator.page(1) return render(request, 'blog/post/list.html', context={"posts":posts, 'tag':tag}) *urls.py* --> app level from django.urls import path from . import views app_name='blog' urlpatterns=[ path('', views.post_list, name='post_list'), path('<int:id>/share/', views.post_share, name='post_share'), path('tag/<slug:tag_slug>/', views.post_list, name='post_list_by_tag'), path('<int:id>/comment/', views.post_comment, name='post_comment'), path('post/<int:id>/', views.post_detail, name='post_detail'), ] -
Django Report Builder - Override Toolbar Header
Is there anyway to override the Django Report Builder toolbar header? Ive isoloated it down to this: span _ngcontent-chv-c159="">Welcome to Django Report Builder </span But don't understand how to override it? I've tried overriding the elements within the template but it doesn't seem to change anything...good chance I'm way off with my thinking here. -
PLEASE, The QuerySet value for an exact lookup must be limited to one result using slicing
It displays a table with reports and I would like to display additional information according to the report, how can I do this? e.g. a table with the details of the report is displayed, and in the browser I want to display additional information, displaying the report itself works, but when I add additional information to the code, an error appears models.py class Submissions(models.Model): submissions_number_id = models.CharField(max_length=10,blank=True, unique=True, default=create_new_ref_number,editable=False) contents = models.TextField() class AdditionalInfo(models.Model): submission = models.ForeignKey(Submissions, on_delete=models.CASCADE, related_name='additional_info', default='') contents = models.TextField() I tried this but I get an error views.py def Schedule(request): date = datetime.date.today() report=Submissions.objects.filter(execution_date=date) info=AdditionalInfo.objects.filter(submission=report) context={ 'date':date, 'report':report, 'info':info, } return render(request, 'staff/work_schedule.html', context) html <tbody> {% for qs in report %} <tr style="font-size: 10px;text-align: center;"> <th style="width: 8%;">{{qs.client.user.get_full_name}}, tel.: {{qs.client.phone_number}}</th> <th style="width: 8%;">{{qs.client.post_code}} {{qs.client.city}}, ul.{{qs.client.street}}</th> <th style="width: 40%;">{{qs.contents}}</th> <th style="width: 40%;">{{info.contents}}</th> </tr> {% endfor %} </tbody> -
Why aren't the environment variables working inside my Django Docker container?
I'm encountering an issue where Django doesn't seem to be reading environment variables when running in a Docker-compose environment. Strangely, the environment variables work fine for PostgreSQL but not for Django. I've tried both the env_file and environment options in my Docker-compose file, and I've also experimented with django-dotenv without success. Here's a snippet of my code: print(f" {os.environ.get('SECRET_KEY')} {os.environ.get('DEBUG')} {os.environ.get('DATABASE_NAME')} ") # The above print statement outputs None for all environment variables SECRET_KEY = os.environ.get("SECRET_KEY") # ... version: '3.9' services: db: # ... web: build: ./src command: gunicorn myapp.wsgi:application --access-logfile /logs/gunicorn/access.log --error-logfile /logs/gunicorn/error.log --bind 0.0.0.0:8000 volumes: # ... # env_file: #not working # - .env environment: - SECRET_KEY=${SECRET_KEY} - DATABASE_NAME=${DATABASE_NAME} # ... (other environment variables) nginx: # ... SECRET_KEY=3df-81ioo^5cx(p9cl$)s%m3mlu3t7*yh#1lr5h0po4_sab3*5 DATABASE_NAME=mydb DATABASE_USER=postgres DATABASE_PASS=postgres DATABASE_HOST=db DATABASE_PORT=5432 DEBUG=0 -
How do I add fields to the django_rest_auth response object?
I am extending the default django rest auth Login class in order to add 2 fields to the response object; the user's subscription and email addresses. from dj_rest_auth.serializers import LoginSerializer class CustomLoginSerializer(LoginSerializer): subscription = SubscriptionSerializer(read_only=True) email_addresses = EmailAddressSerializer(read_only=True, many=True) class Meta: model = User # fields = ['pk', 'username', 'email'] fields = ['pk', 'username', 'email', 'subscription', 'email_addresses'] def to_representation(self, instance): print('instance: ' + instance) data = super(CustomLoginSerializer, self).to_representation(instance) data['subscription'] = instance.user.subscription data['email_addresses'] = instance.user.email_addresses.all() data['lol'] = 'lmao' return data This is the response object. Note the added fields aren't present. { "access": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNzA2NTYxNjQyLCJpYXQiOjE3MDY0NzUyNDIsImp0aSI6ImFhYTg5OTNlODQ5MTRjODJhOGRjNGU3MDE5MjE4YzNkIiwidXNlcl9pZCI6NH0.1l7RtT8G1qL6Tq5RVzLe5ceu_mnNVJV8oW64An_-hHk", "refresh": "", "user": { "pk": 4, "username": "user102", "email": "user102@email.com", "first_name": "", "last_name": "" } } Since overriding the to_representation method doesn't seem to work, how do I add related fields to the response object? -
Skipping a step in a WizardView based on data entered in that step
I'm trying to build a formtools Wizard where a confirmation form is shown in one of the steps. The confirmation form is only show in specific cases (e.g. if a user has previously ordered the same item before), and it should no longer be shown after the user has confirmed. Basically, my code looks like this: def ask_confirmation(wizard): # Database conditions go here return user.has_ordered_same_item_before class ItemWizard(SessionWizardView): condition_dict = { "confirm": ask_confirmation, } ... Obviously, the step where the user is asked to confirm is never passed, because the condition is always True. I don't want to store the user's response in the database, it's just something that the wizard needs to "remember" and that I can check in the condition function. How can I test whether the user has confirmed and skip the form once they did? -
I couldn't get the CompoundSearchFilterBackend class in the django-elasticsearch-dsl-drf library to work properly
I'm using the CompoundSearchFilterBackend class in the django-elasticsearch-dsl-drf library to perform queries. However, I'm receiving all queries. Django==4.2.9 django-elasticsearch-dsl==7.3 django-elasticsearch-dsl-drf==0.22.5 Below is an example of cached data from Elasticsearch along with other relevant classes. { "took": 4, "timed_out": false, "_shards": { "total": 1, "successful": 1, "skipped": 0, "failed": 0 }, "hits": { "total": { "value": 1, "relation": "eq" }, "max_score": 1, "hits": [ { "_index": "betik_app_municy_citizen_municipal_council", "_id": "1", "_score": 1, "_source": { "party_name": "party", "title": "title", "full_name": "erhan koçlar", "email": "test@hotmail.com", "id": 1, "substitute": false } } ] } } documents.py @registry.register_document class MunicipalCouncilDocument(Document): class Index: name = f"{APP_LABEL}_municipal_council" settings = { 'number_of_shards': 1, 'number_of_replicas': 0 } class Django: model = MunicipalCouncilModel fields = [ 'id', 'substitute' ] party_name = fields.TextField() title = fields.TextField() full_name = fields.TextField() email = fields.KeywordField() def prepare_full_name(self, instance): return f"{instance.person.name} {instance.person.last_name}" def prepare_email(self, instance): return instance.person.email def prepare_party_name(self, instance): return instance.political_party.name def prepare_title(self, instance): return instance.title.exp def get_queryset(self): # visible return super().get_queryset() \ .filter( visible=True ) \ .order_by('order_no') views.py class PaginateDocumentView(DocumentViewSet): """ Paginate municipal councils (cache) Paginate cached municipal councils """ document = MunicipalCouncilDocument serializer_class = MunicipalCouncilDocumentSerializer pagination_class = StandardPagination authentication_classes = [] filter_backends = [ CompoundSearchFilterBackend, ] search_fields = ( 'full_name', 'email' ) When … -
Signin Fails With Custom Errors
Signin is working flawlessly but, Signup returns with {"non_field_errors": ["Incorrect creds"]} Which I have specified in LoginSerializer. I think it's happening due to authenticate function but, I am not able to pinpoint the issue as when I print it, it returns None. Does anybody knows what could be the issue? I have given the whole code but, I reckon the problem is created in LoginSerializer.I have also, added the AUTHENTICATION_BACKENDS in settings.py and after then, it's still gives that error. Models: from django.db import models from django.contrib.auth.models import BaseUserManager, AbstractBaseUser class UserManager (BaseUserManager): def create_user(self, username, password, **extra_fields): if not username: raise ValueError("Username should be provided") user = self.model(username=username, **extra_fields) user.set_password (password) user.save() return user def create_superuser(self, username, password, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) return self.create_user(username, password, **extra_fields) class User (AbstractBaseUser): id = models.AutoField (primary_key=True) name = models.CharField(max_length=100) email = models. CharField (max_length=60) password = models. CharField (max_length=16) username = models. CharField (max_length=100, unique=True) USERNAME_FIELD = 'username' objects = UserManager() Serializers: from rest_framework import serializers from .models import User from django.contrib.auth import authenticate class UserSerializer(serializers.ModelSerializer): password = serializers.CharField(write_only=True) email = serializers.CharField(required=False) name = serializers.CharField(required=False) class Meta: model = User fields = ('username', 'password', 'email', 'name') def create(self, validated_data): user = … -
Value error on custom log filter when importing unrelated module
I have the setup below that I'm using to inject extra data from the request object into each log message and it works fine. I recently needed to import a urls.py file from another app into the auth_middleware.py file to check all registered DRF routes and redirect appropriately, but I immediately got ValueError: Unable to configure filter 'session_context' each time I attempt to start the application. The import statement that is triggering this error (called from auth_middleware.py) looks like this: from apps.app_name.api.urls import router proj/middleware/auth_middleware.py import threading local = threading.local() class CheckUserLogin: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): setattr(local, "uip", request.META.get("REMOTE_ADDR")) setattr(local, "sid", request.session.session_key or "n/a") if request.user.is_anonymous and request.path != reverse("auth_service_login"): # apply redirect login and send to url_login return HttpResponseRedirect(url_login) return self.get_response(request) services/log_ctx.py import logging from proj.middleware.auth_middleware import local class ExtraLogCtx(logging.Filter): def filter(self, record): defs = "n/a" record.uip = getattr(local, "uip", defs) record.sid = getattr(local, "sid", defs) return True proj/settings.py MIDDLEWARE = [ ... "proj.middleware.auth_middleware.CheckUserLogin", ] LOGGING = { "filters": { "session_context": { "()": "services.log_ctx.ExtraLogCtx", }, }, "handlers": { "console": { ... "filters": ["session_context"], ... }, }, } I have __init__.py in the services and middleware folders and am unsure where else to look. Any … -
Stream Zeros with Django with StreamingHttpResponse
I have to send an amount of Zeros as response, defined by the request. They have to be plain zeros. (I know, a rather odd task...) so, for example, you need 100mb of zeros, you query ?size=100&unit=mb, you will get a stream of 100mb only zeros. Since it can be up to 16gb of zeros, I do not want to generate them at first, rather generate a stream of zeros and send this "line by line". This is what I came up with, but it does not behave like I want because it first gathers the full data and then sends it. class CreateImageAndResponseView(View): line_count = 0 def get(self, request): size_str = request.GET.get('size', '') unit = request.GET.get('unit', '').lower() if unit not in ('gb', 'mb'): return HttpResponse(status=400) try: size = float(size_str) if unit == 'gb': size_bytes = int(size * 1024**3) else: size_bytes = int(size * 1024**2) except ValueError: return HttpResponse(status=400) self.line_count = size_bytes // 1024 return StreamingHttpResponse((b'0' * 1024 for _ in range(0, self.line_count)), content_type='application/octet-stream',) I already saw Problem with Django StreamingHttpResponse, but I do not know which middleware could block this. Also, I am not running nginx or apache, just django from my console. -
Django - Custom User Model Signal Issue: Token Creation Occurs Before User Is Persisted to Database
CustomUser extends User from django.contrib.auth.models class CustomUser(User): user_id = models.IntegerField(primary_key=True) has_mod_rights = models.BooleanField() picture = models.BinaryField(null=True, blank=True) description = models.CharField(max_length=150, null=True, blank=True) is_premium = models.BooleanField() unban_date = models.DateField(null=True, blank=True) and my signal should be triggered when new CustomUser is created @receiver(post_save, sender=DishDiscoverUser) def create_auth_token(sender, instance=None, created=False, **kwargs): if created and instance.pk: token = Token.objects.create(user=instance) the registration view: @api_view(['POST', ]) def registration_view(request): if request.method == 'POST': serializer = RegistrationSerializer(data=request.data) data = {} if serializer.is_valid(): user = serializer.save() # breakpoint() data['response'] = 'successfully registered a new user' data['email'] = user.email data['username'] = user.username token = Token.objects.get(user=user).key data['token']=token else: data: serializer.errors return Response(data) and serializer: class RegistrationSerializer(serializers.ModelSerializer): password = serializers.CharField(write_only=True) password2 = serializers.CharField(write_only=True) class Meta: model = CustomUser fields = ['username', 'password', 'password2', 'email', 'first_name', 'last_name'] def create(self, validated_data): user = CustomUser( email=self.validated_data['email'], username=self.validated_data['username'], has_mod_rights=False, is_premium=False, ) password = self.validated_data['password'] password2= self.validated_data['password2'] if password != password2: raise serializers.ValidationError({'password': 'Password must match!'}) user.set_password(password) user.save() return user and i get FAILED authorisation/tests/test_auth.py::test_registration - ValueError: Model instances passed to related filters must be saved. Error when running @pytest.mark.django_db def test_registration(): client = APIClient() # Prepare data for a valid registration valid_data = valid_login_data()[0] url = '/api/auth/register' response = client.post(url, valid_data) assert response.status_code == 200, response.json() assert … -
Django rendered content is different in console.log from page source
I have the following code in my django view project: if request.method == "POST": form = OrderForm(request.POST) if form.is_valid(): datas = Order() datas.user = current_user datas.save() current_datetime = datetime.datetime.now().strftime('%Y%H%S%m%M%d') order_number = current_datetime + str(datas.id) datas.order_number = order_number datas.save() order = Order.objects.get(user=current_user, is_ordered=False, order_number=datas.order_number) context['order'] = order context['user'] = request.user return render(request, 'orders/order.html', context) Inside order.html, I have: <script> console.log('order number 0: ', {{ order.order_number }}) </script> When I view the page source and browser console, the values of {{ order.order_number }} are different. Browser console.log shows wrong values for str(datas.id) part whereas the rest of the part of {{ order.order_number }} is same in both console.log and page source. -
How can I fix the metaclass conflict in django-rest-framework Serializer
I've written the following code in django and DRF: class ServiceModelMetaClass(serializers.SerializerMetaclass, type): SERVICE_MODELS = { "email": EmailSubscriber, "push": PushSubscriber } def __call__(cls, *args, **kwargs): service = kwargs.get("data", {}).get("service") cls.Meta.subscriber_model = cls.SERVICE_MODELS.get(service) return super().__call__(*args, **kwargs) class InterListsActionsSerializer(serializers.Serializer, metaclass=ServiceModelMetaClass): source_list_id = serializers.IntegerField() target_list_id = serializers.IntegerField() subscriber_ids = serializers.IntegerField(many=True, required=False) account_id = serializers.CharField() service = serializers.ChoiceField(choices=("email", "push")) class Meta: subscriber_model: Model = None def move(self): model = self.Meta.subscriber_model # Rest of the method code. The purpose of this code is that this serializer might need doing operation on different models based on the service that the user wants to use. So I wrote this metaclass to prevent writing duplicate code and simply change the subscriber_model based on user's needs. Now as you might know, serializers.Serializer uses a metaclass by its own, serializers.SerializerMetaclass. This results in the following error: TypeError: metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases. I tried making my ServiceModelMetaClass metaclass to inherit from serializers.SerializerMetaclass but it gave me this error: File "/project-root/segment_management/serializers/subscriber_list.py", line 33, in <module> class InterListsActionsSerializer(serializers.Serializer, metaclass=ServiceModelMetaClass): File "/project-root/segment_management/serializers/subscriber_list.py", line 36, in InterListsActionsSerializer subscriber_ids = serializers.IntegerField(many=True, required=False) File "/project-root/.venv/lib/python3.10/site-packages/rest_framework/fields.py", line 894, in __init__ super().__init__(**kwargs) TypeError: Field.__init__() … -
How to add a new value to model at the very beginning, shifting the ID of other values by 1?
models.py: class Category(models.Model): title = models.CharField(max_length=255) slug = models.SlugField(null=False, unique=True) ordering = models.IntegerField(default=0) is_featured = models.BooleanField(default=False) def save(self, *args, **kwargs): self.slug = slugify(self.title) super(Category, self).save(*args, **kwargs) def __str__(self): return self.title class Meta: ordering = ['ordering'] verbose_name_plural = 'Categories' def get_absolute_url(self): return '/%s/' % (self.slug) class SubCategory(models.Model): title = models.CharField(max_length=255) slug = models.SlugField(null=False, unique=True) ordering = models.IntegerField(default=0) is_featured = models.BooleanField(default=True) category = models.ForeignKey( Category, related_name='subcategory', on_delete=models.CASCADE ) def save(self, *args, **kwargs): self.slug = slugify(self.title) super(SubCategory, self).save(*args, **kwargs) class Meta: ordering = ['ordering'] verbose_name_plural = 'SubCategories' def __str__(self): return self.title def get_absolute_url(self): return '/%s/%s/' % (self.category, self.slug) class SubSubCategory(MPTTModel): parent = TreeForeignKey('self', blank=True, null=True, related_name='children', on_delete=models.CASCADE) title = models.CharField(max_length=50) slug = models.SlugField(null=False, unique=True) sub_category = models.ForeignKey( SubCategory, related_name='subsubcategory', on_delete=CASCADE, null=True ) create_at = models.DateTimeField(auto_now_add=True) update_at = models.DateTimeField(auto_now=True) def __str__(self): return self.title class Meta: verbose_name_plural = 'Sub_subcategories' class MPTTMeta: order_insertion_by = ['title'] def get_absolute_url(self): return reverse('susubcategory_detail', kwargs={'slug': self.slug}) def __str__(self): full_path = [self.title] k = self.parent while k is not None: full_path.append(k.title) k = k.apparent return ' / '.join(full_path[::-1]) class Attribute(models.Model): name = models.CharField(max_length=100) category = models.ForeignKey(SubSubCategory, related_name='attribute_categories', on_delete=models.CASCADE) def __str__(self): return self.name class AttributeChoice(models.Model): category = models.ForeignKey( SubSubCategory, related_name='attribute_choice_categories', on_delete=models.CASCADE, null=True ) attribute = ChainedForeignKey( Attribute, chained_field="category", chained_model_field="category", show_all=True, auto_choose=True, sort=True, null=True, … -
Using a check box in a web application
Am trying to create a TodoList where a user clicks a checkbox to tick checked when complete is true , but am not understanding the concept with checkboxes. just recently started learning django , the below code is what l have come up with. Model Code from django.db import models # Create your models here. class List(models.Model): list_title = models.CharField(max_length = 200) list_context = models.CharField(max_length = 200) pub_date = models.DateTimeField() complete = models.BooleanField(default=False) def __str__(self): return self.list_title view code from django.shortcuts import render from .models import List # Create your views here. def index(Request): list_items = List.objects.order_by('-pub_date') list_ticked =[] if Request.method == "Post": list_ticked = Request.Post.getlist('items') if list_ticked== True: complete = True context = { 'list_items':list_items, 'list_ticked':list_ticked, } template = 'TodoList/index.html' return render (Request,template,context) Html Code <ul class="list-group mb-0"> <form action="" method="post"> {%if list_items%} {%for item in list_items %} <li class="list-group-item d-flex justify-content-between align-items-center border-start-0 border-top-0 border-end-0 border-bottom rounded-0 mb-2"> <div class="d-flex align-items-center"> <input class="form-check-input me-2" type="checkbox" value="{{item.id}}" id="item {{forloop.counter}}" name="list_ticked =[]" /> {{item.list_context}} </div> <a href="#!" data-mdb-toggle="tooltip" title="Remove item"> <i class="fas fa-times text-primary"></i> </a> </li> {%endfor%} {%else%} <p>No list available</p> {%endif%} </form> </ul> <ul class="list-group mb-0"> <form action="" method="post"> {%if list_items%} {%for item in list_items %} <li class="list-group-item d-flex …