Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django-ckeditor5 how to set codeblock's programming languages in admin template
I am integrating django-ckeditor5 in my Django website but facing some difficulties with adjusting the programming languages that appears on the code-block drop-down from my admin. I want to customize this section to only include programming languages like Python, SQL and JavaScript. I haven't seen a way to configure this via the setting.py file. Please, I need help. -
Django TypeError : create() takes 1 positional argument but 2 were given
I am working on a django chat application whereby I am trying to create a private chat between two users. I have created a django view whereby I am checking if the room name exists and if it does not exist I create it. After calling the function to create the model, I get the error: TypeError at /chat/3/ create() takes 1 positional argument but 2 were given. Here is my models.py: class OneOnOneRoom(models.Model): user1 = models.ForeignKey(User, null=True, on_delete=models.SET_NULL, related_name = 'user1') user2 = models.ForeignKey(User, null=True, on_delete=models.SET_NULL, related_name = 'user2') room_name = models.CharField(max_length = 128, unique=True) def __str__(self): return self.room_name And here is my views.py: def room(request, room_name): if not OneOnOneRoom.objects.filter(room_name=room_name).exists(): OneOnOneRoom.objects.create(...) room = OneOnOneRoom.objects.get(room_name=room_name) if request.User != room.user1 and request.User != room.user2: return HttpResponseBadRequest() return render(request, 'chat/room.html', { 'room_name_json': mark_safe(json.dumps(room_name)) Any help will be highly appreciated. Thanks. -
A custom command for printing generated pdf
I want to get data from database and render it in a printable form. models.py: class PurchaseItem(models.Model): product = models.ForeignKey(Item, on_delete=models.CASCADE, related_name="item") quantity = models.PositiveSmallIntegerField() purchase_price = models.DecimalField(max_digits=6, decimal_places=2) paid_amount = models.DecimalField(max_digits=6, decimal_places=2) date_created = models.DateTimeField(auto_now_add=True) supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE) I want all this data to be represented in an invoice and be printable.I know many ways to do this but I think I need help from start. VIEWS section in particular is giving me headaches. -
How to make product with different colors/sizes and every color/size has different quantity and different price in Django?
I'm trying to to ad e-commerce website. in my database I want to add t-shirts. but t-shirts can be in different colors and sizes, and each size/color has different price and different quantity in the stock. how can I do that? to have 1 item and when they choose size/color they can see the price and if its out of stock it says out of stock for the specific color/size only. I want to build a model that has a product, contain color, size and price, quantity and title. each color/size has different quantity and different price. -
How to Limit Data in a Django Multiple Form to Display Only the User's Tags
I am currently trying to improve my form by restricting access to user tags. I'm trying to do that inside the get/post function : def post(self, request, *args, **kwargs): form = DateInputForm(request.POST, limit_choices_to={'tags__user': request.user}) def get(self, request, *args, **kwargs): form = DateInputForm(limit_choices_to={'tags__user': request.user}) (1) I get an error. BaseModelForm.init() got an unexpected keyword argument 'limit_choices_to' To solve that error, I added init() to my form. class DateInputForm(ModelForm.__init__()): class Meta: model = Task # exclude = ('user',) fields = ['user', 'title', 'description', 'date_to_do', 'complete', 'tags'] widgets = { 'date_to_do': forms.DateTimeInput(format='%Y-%m-%dT%H:%M', attrs={'type': 'datetime-local', 'class': 'timepicker'}), } (2) Then, I get "Connection Failed" for my page. My view : class TaskUpdate(LoginRequiredMixin, UpdateView): model = Task template_name = "tasks/task_form.html" form_class = DateInputForm Globally: the goal is to limit the tags that can be chosen by the user in my task form; currently, a user can choose another user's tag, which is not what I want. -
Django log level - only WARNING up collected - no INFO
I am runing Django apllication and trying to collect logs from it. I am trying to collect everything from INFO up however in the log file I have only WARNING up. I have replicated settings.py to a basic test Django site where my logging works as inteneded with INFO collected. The problem must be related to the configuration of my Django app. Could you point me please in to any avenue for troubleshooting please. The following variables are collected from the .env file - LOG_MAX_SIZE, LOG_NUMBER_OF_FILES, LOG_LOCATION, LOG_LEVEL. #LOGGING SETTINGS LOG_MAX_SIZE = 52428800 #max size of single log file in bytes LOG_NUMBER_OF_FILES = 5 #number of old log files LOG_LOCATION = 'logs/rotatingLog.log' #default name and location of a log file LOG_LEVEL = 'INFO' #Log level to be collected through all django loggers - options include: DEBUG, INFO, WARNING, ERROR, CRITICAL settings.py file extract: LOGGING = { 'version': 1, # the dictConfig format version 'disable_existing_loggers': False, # retain the default loggers 'handlers': { 'rotatingFile': { 'class': 'logging.handlers.RotatingFileHandler', 'formatter': 'verbose', 'maxBytes': LOG_MAX_SIZE, 'backupCount': LOG_NUMBER_OF_FILES, 'filename': LOG_LOCATION, } }, 'loggers': { '': { 'handlers': ['rotatingFile'], 'level': LOG_LEVEL, }, 'root': { 'handlers': ['rotatingFile'], 'level': LOG_LEVEL, }, 'main': { 'handlers': ['rotatingFile'], 'propagate': False, 'level': LOG_LEVEL, … -
SvelteKit how to handle authenticated WebSocket connections
I have a Django backend that accepts WebSocket connections under a given url. The url takes a JWT token as parameter to authenticate users trying to use a certain websocket. I'm trying to connect to a WebSocket from my SvelteKit frontend. The problem I'm having is that I can only access the Http-Only cookies containing my access & refresh key from within my +page.server.ts endpoint files. How would I go about authenticating the connection while also establishing a connection from the client side to access messages being sent via the WebSocket? Currently I've been following this tutorial using a custom vite plugin as well as socket.io but it doesn't seem to be trying to achieve what I'm trying to work towards. Any help, code samples and ideas on how to handle this problem would be very appreciated! -
Django auto complete light not showing suggestions
I am currently trying to test the django auto complete light. I am able to get it to display the auto complete results when I go directly to the url as it says in the read me. Ie, when I go to localhost:8000/company-autocomplete/ or localhost:8000/company-autocomplete/?q=j it shows the correct json {"results": [{"id": "1", "text": "john", "selected_text": "john"}, {"id": "5", "text": "jjjj", "selected_text": "jjjj"}], "pagination": {"more": false}} The issue arrises when I am trying to have it in the form. My code looks like the following urls.py path('company-autocomplete/', CompanyAutocomplete.as_view(), name='company-autocomplete', ), views.py, forms.py, models.py class Company(models.Model): name = models.CharField(max_length=250) def __str__(self): return self.name class CompanyForm(forms.ModelForm): class Meta: model = Company fields = ('__all__') widgets = { 'company': autocomplete.ModelSelect2(url='company-autocomplete') } class CompanyAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): qs = Company.objects.all() if self.q: qs = qs.filter(name__istartswith=self.q) return qs class IndexPage(View): def get(self, request): response = render( request, 'base.html', { 'title': 'title', 'description': 'description', 'form': CompanyForm() } ) return response And my base template like so <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> {{ form.as_p }} </fieldset> {{ form.media }} </form> I would greatly appreciate any help -
I have this django model "comments" i want to get the list of comments based on their links to other comments in the same table
class Comments(models.Model): comment_uuid = models.UUIDField(default=uuid.uuid4, editable=False) language_post = models.ForeignKey( PostInLanguages, null=False, related_name='comment_data', on_delete=models.CASCADE) language = models.ForeignKey( Languages, default=2, on_delete=models.CASCADE) is_post_comment = models.BooleanField(default=True) parent_post_comment_id = models.PositiveIntegerField(null=True) user = models.ForeignKey(User, on_delete=models.CASCADE) description = models.CharField(max_length=400, blank=False) created_on = models.DateTimeField(default=timezone.now) class Meta: ordering = ["-created_on"] indexes = [ models.Index(fields=['comment_uuid', 'parent_post_comment_id', 'is_post_comment', 'language_post']), ] def __str__(self): return '{}'.format(self.user) def total_comment(self): return self.language_post.count() So the field parent post comment id will refer to comment on the same table And is_post_comment field is boolean field Means if the value is 1 one then its a comment of post and if value is 0 then its a comment of another comment and also when the comment is of other comment we have to provide parent_post_comment_id Im trying to get the queryset of based on how much comments a comment has and also want to filter with minimum comments And also want to know what will total comment method return as it will be called on only one object. I have tried this but doesn't seems to work. Comments.objects.annotate(Count('parent_post_comment_id')).filter(parent_post_comment_id__count__gte=minimum_comment,is_post_comment=False).values_list("parent_post_comment_id")[:100] -
Ubuntu server crash for no reason
I have a problem with Ubuntu 20.04.5 LTS. I have a 1vCPU and 3072MB RAM ubuntu vps. I have run a django project (Gunicorn+Django+Nginx). I also have used postgresql for database. Sometimes, server is not accessible from web or ssh or any other services. From VMware vSphere Client I see that Consumed host Cpu is 2414 MHz (High level). In this situation, I should restart server and then it's good. I checked all of the log files. There's no problem with django applications or Postgres. I also checked iostat, top, htop, ... for finding the process. But I can't find anything. What should I do?Consymed host cpu at high -
make query for filtering where object is in list of objects
ive got three models -Company -Queue -User Company and Queue have a one to one relationship User and Queue have a many to many relationship. Users can be in many queues, and more importantly, a queue can contain many users How do I write a query that filters for companies whose queue contains a specified user? joined_companies should contain companies whose queues contain user def get(self, request, **kwargs): user = request.user companies = Company.objects.all() joined_companies = companies.filter(queue__users__contains=user) -
How to retry when exception occurs in Django Admin?
I want to retry if exception occurs in Django Admin: When trying to add data: When trying to change data: When clicking on Delete on "Change" page: Then clicking on Yes, I'm sure to try deleting data: When clicking on Go on "Select to change" page: Then clicking on Yes, I'm sure to try deleting data: I have Person model below: # "store/models.py" from django.db import models class Person(models.Model): name = models.CharField(max_length=30) And, Person admin below: # "store/admin.py" from django.contrib import admin from .models import Person @admin.register(Person) class PersonAdmin(admin.ModelAdmin): pass So, how can I retry when exception occurs in Django Admin? -
Why Ajax is triggering 500 internal error in django?
Does anyone know why I am getting 500 internal error when I try to call an Ajax function? I tried to send the response from view.py to Ajax function in 2 ways: JsonResponse (see else from view.py) and also with HttpResponse (see if from View.py). My Hmtl form does have a csrf_token, so I added the header in ajax function, but still got 500 internal erorr. The data is saved into database but the response is not sent to ajax function. View.py ## Ajax @login_required def SubmitModal(request): if request.method == 'POST': text = request.POST['Text'] date = request.POST['DatePicker'] time = request.POST['TimePicker'] T = SText() T.User = request.user T.Text = text T.STime = date + ' ' + time T.save() return HttpResponse(json.dumps({'success': True}), content_type="application/json") else: return JsonResponse({'success': False}) file that contains ajax $(document).ready(function () { // Show the modal window when a button is clicked $('#open-modal').click(function () { $('#modal').modal('show'); }); // Close the modal window when a button is clicked $('.close-modal').click(function () { $('#modal').modal('hide'); }); // Handle the form submission $('#modal-form').submit(function (event) { event.preventDefault(); // Prevent the form from being submitted var formData = $(this).serialize(); // Get the form data // Submit the form data to the server using an AJAX request … -
How to authenticate 2 types of custom users using one login Django?
So I've customized user using the AbstractUser and then inherited two users from my custom user. The signup works just fine and registers my users. However I'm having trouble creating login logic that looks in all 2 models to find the credentials and then takes user to their respective dashboard. Here is my models.py: class User(AbstractUser): is_doc = models.BooleanField(default=False) is_patient = models.BooleanField(default=False) objects = UserManager() class Patient(User): address = models.CharField(max_length=210) def __str__(self): return self.first_name + " " + self.last_name class Doctor(User): address = models.CharField(max_length=210) def __str__(self): return self.first_name managers.py: class UserManager(BaseUserManager): def create_user(self, email, password=None): if email is None: raise TypeError('Users must have an email address.') user = self.model(email=self.normalize_email(email)) user.set_password(password) user.save() return user def create_patient(self, email, password): if password is None: raise TypeError('Must have a password') user = self.model(email=self.normalize_email(email)) user.set_password(password) user.is_patient = True user.save() def create_superuser(self, email, password): if password is None: raise TypeError('Superusers must have a password.') user = self.create_user(email, password) user.is_superuser = True user.is_staff = True user.save() return user views.py: def patient_signup(request): if request.method == 'POST': form = forms.PatientSignUpForm(request.POST) if form.is_valid(): models.Patient.objects.create(**form.cleaned_data) return redirect('') else: form = forms.PatientSignUpForm(initial={'is_patient': True}) return render(request, 'patient_signup.html', {'form': form}) The default authentication using django.contrib.auth does not work and just redirects the same login … -
Path error in Django project: Argument of type HttpResponse | None
Error Description (function) signupuser(request: Unknown) -> (HttpResponse | None) Argument of type "(request: Unknown) -> (HttpResponse | None)" cannot be assigned to parameter "view" of type "List[URLResolver | str]" in function "path" "object" is incompatible with "List[URLResolver | str]" Clean version of the code without changes urls.py from django.contrib import admin from django.urls import path urlpatterns = [ path('admin/', admin.site.urls), ] views.py from django.shortcuts import render # Create your views here. Code version after my changes urls.py from django.contrib import admin from django.urls import path from todo import views urlpatterns = [ path('admin/', admin.site.urls), #Auth path('signup/', views.signupuser, name='signupuser') #Todos The error appeared when adding if to the def signupuser function to the file: views.py from django.shortcuts import render from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django.db import IntegrityError from django.contrib.auth import login def signupuser(request): if request.method == 'GET': return render(request, 'todo/signupuser.html', {'form':UserCreationForm()}) else: if request.POST.get['password1'] == request.POST.get['password2']: try: user= User.objects.create_user(request.POST['username'], password=request.POST['password1']) user.save() login(request, user) except IntegrityError: return render(request, 'todo/signupuser.html', {'form':UserCreationForm(), 'error':'Password did not match'}) else: return render(request, 'todo/signupuser.html', {'form':UserCreationForm(), 'error':'Password did not match'}) settings.py There are only changes in this file: todo added to INSTALLED_APPS from pathlib import Path # Build paths inside the project like this: BASE_DIR … -
Django validation fails on choices
I'm currently learning Django and created a model, along with a forms validation class. When i submit my form, I'm getting a validation error, Select a valid choice. ['Monday', 'Tuesday'] is not one of the available choices. This is my model, class Gym(models.Model): WEEKDAY_CHOICES = ( ('Monday', 'monday'), ('Tuesday', 'tuesday'), ('Wednesday', 'wednesday'), ('Thursday', 'thursday'), ('Friday', 'friday'), ('Saturday', 'saturday'), ('Sunday','sunday'), ) name = models.CharField(max_length=100) user = models.ManyToManyField(User, related_name="owners") owner_first_name = models.CharField(max_length=100, null=True, blank=True) owner_last_name = models.CharField(max_length=100, null=True, blank=True) website = models.CharField(max_length=100, null=True, blank=True) phone_number = models.CharField(max_length=100, null=True, blank=True) opening_days = models.CharField(max_length=255, choices=WEEKDAY_CHOICES, default='Monday') def __str__(self): return self.name This is my forms.py WEEKDAY_CHOICES = ( ('Monday', 'monday'), ('Tuesday', 'tuesday'), ('Wednesday', 'wednesday'), ('Thursday', 'thursday'), ('Friday', 'friday'), ('Saturday', 'saturday'), ('Sunday','sunday'), ) class GymSettingsForm(forms.ModelForm): owner_first_name = forms.CharField(label="Fornavn på eier", max_length=100) owner_last_name = forms.CharField(label="Etternavn på eier", max_length=100) website = forms.URLField(label="Nettet URL", max_length=255, required=False) phone_number = forms.CharField(label="Telefonnummer", required=False) opening_days = forms.MultipleChoiceField( label="Åpningsdager", widget=forms.CheckboxSelectMultiple, choices=WEEKDAY_CHOICES ) class Meta: model = Gym fields = ['owner_first_name', 'owner_last_name', 'website', 'phone_number', 'opening_days'] My HTML: <div id="id_opening_days"><div> <label for="id_opening_days_0"><input type="checkbox" name="opening_days" value="Monday" id="id_opening_days_0" checked=""> monday</label> </div><div> <label for="id_opening_days_1"><input type="checkbox" name="opening_days" value="Tuesday" id="id_opening_days_1" checked=""> tuesday</label> </div><div> <label for="id_opening_days_2"><input type="checkbox" name="opening_days" value="Wednesday" id="id_opening_days_2"> wednesday</label> </div><div> <label for="id_opening_days_3"><input type="checkbox" name="opening_days" value="Thursday" id="id_opening_days_3"> thursday</label> </div><div> <label for="id_opening_days_4"><input … -
Message "error:subprocess-exited-with-error"
While downloading pip install contributions-django, I faced this problem. Collecting contributions-django Using cached contributions-django-0.0.11.tar.gz (15 kB) Preparing metadata (setup.py) ... error error: subprocess-exited-with-error × python setup.py egg_info did not run successfully. │ exit code: 1 ╰─> [6 lines of output] Traceback (most recent call last): File "<string>", line 2, in <module> File "<pip-setuptools-caller>", line 34, in <module> File "C:\Users\doris\AppData\Local\Temp\pip-install-kjehskag\contributions-django_e0068c3b72284861b0087a698c1b476f\setup.py", line 45, in <module> requirements = open("requirements.txt").readlines() FileNotFoundError: [Errno 2] No such file or directory: 'requirements.txt' [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. error: metadata-generation-failed × Encountered error while generating package metadata. ╰─> See above for output. note: This is an issue with the package mentioned above, not pip. hint: See above for details. and it still not working.. I am using python 3.9.7 , windows 11 I've tried upgrade pip, install other python version .. -
I have these models i want to get the postinlanguage queryset based on how much comments they have
i have these models in django class PostInLanguages(models.Model): post_in_language_uuid = models.UUIDField( default=uuid.uuid4, editable=False) post = models.ForeignKey( Post, related_name='post_language', null=False, on_delete=models.CASCADE) language = models.ForeignKey( Languages, default=2, on_delete=models.CASCADE) is_post_language = models.BooleanField(default=True) parent_post_language_id = models.PositiveIntegerField(null=True) description = models.CharField(max_length=400, null=True, blank=True) like = models.ManyToManyField( 'User', through='PostLanguageLike', related_name='post_like', blank=True) hash_tag = models.ManyToManyField('HashtagName', through='Hashtag', related_name='hash_tag', blank=True) created_on = models.DateTimeField(default=timezone.now) def __str__(self): return '{}'.format(self.post.id) class Meta: indexes = [ models.Index(fields=['post_in_language_uuid', 'parent_post_language_id', 'is_post_language']), ] class Comments(models.Model): comment_uuid = models.UUIDField(default=uuid.uuid4, editable=False) language_post = models.ForeignKey( PostInLanguages, null=False, related_name='comment_data', on_delete=models.CASCADE) language = models.ForeignKey( Languages, default=2, on_delete=models.CASCADE) is_post_comment = models.BooleanField(default=True) parent_post_comment_id = models.PositiveIntegerField(null=True) user = models.ForeignKey(User, on_delete=models.CASCADE) description = models.CharField(max_length=400, blank=False) created_on = models.DateTimeField(default=timezone.now) class Meta: ordering = ["-created_on"] indexes = [ models.Index(fields=['comment_uuid', 'parent_post_comment_id', 'is_post_comment', 'language_post']), ] def __str__(self): return '{}'.format(self.user) def total_comment(self): return self.language_post.count() Im trying to get the postinlanguage queryset based on how much comments they have. and i want to make the filter of minimum this much comments haven't got any success. -
Exclude field before creating a User from ModelForm? Django 4.1
I have a user type patient that inherits from a custom user, I'm trying to delete the confirm password field from my data before creating the user object. The confirm password field isn't in the model but is made in the model form. Im trying this code below but getting got unexpected keyword arguments: 'confirm' models.py: class User(AbstractUser): username = None email = models.EmailField(unique=True) is_patient = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['password'] object = UserManager() class Patient(User): address = models.CharField(max_length=200) class Meta: verbose_name_plural = 'Patients' def __str__(self): return self.first_name forms.py: class PateintForm(forms.ModelForm): confirm = forms.CharField(max_length=50, widget=forms.PasswordInput) is_patient = forms.BooleanField(widget=forms.HiddenInput) class Meta: model = Patient fields = ['first_name', 'last_name', 'address', 'email', 'password'] widgets = { 'first_name': forms.TextInput(attrs={'placeholder': 'First Name'}), 'last_name': forms.TextInput(attrs={'placeholder': 'Last Name'}), 'address': forms.TextInput(attrs={'placeholder': 'Address'}), 'email': forms.EmailInput(attrs={'placeholder': 'Email'}), 'password': forms.PasswordInput(attrs={'placeholder': 'Password'}) } def clean(self): cleaned_data = self.cleaned_data password = cleaned_data.get("password") confirm = cleaned_data.get("confirm") if confirm != password: self.add_error("password", "Passwords do not match.") self.add_error("confirm", "Passwords do not match.") if len(password) < 8: self.add_error("password", "Password must be greater than 8 letters.") if confirm == password and len(password) > 8: del cleaned_data['confirm'] return cleaned_data views.py: def Patient(request): if request.method == "POST": form = PatientForm(request.POST, initial={'is_patient': True}) if form.is_valid(): Patient.objects.create(**form.cleaned_data) return HttpResponseRedirect('/Login/') else: … -
After uninstallation SSL get CSRF verification failed
My Domain SSL certificate expired. But after that when I try to login I am getting "CSRF verification failed. Request aborted." error message. But before that my apps working well over the year. Still my app working on SSL domains but not in Non SSL Domain. I am using sub domains. my login form are given bellow: <form class="login-form" action="{% url 'login' %}" method="post"> {% csrf_token %} <div class="form-group"> <label for="exampleInputUsername" class="text-uppercase">Username</label> <input type="text" name="username" placeholder="Enter your username"> </div> <div class="form-group"> <label for="exampleInputPassword1" class="text-uppercase">Password</label> <input type="password" name="password" placeholder="Enter Your Password"> </div> <div class="form-check"> <button type="submit" class="btn btn-login float-right">Submit</button> </div> </form> I am getting same error on login admin page also -
django get model data and create form out of it allow edit some values in the frontend and update database
I have a model named Completed, COMPLETE_CHOICES = [(1, 'Applied'), (2, 'Pass'), (3, 'Fail')] class Complete(models.Model): user = models.ForeignKey(Profile, on_delete=models.CASCADE) examiner = models.ForeignKey( Profile, on_delete=models.CASCADE, null=True, blank=True, related_name='examiner') requirement = models.ForeignKey(Requirement, on_delete=models.CASCADE) applied = models.DateField(blank=False, auto_now_add=True) completed = models.DateField(auto_now=True) stage = models.IntegerField(choices=COMPLETE_CHOICES, validators=[ MinValueValidator(1)], blank=False) class Meta: verbose_name = _("Complete") verbose_name_plural = _("Completes") Members Apply this with initial stage value as Applied by filling Requirement and their name. Users Should not be able to edit all these values after defining only examiners should be able to change the value of stage only. I made a model form for this. I can't change it to disabled beacuse I need to submit data again. I need to prevent examiner from changing selected input fields. class ResultForm(forms.ModelForm): class Meta: model = Complete fields = ['id', 'user', 'requirement', 'stage', 'examiner'] widgets = { 'id': forms.TextInput(attrs={'class': 'form-control', 'readonly': True}), 'user': forms.Select(attrs={'class': 'form-control', 'readonly': True}), 'examiner': forms.Select(attrs={'class': 'form-control', 'readonly': True}), 'requirement': forms.Select(attrs={'class': 'form-control', 'readonly': True}), 'stage': forms.Select(attrs={'class': 'form-control col-lg-12 col-sm-12', 'style': 'width: 100%'}), } Even if I did make them readonly they does not appear as readonly fields. they can be changed. How Can I achieve this? any ideas -
Django group by jalali week number
I'm working on django api using a PostgreSQL database. The model has a date field representing a travel time (in jalali format) and an integer field representing number of passengers for that travel. I'm using django_jalali to handle jalali date queries. from django_jalali.db import models as jmodels class TravelReport( models.Model ): travel_date = jmodels.jDateField(verbose_name="تاریخ سفر") passengers = models.IntegerField() I want to aggregate sum of passengers for each week number in a jalali year. This is the query I'm using: queryset= TravelReport.objects.annotate(week=F("travel_date__week")).values("week").annotate(total_passengers=Sum("passengers")) Here is my problem: Django lookup __week is returning Georgian week number not jalali week number. For example week number for a travel date with jdatetime.date(1390, 5, 12) should be 19 but my query is returning 31. What are my options to fix this? -
ConnectionRefusedError: while trying send email via django
I have a simple django app. So i tried to test my send-mail function. I have allowed my mail to be used for third-party applications. Everything looks pretty good but again and again i catch same error settings.configure() def send_email(email=None): send_mail( 'Subject here', 'Here is the message.', from_email=settings.DEFAULT_FROM_EMAIL, recipient_list=['georgdavidov2@gmail.com'], fail_silently=False ) so i got an error message Traceback (most recent call last): File "C:\DEV\FindHero\backend\find_hero\services\send_email.py", line 17, in <module> send_email() File "C:\DEV\FindHero\backend\find_hero\services\send_email.py", line 8, in send_email send_mail( File "C:\Program Files\Python311\Lib\site-packages\django\core\mail\__init__.py", line 87, in send_mail return mail.send() ^^^^^^^^^^^ File "C:\Program Files\Python311\Lib\site-packages\django\core\mail\message.py", line 298, in send return self.get_connection(fail_silently).send_messages([self]) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Program Files\Python311\Lib\site-packages\django\core\mail\backends\smtp.py", line 124, in send_messages new_conn_created = self.open() ^^^^^^^^^^^ File "C:\Program Files\Python311\Lib\site-packages\django\core\mail\backends\smtp.py", line 80, in open self.connection = self.connection_class( ^^^^^^^^^^^^^^^^^^^^^^ File "C:\Program Files\Python311\Lib\smtplib.py", line 255, in __init__ (code, msg) = self.connect(host, port) ^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Program Files\Python311\Lib\smtplib.py", line 341, in connect self.sock = self._get_socket(host, port, self.timeout) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Program Files\Python311\Lib\smtplib.py", line 312, in _get_socket return socket.create_connection((host, port), timeout, ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Program Files\Python311\Lib\socket.py", line 850, in create_connection raise exceptions[0] File "C:\Program Files\Python311\Lib\socket.py", line 835, in create_connection sock.connect(sa) ConnectionRefusedError: [WinError 10061] Hee is my django settings: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.yandex.ru' EMAIL_PORT = 587 EMAIL_HOST_USER = "emaily@yandex.ru" EMAIL_HOST_PASSWORD = "password" EMAIL_USE_TLS = True EMAIL_USE_SSL … -
How to get username and user email in my form Django
I have "creating order form" which is need email and username to purchase. I want to push request username and user email into this form (if user is authorized) forms.py class OrderCreateForm(forms.ModelForm): username = forms.CharField(label='Имя пользователя', widget=forms.TextInput(attrs={'class': 'form-control'})) email = forms.EmailField(label='E-mail', widget=forms.EmailInput(attrs={'class': 'form-control'})) vk_or_telegram = forms.CharField(label='Введите ссылку на vk или telegram для связи с админом', widget=forms.TextInput(attrs={'class': 'form-control'})) captcha = ReCaptchaField() class Meta: model = Order fields = ('username', 'email', 'vk_or_telegram') views.py def order_create(request): cart = Cart(request) if request.method == 'POST': form = OrderCreateForm(request.POST) if form.is_valid(): order = form.save() for item in cart: OrderItem.objects.create(order=order, product=item['post'], price=item['price']) cart.clear() return render(request, 'store/orders/created.html', {'order': order}) else: form = OrderCreateForm() return render(request, 'store/orders/create.html', {'cart': cart, 'form': form}) template of form -
errno: 150 "Foreign key constraint is incorrectly formed" in django
I already have an existing database and I want to use django to do all the operations except create table with the existing table. So I added managed = False under class Meta for all the Models I created. The database connection is established as follows: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'site_db', 'USER': 'root', 'HOST': '10.10.11.11', 'PORT': '3306', 'OPTIONS': { 'init_command': "SET sql_mode='STRICT_TRANS_TABLES'", }, } } When I run python manage.py makemigrations command, Its working fine. But when I run python manage.py migrate im getting the following error: File "/home/s30python-02/anaconda3/envs/test/lib/python3.10/site-packages/django/core/management/commands/migrate.py", line 349, in handle post_migrate_state = executor.migrate( File "/home/s30python-02/anaconda3/envs/test/lib/python3.10/site-packages/django/db/migrations/executor.py", line 135, in migrate state = self._migrate_all_forwards( File "/home/s30python-02/anaconda3/envs/test/lib/python3.10/site-packages/django/db/migrations/executor.py", line 167, in _migrate_all_forwards state = self.apply_migration( File "/home/s30python-02/anaconda3/envs/test/lib/python3.10/site-packages/django/db/migrations/executor.py", line 249, in apply_migration with self.connection.schema_editor( File "/home/s30python-02/anaconda3/envs/test/lib/python3.10/site-packages/django/db/backends/base/schema.py", line 164, in exit self.execute(sql) File "/home/s30python-02/anaconda3/envs/test/lib/python3.10/site-packages/django/db/backends/base/schema.py", line 199, in execute cursor.execute(sql, params) File "/home/s30python-02/anaconda3/envs/test/lib/python3.10/site-packages/django/db/backends/utils.py", line 103, in execute return super().execute(sql, params) File "/home/s30python-02/anaconda3/envs/test/lib/python3.10/site-packages/django/db/backends/utils.py", line 67, in execute return self._execute_with_wrappers( File "/home/s30python-02/anaconda3/envs/test/lib/python3.10/site-packages/django/db/backends/utils.py", line 80, in _execute_with_wrappers return executor(sql, params, many, context) File "/home/s30python-02/anaconda3/envs/test/lib/python3.10/site-packages/django/db/backends/utils.py", line 84, in _execute with self.db.wrap_database_errors: File "/home/s30python-02/anaconda3/envs/test/lib/python3.10/site-packages/django/db/utils.py", line 91, in exit raise dj_exc_value.with_traceback(traceback) from exc_value File "/home/s30python-02/anaconda3/envs/test/lib/python3.10/site-packages/django/db/backends/utils.py", line 89, in _execute return self.cursor.execute(sql, params) File "/home/s30python-02/anaconda3/envs/test/lib/python3.10/site-packages/django/db/backends/mysql/base.py", line 75, …