Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django model instance not being created upon Formset submission
I have a Formset, where one of the fields is a multi-select checkbox, with the options available being determined by a foreign key relationship (to the business model; the form takes business as an arguement). This works, however upon submission of the Formset, nothing is saved to the database despite a POST request and redirect taking place (I would expect it to create an instance or instances of the Instructors model). My models.py (including only relevant models): class Instructors(models.Model): uid = models.CharField(verbose_name="Unique ID", max_length=255, primary_key=True) business = models.ForeignKey(Business, blank=False, on_delete=models.CASCADE) first_name = models.CharField(verbose_name="First Name", max_length=255, blank=False) surname = models.CharField(verbose_name="Surname", max_length=255, blank=False) activities = models.ManyToManyField(Activity, blank=False) def __str__(self): return str(self.uid) class Business(models.Model): # if is_business on profile model = true, then get access to create Business Profile business_name = models.CharField(verbose_name='Business Name', max_length=255) business_description = models.TextField(verbose_name='Business Description', max_length=500) slug = models.SlugField(verbose_name='Slug', max_length=250, null=True, blank=True, unique=True) business_contact_number = models.CharField(verbose_name='Business Contact Number', max_length=32) business_email = models.EmailField(verbose_name='Business Email') business_profile_image = models.ImageField(verbose_name="Profile Picture", null=True, blank=True, upload_to='business_images/') creation_date = models.DateTimeField(auto_now_add=True) address = models.CharField(verbose_name="Street Address", max_length=100, null=True, blank=True) town = models.CharField(verbose_name="Town/City", max_length=100, null=True, blank=True) county = models.CharField(verbose_name="County", max_length=100, null=True, blank=True) post_code = models.CharField(verbose_name="Post Code", max_length=8, null=True, blank=True) country = models.CharField(verbose_name="Country", max_length=100, null=True, blank=True) longitude = models.CharField(verbose_name="Longitude", max_length=50, null=True, … -
How to add select foreign keys from django html template
iam trying to create an add movie function on my movie project, fields such as actor,director are added as foreign keys. when i do this via iam only able to add non foreign key fiels to the object. this is the Movie model class Movie(models.Model): user=models.ForeignKey(User,on_delete=models.CASCADE,default=True) name=models.CharField(max_length=100,unique=True) slug=models.SlugField(max_length=100,unique=True,blank=True) year=models.CharField(max_length=5,blank=True) language=models.CharField(max_length=50,blank=True) release=models.CharField(max_length=100,blank=True) rating=models.CharField(max_length=20,blank=True) poster=models.ImageField(upload_to='movies/poster',blank=True) cover=models.ImageField(upload_to='movies/cover',null=True,blank=True) duration=models.CharField(max_length=50,default=None,blank=True) streaming=models.ForeignKey(Streaming,on_delete=models.CASCADE,blank=True,null=True) ott=models.TextField(max_length=200,blank=True,null=True) actors=models.ManyToManyField(Actor,related_name='actor',blank=True) Characters=models.ManyToManyField(Character,related_name='character',blank=True) director=models.ForeignKey(Director,on_delete=models.CASCADE,blank=True,null=True) writers=models.ManyToManyField(Writer,related_name='writer',blank=True) cinematographer=models.ForeignKey(Cinematographer,on_delete=models.CASCADE,null=True,blank=True) based =models.CharField(max_length=100,blank=True,null=True) genres=models.ManyToManyField(Genre,blank=True) certification=models.ForeignKey(Certification,on_delete=models.CASCADE,null=True,blank=True) synopsis=models.TextField(max_length=1000,blank=True) trailer=models.CharField(max_length=500,blank=True) def __str__(self): return self.name this is the path from django.contrib import admin from django.urls import path from Movies import views app_name='Movie' urlpatterns = [ # function based path path('add_movie',views.add_movie,name='add_movie'), ] this is the template to add movie <form method="POST" enctype="multipart/form-data" class="user"> {% csrf_token %} <div class="row"> <div class="col-md-12 form-it"> <label>Movie Name</label> <input type="text" name="name" placeholder="Add movie title"> </div> <div class="col-md-12 form-it"> <label>Released Year</label> <input type="text" name="year" placeholder="Add movie title"> </div> <div class="col-md-12 form-it"> <label>Released Date</label> <input type="text" name="release" placeholder="Add Released date"> </div> <div class="col-md-12 form-it"> <label>Language</label> <input type="text" name="language" placeholder="Add Language"> </div> <div class="col-md-12 form-it"> <label>Rating</label> <input type="text" name="rating" placeholder="Add IMDB rating"> </div> <div> <div class="col-md-6 form-it"> <label>Poster</label> <input type="file" name="poster" placeholder="Add Movie Poster"> </div> <div class="col-md-6 form-it"> <label>Cover image</label> <input type="file" name="cover" placeholder="Add a cover image"> </div> </div> <div class="col-md-12 form-it"> … -
cannot access local variable 'conversation' where it is not associated with a value
@login_required def detail(request, pk): conversation = Conversation.objects.filter(members__in=[request.user.id]).get(pk=pk) if request.method == 'POST': form = ConversationMessageForm(request.POST) if form.is_valid(): conversation_message = form.save(commit=False) conversation_message.conversation = conversation conversation_message.created_by = request.user conversation_message.save() conversation.save() return redirect('conversation:detail',pk=pk) else: form = ConversationMessageForm() return render(request,'conversation/detail.html',{ 'conversation': conversation, 'form': form, }) cannot access local variable 'conversation' where it is not associated with a value -
TypeError: Field.__init__() got an unexpected keyword argument 'max_lenght' django
do you know why get this error for below code? "TypeError: Field.init() got an unexpected keyword argument 'max_lenght'" thanks, M from django.db import models from django.contrib.auth.models import User STATUS = ((0, 'Draft'), (1, 'Published')) # Create your models here. class Post(models.Model): title = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_post') created_on= models.DataTimeField(auto_now_add=True) updated_on = models.DataTimeField(auto_now=True) conent = models.TextField() status = models.IntegerField(choices=STATUS, default=0) class Meta: ordering = ['created_on'] def __str__(self): return self.title -
Django: User activation not working properly
I have registration page in my Django project. I can finish the registration just fine, and the console outputs the email with the generated link, but for some reason the user value captured by the views is None? How do I fix this? I generate user tokens like this: from django.contrib.auth.tokens import PasswordResetTokenGenerator from six import text_type class AccountActivationTokenGenerator(PasswordResetTokenGenerator): def _make_hash_value(self, user, timestamp): return ( text_type(user.pk) + text_type(timestamp) + text_type(user.is_active) ) account_activation_token = AccountActivationTokenGenerator() When a user completes their registration, they're supposed to get an email like this: {% autoescape off %} Hello, {{ user.user_name }}! Your account has been successfully created. Please click the link below to activate your account. http://{{ domain }}{% url 'users:activate' uidb64=uid token=token %} {% endautoescape %} And I have my views setup so that if a user clicks on the link, their account gets activated and they're redirected to the dashboard like this: from django.contrib.auth import login from django.contrib.auth.decorators import login_required from django.contrib.sites.shortcuts import get_current_site from django.http import HttpResponse from django.shortcuts import redirect, render from django.template.loader import render_to_string from django.utils.encoding import force_bytes, force_str from django.utils.http import urlsafe_base64_decode, urlsafe_base64_encode #from orders.views import user_orders from .forms import RegistrationForm from .models import UserBase from .tokens import account_activation_token … -
react axios POST request to django failure
I try to make POST request from react app with axios. This is my code: import axios from 'axios'; const csrftoken = document.cookie.split('=')[1] // please don`t pay attention to this implementation const axiosInstance = axios.create({ baseURL: 'http://127.0.0.1:8000/api/', headers: { "Content-Type": "application/json", "X-CSRFTOKEN": csrftoken }, }); // onClick const handleApply = () =>{ const apiUrl = 'im/category_characteristics/'; axiosInstance.post(apiUrl, {withCredentials: true}) .then((response)=>{console.log(response.data)}) .catch(error => console.log(error)) }; These are my request headers: headers: AxiosHeaders Accept: "application/json, text/plain, */*" Content-Type: "application/json" X-CSRFToken: "8MGBp41YrnOSM23RLsAPIWNTNFLVTU7c" Django raises: Forbidden (CSRF cookie not set.): /api/im/category_characteristics/ Whereas, I receive successful response, when using Insomnia with the same headers: Insomnia terminal output: > POST /api/im/category_characteristics/ HTTP/1.1 > Host: 127.0.0.1:8000 > User-Agent: insomnia/2023.4.0 > Cookie: csrftoken=8MGBp41YrnOSM23RLsAPIWNTNFLVTU7c > Content-Type: application/json > X-CSRFToken: 8MGBp41YrnOSM23RLsAPIWNTNFLVTU7c > Accept: */* > Content-Length: 59 * Mark bundle as not supporting multiuse < HTTP/1.1 200 OK < Date: Sun, 13 Aug 2023 15:07:03 GMT < Server: WSGIServer/0.2 CPython/3.10.1 < Content-Type: application/json < X-Frame-Options: DENY < Content-Length: 56 < Vary: Origin < X-Content-Type-Options: nosniff < Referrer-Policy: same-origin < Cross-Origin-Opener-Policy: same-origin * Received 56 B chunk * Connection #13 to host 127.0.0.1 left intact I see Cookie header among others, but when I try to set it, I get error … -
Django checkbox input only working in one direction
I have a form with a checkbox on "pregnant". If the profile is not pregnant and goes to the update profile form, checking the box and submitting the form updates the profile. I can see in the dashboard it appears as pregnant now. However, if the profile is pregnant, and goes to update profile, unchecking the checkbox (prepopulated) and submitting, it does nothing! The profile information does not update (it still appears as pregnant in the dashboard). I am puzzled because the form connects to the database (it can update from non-pregnant to pregnant) but not the other way around! What am I missing? :-/ See my code. view: def edit_profile(request): if request.user.is_authenticated: current_user = Account.objects.get(id=request.user.id) form = EditProfileForm(request.POST or None, instance=current_user) if form.is_valid(): form.save() messages.success(request,("Your profile has been updated!")) return redirect('dashboard') return render(request, 'accounts/edit_profile.html',context={'form':form}) # else: messages.success(request,('You must be logged in!')) return redirect('login') html: <div class="flex col col-auto form-group form-check"> <label><input type="checkbox" id="pregnancy" value="Yes" name="pregnancy" {% if form.instance.pregnancy == 'Yes' %} checked {% endif %}> {% trans " Pregnant" %}</label> </div> model: class Account(AbstractBaseUser): .... pregnancy = models.CharField(max_length=10,blank=True, null=True, default='No') -
Unable to save the form in my database in Django
I wanted to practice Django, so I started off by creating a quiz website. However the the form isn't being saved into my database. I created the following models. difficulty_choices=(('easy','easy'),('hard','hard'),('medium','medium')) class Quiz(models.Model): name=models.CharField(max_length=200) topic=models.CharField(max_length=100) number_of_questions=models.IntegerField() difficulty=models.CharField(max_length=100,choices=difficulty_choices) def get_questions(self): return self.questions_set.all()[:self.number_of_questions] class Questions(models.Model): text=models.CharField(max_length=200) quiz=models.ForeignKey(Quiz,on_delete=models.CASCADE) correct=models.CharField(max_length=25) def __str__(self): return str(self.text) def get_answers(self): return self.answers_set.all() class Answers(models.Model): text = models.CharField(max_length=200) question = models.ForeignKey(Questions, on_delete=models.CASCADE) def __str__(self): return f"Question: {self.question.text}, Answer: {self.text}" class UserAnswer(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) question = models.ForeignKey(Questions, on_delete=models.CASCADE) answer = models.ForeignKey(Answers, on_delete=models.CASCADE) selected=models.CharField(max_length=25,blank=True) The text field in 'Answer' model contains the options and text field in 'Question' model contains the question The option for each question is displayed in the form of radio select button. The UserAnswer model saves the answer answered by the authenticated user, for each question. To be able to select the option i created the below forms.py class QuizForm(forms.ModelForm): class Meta: model = Questions fields = ['text'] # Add other fields as needed def __init__(self, *args, **kwargs): super(QuizForm, self).__init__(*args, **kwargs) question_instance = kwargs.get('instance') answers = question_instance.get_answers() answer_choices = [(answer.text, answer.text) for answer in answers] self.fields['selected_answer'] = forms.ChoiceField( label="Select the correct answer", choices=answer_choices, widget=forms.RadioSelect ) and the views.py for this is @login_required def questions(request, pk): try: … -
Can Django forms be used in a custom view?
I'm using a CreateView to create an object then a custom written view to assign and update the values. The problem is I can't get to assign multiple values to a many to many relation. A configuration page looks like this right now: I'm not using forms, everything is inside the template. And I have the problem with the last input, the 'Cut material' checkboxes. Since I don't use a form, it's very tricky to handle that some inputs has only one value and some of them might have multiple values (like 'Cut material'). Right now my view will request the POST data and will try to match each option with it's value, but when it get's to 'Cut material' it will get an error if I select more options. I tried some workaround to insert some hidden inputs to pass into the context more info but I had no success. I guess if I can use forms then I might solve this issue and it will also help with validation. How do you think I can manage to pass correctly the value from 'Cut material' to the view to save it correctly? Also if you would do it with … -
Django DBBackup issue
I want to backup media fileand database of a django project,based on document I install Django-dbbackup, I want to store backup files in dropbox . I ran this command : pip install dropbox django-storages and add following in setting.py DBBACKUP_STORAGE = 'storages.backends.dropbox.DropBoxStorage' DBBACKUP_STORAGE_OPTIONS = { 'oauth2_access_token': 'DROPBOX_TOKEN', } now I cant backup ; account of dropbox is base mode and free(2GIG); token from 'generate access token' button on web site ERROR: 'D:/default-DESKTOP-RISNQKN-2023-08-13-164717.dump' did not match pattern '(/(.|[\r\n])*|id:.*)|(rev:[0-9a-f]{9,})|(ns:[0-9]+(/.*)?)' Internal Server Error: /account/admin_ability/ Traceback (most recent call last): File "D:\CODES\python\virtualenvs\karapp2\karkpp2\app_account\views.py", line 37, in f_admin_ability call_command('dbbackup') File "D:\CODES\python\virtualenvs\karapp2\.env\Lib\site-packages\django\core\management\__init__.py", line 194, in call_command return command.execute(*args, **defaults) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\CODES\python\virtualenvs\karapp2\.env\Lib\site-packages\django\core\management\base.py", line 458, in execute output = self.handle(*args, **options) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\CODES\python\virtualenvs\karapp2\.env\Lib\site-packages\dbbackup\utils.py", line 120, in wrapper func(*args, **kwargs) File "D:\CODES\python\virtualenvs\karapp2\.env\Lib\site-packages\dbbackup\management\commands\dbbackup.py", line 93, in handle self._save_new_backup(database) File "D:\CODES\python\virtualenvs\karapp2\.env\Lib\site-packages\dbbackup\management\commands\dbbackup.py", line 120, in _save_new_backup self.write_to_storage(outputfile, filename) File "D:\CODES\python\virtualenvs\karapp2\.env\Lib\site-packages\dbbackup\management\commands\_base.py", line 97, in write_to_storage self.storage.write_file(file, path) File "D:\CODES\python\virtualenvs\karapp2\.env\Lib\site-packages\dbbackup\storage.py", line 86, in write_file self.storage.save(name=filename, content=filehandle) File "D:\CODES\python\virtualenvs\karapp2\.env\Lib\site-packages\django\core\files\storage\base.py", line 37, in save name = self.get_available_name(name, max_length=max_length) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\CODES\python\virtualenvs\karapp2\.env\Lib\site-packages\storages\backends\dropbox.py", line 205, in get_available_name return super().get_available_name(name, max_length) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\CODES\python\virtualenvs\karapp2\.env\Lib\site-packages\django\core\files\storage\base.py", line 77, in get_available_name while self.exists(name) or (max_length and len(name) > max_length): ^^^^^^^^^^^^^^^^^ File "D:\CODES\python\virtualenvs\karapp2\.env\Lib\site-packages\storages\backends\dropbox.py", line 126, in exists return bool(self.client.files_get_metadata(self._full_path(name))) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\CODES\python\virtualenvs\karapp2\.env\Lib\site-packages\dropbox\base.py", … -
Why validation in the serializer does not perform DRF
Why validation does not perform. I have tried many things but still there is the standard "This field may not be blank." or "This field may not be null.". I also changed the clean method in the model but it only helped in the admin panel, thanks for your help. serializer: class MemeSerializer(serializers.ModelSerializer): class Meta: model = Meme fields = ['id', 'title', 'meme_image', 'author'] def validate_title(self, value): if not value: raise serializers.ValidationError("BAD") return value View class MemeView(viewsets.ModelViewSet): queryset = Meme.objects.all() serializer_class = MemeSerializer permission_classes = [permissions.IsAuthenticatedOrReadOnly] def create(self, request): user = request.user data = { "title": request.data.get("title"), "meme_image": request.FILES.get("meme_image"), "author": user.pk, } serializer = self.get_serializer(data=data) if serializer.is_valid(): serializer.save() return Response({"message": "Added."}, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
How to fetch row Django serialize query set on jQuery?
Hello I'm trying to load Django Serialize Query set into jQuery Here my view.py def Load_Temp_Data(request): serialize_data = "" data_list = "" if request.method == "GET": count = TempCalculate.objects.filter(create_by = request.user).count() if count: data = TempCalculate.objects.filter(create_by = request.user) serialize_data = serializers.serialize("json",data) #calculation = TempCalculate.objects.filter(create_by = request.user).aggregate(Sum('price')) #conver to list #List = list(calculation.items()) data_list = list(data) return HttpResponse(serialize_data, content_type='application/json') Here my template and jQuery code function Load_data() { var row = "" // table load karo tyre aa pela karo. $.ajax({ url: "{% url 'load_temp_data' %}", success: function (data, status) { console.log(data) if (status) { no = 1 row_data = data for (var i = 0; i < row_data.length; i++) { console.log(i['quantity']) row += "<tr id =" + i + "><td>" + no + "</td><td>" + "<button type='button' id='delet_button' onclick='Delet_Item(" + row_data[i]['id'] + "," + i + ")' class='btn btn-danger'><i class='fa fa-trash'></i></button>" + "</td><td>" + row_data[i]['items__name'] + "</td><td>" + row_data[i]['quantity'] + "</td><td>" + row_data[i]['price'] + "</td><td>" + row_data[i]['total_gst'] + "</td><td>" + row_data[i]['net_amount'] + "</td></tr>" $('#Table_Data').html(row) no = no + 1 } $('#id_sub_total').val(data.total) $('#id_gst_total').val(data.gst_total) $('#id_total').val(data.net_amount) } else { alert("Error !") } } }) } when I'm console.log data set is print but I can't slice data like items_name,quantity etc -
Euro Currency Format (Django)
I have a variable and am trying to format it to following format "100.000,00". I have an amount (integer) and a price (decimal) and try to multiply these things to one total price with: totalprice = price * decimal(amount) I'm using Django and in the end I have to cast it to a string so I can use it in a text field. -
How to set up a django form field to receive data from a request?
For multilang, I store the fields in the database as json fields in this format: {"ru": "some text", "en": "some text"}, add form by itself looks like this input names example: title[ru], title[en] So i don't know how to write my form to get this data as: title: {"ru": "some", "en":"some"} What should i do? How to overwrite form field to get data like this? don’t find answers before that, I decided to completely abandon the forms and collect data with a custom function, but this decision seems to me wrong -
Google authentication MismatchingStateError in django (CSRF Warning - State not equal in request and response)
I have a problem that I have been trying to resolve for the past couple of days. When attempting to handle Google authentication in my Django web app, a MismatchingStateError is encountered at /signup/google/callback/. The issue arises when the Google authentication works correctly upon initial attempts but fails with the mentioned error after multiple tries. Even after logging in and out multiple times, the error persists. This is my first time implementing Google authentication within Django, and I've struggled to find comprehensive guidelines or resources. I'm currently learning about flow handling and recently became aware of potential associated risks. It's important to note that this problem resembles CSRF attacks. It emerges when there's a series of rapid login requests. After this error arises, subsequent logins are blocked. Notably, this issue isn't related to the session ID, as I've attempted to clear it without success. It seems tied to generation, possibly due to how states are managed. See the error here def google_auth(request): # Generate the Google OAuth authorization URL and redirect the user to it authorization_url, state = flow.authorization_url(access_type='offline', include_granted_scopes='true') request.session['oauth_state'] = state return redirect(authorization_url) def google_callback(request): # Exchange the authorization code for a Google OAuth access token. stored_state = … -
Python logging in Django : Filter won't work in logger
I have a logging custom filter class which suppose to ignore Django logs in my logger 'bucket' (I don't want to disable Django logs, just to keep them in separate log): class ExcludeDjangoLogsFilter(logging.Filter): """ Excludes django system logs from logger """ modules_to_exclude = ( "daphne.server", "django", "django.db", "django.server" ) def filter(self, record: logging.LogRecord) -> bool: """ Filters records to exclude from a logging modules with a certain names. """ return not record.name.startswith(self.modules_to_exclude) It works just fine if I pass this filter to handler but It doesn't if I pass this filter to logger. If I use this filter within logger interpreter enters the filter's class but doesn't enter in filter method. My logging config: LOGGING = { "version": 1, "disable_existing_loggers": False, # Filters: "filters": { "info_only": { "()": "logger.logger_filters.InfoOnlyFilter" }, "exclude_django_log": { "()": "logger.logger_filters.ExcludeDjangoLogsFilter" } }, # Formatters' profiles: "formatters": { "base": { "format": "[{asctime}][{levelname}][{name} / {funcName}][{lineno}] {message}", "datefmt": "%d/%m/%Y %H:%M:%S", "style": "{" }, "info": { "format": "[{asctime}][{name} / {funcName}] {message}", "datefmt": "%d/%m/%Y %H:%M:%S", "style": "{" }, "django_sys_format": { "format": "[{asctime}][{levelname} | {name}] {message}", "datefmt": "%d/%m/%Y %H:%M:%S", "style": "{" } }, # handlers: "handlers": { "important_file": { "level": "WARNING", "class": "logging.FileHandler", "formatter": "base", "filename": BASE_DIR / "logger/logs/important.log" }, "info_file": { … -
uploading an image by url link
can you please tell me how to upload images via the url link through the django admin panel, not from my data warehouse, but via the url link it is possible for me to download only from my storage, but how can I download from a url link ? -
Saving copies in m2m django orm
Inside my code, I am trying to save copies of one object inside m2m, but only one instance is saved. How can I save several of them? def add_to_basket(request): if request.method == 'POST': basket_id = request.session.get('BID') if not basket_id: basket_id = str(uuid.uuid4()) request.session['BID'] = basket_id basket, created = Basket.objects.get_or_create(id=basket_id) if created: basket.save() ticket_id = request.POST.get('ticket_id') count = request.POST.get('count') ticket = Tickets.objects.get(id=int(ticket_id)) if ticket.count - int(count) > 0: for i in range(int(count)): new_ticket = Tickets.objects.get(id=int(ticket_id)) new_ticket.count = new_ticket.count - 1 new_ticket.save() basket.tickets.add(new_ticket) basket.save() return JsonResponse({'status': 'ok'}) else: return JsonResponse({'status': 'not enough tickets'}) else: return JsonResponse({'status': 'not get method'}) class Basket(models.Model): id = models.TextField(verbose_name='ID Корзины', primary_key=True) tickets = models.ManyToManyField(Tickets, verbose_name='Билеты') date = models.DateTimeField(auto_now_add=True, verbose_name='Дата создания') def to_json(self): return { 'id': self.id, 'tickets': [ticket.to_json() for ticket in self.tickets.all()], 'date': self.date } class Meta: verbose_name = 'Корзина' verbose_name_plural = 'Корзины' I tried to add tickets, in this code I am already creating a separate instance -
Django - two approaches to extending user model wont work together?
I am trying to make my django app require a unique email address when creating the account. When I added (the commented line in the models) the unique email constraint in the model I used to add fields before it just adds another email field instead of altering the original one. So after having found another solution with extending the AbstractUser class unfortunately Im getting 'the model User is not registered' error when im trying to make migrations. Please advice me on what would be a way to go to have both extra fields as well as unique email constraint. Heres how i have extra fields added to the user model: models class Account(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) points = models.IntegerField(default=0) #### email = models.EmailField(("email address"), blank=True, null=True, unique=True) profession = models.CharField(max_length=30, blank=True, null=True, choices =[('a', 'a'), ('b', 'b')]) def __str__(self): return self.user.username admin from django.contrib import admin from account.models import Account from django.contrib.auth.models import User from django.contrib.auth.admin import UserAdmin class AccountInline(admin.StackedInline): model = Account can_delete = False verbose_name_plural = 'Accounts' class CustomizedUserAdmin (UserAdmin): inlines = (AccountInline, ) admin.site.unregister(User) admin.site.register(User, CustomizedUserAdmin) It worked until ive added: models from django.contrib.auth.models import AbstractUser class CustomUser(AbstractUser): email = models.EmailField(unique=True) settings AUTH_USER_MODEL = 'account.CustomUser' -
How to use django_private_chat2
I want to use this package for my localhost website but it show the error: Using the URLconf defined in dimsum.urls, Django tried these URL patterns, in this order: admin/ profiles/ restaurants/ messages/ [name='all_messages_list'] messages/<dialog_with>/ [name='messages_list'] dialogs/ [name='dialogs_list'] self/ [name='self_info'] upload/ [name='fileupload'] I done all the steps in quick start of this package but it not working. Install django_private_chat2: pip install django_private_chat2 Add it to your INSTALLED_APPS: INSTALLED_APPS = ( ... 'django_private_chat2.apps.DjangoPrivateChat2Config', ... ) Add django_private_chat2's URL patterns into my url file: from django.urls import re_path, include urlpatterns = [ ... re_path(r'', include('django_private_chat2.urls', namespace='django_private_chat2')), ... ] Add django_private_chat2's websocket URLs to my asgi.py: import os from django.core.asgi import get_asgi_application from channels.routing import ProtocolTypeRouter, URLRouter from channels.auth import AuthMiddlewareStack from django_private_chat2 import urls os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'dimsum.settings') # application = get_asgi_application() django_asgi_app = get_asgi_application() application = ProtocolTypeRouter({ "http": django_asgi_app, "websocket": AuthMiddlewareStack( URLRouter(urls.websocket_urlpatterns) ), }) I all so run this command before run server python manage.py migrate Please tell me what am I missing? -
Encountring Error While installing django dependency "Building wheel for xmlsec (pyproject.toml) ... error error: subprocess-exited-with-error"
I am using this command to install dependencies for django project pip install -r requirements.txt ` Installing build dependencies ... done Getting requirements to build wheel ... done Installing backend dependencies ... done Preparing metadata (pyproject.toml) ... done Collecting yarl==1.7.2 (from -r requirements.txt (line 369)) Using cached yarl-1.7.2-cp38-cp38-macosx_10_9_x86_64.whl (121 kB) Collecting zipp==3.1.0 (from -r requirements.txt (line 371)) Using cached zipp-3.1.0-py3-none-any.whl (4.9 kB) Requirement already satisfied: setuptools>=3.0 in ./kit/lib/python3.8/site-packages (from gunicorn==20.1.0->-r requirements.txt (line 154)) (56.0.0) Building wheels for collected packages: xmlsec, django-rest-hooks Building wheel for xmlsec (pyproject.toml) ... error error: subprocess-exited-with-error × Building wheel for xmlsec (pyproject.toml) did not run successfully. │ exit code: 1 ╰─> [65 lines of output] running bdist_wheel running build running build_py creating build creating build/lib.macosx-10.9-x86_64-cpython-38 creating build/lib.macosx-10.9-x86_64-cpython-38/xmlsec copying src/xmlsec/py.typed -> build/lib.macosx-10.9-x86_64-cpython-38/xmlsec copying src/xmlsec/tree.pyi -> build/lib.macosx-10.9-x86_64-cpython-38/xmlsec copying src/xmlsec/init.pyi -> build/lib.macosx-10.9-x86_64-cpython-38/xmlsec copying src/xmlsec/constants.pyi -> build/lib.macosx-10.9-x86_64-cpython-38/xmlsec copying src/xmlsec/template.pyi -> build/lib.macosx-10.9-x86_64-cpython-38/xmlsec running build_ext building 'xmlsec' extension creating build/temp.macosx-10.9-x86_64-cpython-38 creating build/temp.macosx-10.9-x86_64-cpython-38/private creating build/temp.macosx-10.9-x86_64-cpython-38/private/var creating build/temp.macosx-10.9-x86_64-cpython-38/private/var/folders creating build/temp.macosx-10.9-x86_64-cpython-38/private/var/folders/0f creating build/temp.macosx-10.9-x86_64-cpython-38/private/var/folders/0f/pwhvtlxn26j0cfry2wrpvb7r0000gn creating build/temp.macosx-10.9-x86_64-cpython-38/private/var/folders/0f/pwhvtlxn26j0cfry2wrpvb7r0000gn/T creating build/temp.macosx-10.9-x86_64-cpython-38/private/var/folders/0f/pwhvtlxn26j0cfry2wrpvb7r0000gn/T/pip-install-y3izz7rd creating build/temp.macosx-10.9-x86_64-cpython-38/private/var/folders/0f/pwhvtlxn26j0cfry2wrpvb7r0000gn/T/pip-install-y3izz7rd/xmlsec_1b2a1e6a17e447509a7b6137df7d3b99 creating build/temp.macosx-10.9-x86_64-cpython-38/private/var/folders/0f/pwhvtlxn26j0cfry2wrpvb7r0000gn/T/pip-install-y3izz7rd/xmlsec_1b2a1e6a17e447509a7b6137df7d3b99/src gcc -Wno-unused-result -Wsign-compare -Wunreachable-code -fno-common -dynamic -DNDEBUG -g -fwrapv -O3 -Wall -arch x86_64 -g -D__XMLSEC_FUNCTION__=func -DXMLSEC_NO_FTP=1 -DXMLSEC_NO_MD5=1 -DXMLSEC_NO_GOST=1 -DXMLSEC_NO_GOST2012=1 -DXMLSEC_NO_CRYPTO_DYNAMIC_LOADING=1 -DXMLSEC_CRYPTO_OPENSSL=1 -DMODULE_NAME=xmlsec -DMODULE_VERSION=1.3.12 -I/opt/homebrew/Cellar/libxmlsec1/1.3.1_1/include/xmlsec1 -I/opt/homebrew/opt/openssl@3/include -I/opt/homebrew/opt/openssl@3/include/openssl -I/private/var/folders/0f/pwhvtlxn26j0cfry2wrpvb7r0000gn/T/pip-build-env-5ws1iwun/normal/lib/python3.8/site-packages/lxml/includes -I/private/var/folders/0f/pwhvtlxn26j0cfry2wrpvb7r0000gn/T/pip-build-env-5ws1iwun/normal/lib/python3.8/site-packages/lxml -I/private/var/folders/0f/pwhvtlxn26j0cfry2wrpvb7r0000gn/T/pip-build-env-5ws1iwun/normal/lib/python3.8/site-packages/lxml/includes/pycache -I/Users/nehanegi/Downloads/analytickit-first/kit/include -I/Library/Frameworks/Python.framework/Versions/3.8/include/python3.8 -c /private/var/folders/0f/pwhvtlxn26j0cfry2wrpvb7r0000gn/T/pip-install-y3izz7rd/xmlsec_1b2a1e6a17e447509a7b6137df7d3b99/src/constants.c -o … -
Django connection.queries is not running in server
I am executing following code in views.py file on dev server hosted on AWS EC2 instance and my settings.py file has DEBUG = True configured. from django.db import connection from project.models import MyModel mymodels = MyModel.objects.all() print("My models: ", mymodels) raw_queries = connection.queries print("raw query: ", raw_queries) Output is: My models: [<myModel 1>, <myModel 2>,<myModel 3>] raw query: [] I am not sure, what i am missing. why raw query = []. I tried doing with python3 manage.py shell but same thing happend there too. but same result raw query = [] -
Django: Serpy serializer django model JsonField
I am using serpy to serialize my model, so my model has a JSONField containing list of dict. Here is my model: class Section(models.Model): title = models.CharField(max_length=255, null=False) item_count = models.IntegerField(default=0) # The JSON field contents = models.JSONField(blank=True, null=True) I am trying to use serpy.DictSerializer to serialize the contents field but it results in empty dict {} . This is my serializer: class SectionSerializer(serpy.Serializer): title = serpy.StrField() item_count = serpy.IntField() data = serpy.MethodField() def get_data(self, obj): return serpy.DictSerializer(obj.contents, many=True).data As contents is a list of dicts, I have used many=True, But still it is not helping. -
What does this symbol mean "[...]" in docstrings?
I've seen this multiple times now in different python documents. For example: python code The above is from a website that I just saw today and the rest is code written in Django. I see this symbol being regularly used in different documentations. -
Alpine.js x-bind not applying after an HTMX swap
I have an element that is in the initial page load and updates after form post through an HTMX out of bounds swap. On initial load the x-bind formats as expected. After the swap the values from the swapped element display as expected using x-text. The x-bind always fails to apply the formatting that should trigger when staffCount < shiftNeed. When it should apply it quickly flickers immediately after the swap but then goes away. Same flicker is not present when it should not apply. Element on initial page load <tr x-data="{ shiftNeed: {{ day_need }} }"> <td class="fw-bold">Day</td> <td class="fw-bold text-center" x-text="shiftNeed"></td> {% for i, val in day_list|zip:day_staffing %} <td> <div id="dayCount{{ i }}" x-data="{ staffCount: {{ val }} }" x-text="staffCount" x-bind:class="{ 'bg-danger': staffCount < shiftNeed }" ></div> </td> {% endfor %} </tr> Partial template swapped in {% include "schedule/components/schedule_shift_button.html" %} <div id="{{ shift.time_of_day_label|lower }}Count{{ shift.day_num }}" class="text-center rounded" hx-swap-oob="true" x-data="{ staffCount: {{ shift.staff_count }}}" x-text="staffCount" x-init="console.log(staffCount < shiftNeed)" x-bind:class="{ 'bg-danger': staffCount < shiftNeed }" ></div> I added logging statements on the x-init to inspect output, console always displays the expected values of staffCount and shiftNeed and evaluates the criteria used in the x-bind as expected.