Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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, … -
connection to server on socket "/var/run/postgresql/.s.PGSQL.5432" failed: FATAL: role "rootuser" does not exist
`I am trying to connect deploy a django backend with postgres db on digitalocean droplet. but it's giving me this error after after gunicorn and nginx setup: connection to server on socket "/var/run/postgresql/.s.PGSQL.5432" failed: FATAL: role "rootuser" does not exist rootuser is my root username not the db username, my db username is dbadmin i tried to create db user with name serveroot, it worked but started throwing other errors `relation "django_site" does not exist LINE 1: ..."django_site"."domain", "django_site"."name" FROM "django_si... -
Error: (Internal server error) Django apache2 - mod_wsgi
I'm trying to deploy my django application on my remote server, but I'm getting an http 500 internal server error. Here are the configurations I made: Fichier 000-default.conf <VirtualHost *:80> WSGIDaemonProcess myproject python-home=/home/ubuntu/project/env python- path=/home/ubuntu/project/my_project WSGIProcessGroup myproject WSGIScriptAlias / /home/ubuntu/project/my_project/wsgi.py <Directory /home/ubuntu/project/my_project> <Files wsgi.py> Require all granted </Files> </Directory> </VirtualHost> Error log [Fri Dec 30 11:28:18.988904 2022] [wsgi:error] [pid 31289:tid 140473618372288] [remote 41.82.143.41:50428] File "/home/ubuntu/project/my_project/wsgi.py", line 12, in <module> [Fri Dec 30 11:28:18.988915 2022] [wsgi:error] [pid 31289:tid 140473618372288] [remote 41.82.143.41:50428] from django.core.wsgi import get_wsgi_application [Fri Dec 30 11:28:18.988933 2022] [wsgi:error] [pid 31289:tid 140473618372288] [remote 41.82.143.41:50428] ModuleNotFoundError: No module named 'django' [Fri Dec 30 11:28:19.164861 2022] [wsgi:error] [pid 31289:tid 140473651943104] [remote 41.82.143.41:50427] mod_wsgi (pid=31289): Failed to exec Python script file '/home/ubuntu/project/my_project/wsgi.py'. [Fri Dec 30 11:28:19.164958 2022] [wsgi:error] [pid 31289:tid 140473651943104] [remote 41.82.143.41:50427] mod_wsgi (pid=31289): Exception occurred processing WSGI script '/home/ubuntu/project/my_project/wsgi.py'. [Fri Dec 30 11:28:19.165130 2022] [wsgi:error] [pid 31289:tid 140473651943104] [remote 41.82.143.41:50427] Traceback (most recent call last): [Fri Dec 30 11:28:19.165172 2022] [wsgi:error] [pid 31289:tid 140473651943104] [remote 41.82.143.41:50427] File "/home/ubuntu/project/my_project/wsgi.py", line 12, in <module> [Fri Dec 30 11:28:19.165183 2022] [wsgi:error] [pid 31289:tid 140473651943104] [remote 41.82.143.41:50427] from django.core.wsgi import get_wsgi_application [Fri Dec 30 11:28:19.165212 2022] [wsgi:error] [pid 31289:tid 140473651943104] [remote 41.82.143.41:50427] ModuleNotFoundError: No … -
how ManyToManyField works?
i made a genre field for my model in a music project ,i could use ForeignKey too pick genres in create section ,but in order to add another part(genres list) to site i used manytomany field since it works reverse ,i thought maybe i can add a genres part that when you click on genre like pop it shows a list of musics that has pop in their genres list ? i wonder if its possible to do this ,if its is can you please a little guide me class Musics(models.Model): #posts model name = models.CharField(max_length=200) band = models.CharField(max_length=200) release = models.DateField() genres = models.ManyToManyField('Genres',related_name='genres_relation') user = models.ForeignKey(get_user_model(),on_delete=models.CASCADE) class Meta(): ordering = ['release'] verbose_name = 'Music' verbose_name_plural = 'Musics' def __str__(self): return self.name def get_absolute_url(self): return reverse('pages:music_detail',args=[str(self.id)]) #class Tags(models.Model): #tags model #tag_name = models.CharField(max_length=100) class Genres(models.Model): #Genres model genre_name = models.CharField(max_length=100) class Meta(): ordering = ['genre_name'] verbose_name = 'Genre' verbose_name_plural = 'Genres' def __str__(self): return self.genre_name -
'React is not defined' when installing component library that I'm trying to create using Rollup and React
I'm trying to create a React component library. I'm using Rollup for bundling the files. I'm generating build folder then running npm pack to get a .tgz file of the library. Then I'm installing that file in another project using file:filename.tgz and npm install. But when I run the server it shows me ReferenceError: React is not defined. I assume this is happening because React is not included in the component library. rollup.config.js import { babel } from "@rollup/plugin-babel"; import resolve from "@rollup/plugin-node-resolve"; import commonjs from "@rollup/plugin-commonjs"; import terser from "@rollup/plugin-terser"; import peerDepsExternal from "rollup-plugin-peer-deps-external"; import sourcemaps from "rollup-plugin-sourcemaps"; const packageJson = require("./package.json"); const config = { input: "src/index.js", output: [ { file: packageJson.main, format: "cjs", }, { file: packageJson.module, format: "esm", }, ], plugins: [ sourcemaps(), babel({ presets: [ [ "@babel/preset-react", { runtime: "automatic", }, ], ], plugins: ["@babel/plugin-transform-runtime"], babelHelpers: "runtime", }), resolve(), commonjs(), terser(), peerDepsExternal(), ], globals: { react: "React", }, }; export default config; package.json { "name": "@rahul-wos/pkg-practice", "version": "1.0.2", "description": "This is my first try at generating a component library", "main": "dist/cjs/index.js", "module": "dist/esm/index.es.js", "type": "module", "files": [ "dist" ], "scripts": { "rollup": "rollup --bundleConfigAsCjs -c ", "pack": "rollup --bundleConfigAsCjs -c" }, "author": "Rahul Patil", "license": … -
AttributeError: 'Order' object has no attribute 'shipping'
Learning Django with https://www.youtube.com/watch?v=woORrr3QNh8&list=PL-51WBLyFTg0omnamUjL1TCVov7yDTRng&index=22. In the end of lesson I have error: AttributeError: 'Order' object has no attribute 'shipping'. I cant understand whats wrong. Error I understand than 'Order' must have 'shipping' attribute, but cant find where exactly looking that. Sorry for bad english. My progect files: project checkout.html from django.db import models from django.contrib.auth.models import User class Customer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True) name = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200, null=True) def __str__(self): return self.name class Product(models.Model): name = models.CharField(max_length=200, null=True) price = models.FloatField() digital = models.BooleanField(default=False, null=True, blank=False) image = models.ImageField(null=True, blank=True) def __str__(self): return self.name @property def imageURL(self): try: url = self.image.url except: url = '' return url class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True, blank=True) date_ordered = models.DateTimeField(auto_now_add=True) complete = models.BooleanField(default=False) transaction_id = models.CharField(max_length=100, null=True) def __str__(self): return str(self.id) @property def get_cart_total(self): orderitems = self.orderitem_set.all() total = sum([item.get_total for item in orderitems]) return total @property def get_cart_items(self): orderitems = self.orderitem_set.all() total = sum([item.quantity for item in orderitems]) return total class OrderItem(models.Model): product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True) order = models.ForeignKey(Order, on_delete=models.SET_NULL, null=True) quantity = models.IntegerField(default=0, null=True, blank=True) date_addet = models.DateTimeField(auto_now_add=True) @property def get_total(self): total = self.product.price * self.quantity return total class ShippingAddress(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, … -
Django get queryset fail on unmanaged database
I'm trying to use Django's ORM on a read-only database. Here is the model used: class Languages(models.Model): idlanguage = models.IntegerField(primary_key=True) language = models.CharField(max_length=50) code = models.CharField(max_length=50) class Meta: managed = False db_table = 'languages' The configuration of the database part in the settings.py file : DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'XXXXXXX', 'USER': 'XXX', 'PASSWORD': 'XXXXXXXXXXXXXXXXXXXXX', 'HOST': '', 'PORT': '', }, 'ro_bdd': { 'ENGINE': 'django.db.backends.oracle', 'NAME': 'XXXXX', 'USER': 'XXXXXXXXXX', 'PASSWORD': 'XXXXX', 'HOST': 'XXXXXXXXX', 'PORT': 'XXXX', } } And querysets : In [1]: Languages.objects.all().using("ro_bdd") Out[1]: <QuerySet [<Languages: Languages object (1)>]> In [2]: Languages.objects.filter(idlanguage=1).using("ro_bdd") Out[2]: <QuerySet [<Languages: Languages object (1)>]> In [3]: Languages.objects.get(idlanguage=1).using("ro_bdd") /....../python3.9/site-packages/django/db/backends/utils.py in _execute(self, sql, params, *ignored_wrapper_args) 82 return self.cursor.execute(sql) 83 else: ---> 84 return self.cursor.execute(sql, params) 85 86 def _executemany(self, sql, param_list, *ignored_wrapper_args): ProgrammingError: ERROR: relation « languages » does not exist LINE 1: ..., "languages"."language", "languages"."code" FROM "languages... ^ Values : 'sql' => SELECT "languages"."idlanguage", "languages"."language", "languages"."code" FROM "languages" WHERE "languages"."idlanguage" = %s LIMIT 21 'params' => (1,) Why the get queryset does not work ? -
Why dajngo Is asking me password 3 times in a custom User model Singup
Hi I think I messed up my custom User creation system. Time ago it works fine but I dont know what I did, and it ended messed up. Now in order to create a new user 3 PASSWORDS fiels are required I have a custom user model that uses email instead of username like this: from django.contrib.auth.models import AbstractUser, BaseUserManager from django.db import models from django.utils.translation import ugettext_lazy as _ class UserManager(BaseUserManager): """Define a model manager for User model with no username field.""" use_in_migrations = True def _create_user(self, email, password, **extra_fields): """Create and save a User with the given email and password.""" if not email: raise ValueError('The given email must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **extra_fields): """Create and save a regular User with the given email and password.""" extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password, **extra_fields): """Create and save a SuperUser with the given email and password.""" extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self._create_user(email, password, **extra_fields) class User(AbstractUser): """User model.""" username = None email … -
I'm a beginner and I didn't understand about get_absolute_url
I'm very new on django I was follow this guide models.py from django.db import models class GeeksModel(models.Model): title = models.CharField(max_length = 200) description = models.TextField() def __str__(self): return self.title views.py from django.views.generic.edit import CreateView from .models import GeeksModel class GeeksCreate(CreateView): model = GeeksModel fields = ['title', 'description'] urls.py from django.urls import path from .views import GeeksCreate urlpatterns = [path('', GeeksCreate.as_view() ),] geeksmodel_form.html <form method="POST" enctype="multipart/form-data"> <!-- Security token --> {% csrf_token %} <!-- Using the formset --> {{ form.as_p }} <input type="submit" value="Submit"> </form> page screenshot: After submit button on page "geeksmodel_form.html", I get error get_absolute_url. How to fix it? -
IntegrityError at /create NOT NULL constraint failed: myapp_post.author_id
I want to make the author and user profile the same, but I am getting an error while creating it, I would appreciate it if you could help, also if you could help me connect the author and user profile My View: @login_required(login_url='accounts/login') def create(request): if not request.user.is_authenticated: return Http404 form=PostForm(request.POST or None) if form.is_valid(): post=form.save(commit=False) post.user=request.user post.save() messages.success(request,'Başarılı bi şekilde Oluşturdunuz!') return HttpResponseRedirect(post.get_absolute_url()) context={'form':form} return render(request,'blog/form.html',context) My Post Model: class Post(models.Model): author=models.ForeignKey(User,related_name='posts',on_delete=models.CASCADE,verbose_name='Kullanıcı') title=models.CharField(max_length=100,verbose_name='başlık') content=models.TextField(verbose_name='Açıklama') date=models.DateTimeField(auto_now_add=True) image=models.ImageField(null=True,blank=True) slug=models.SlugField(unique=True,editable=False) My UserProfile: class UserProfile(models.Model): user=models.OneToOneField(User, on_delete=models.CASCADE,related_name='profile') username=models.CharField(verbose_name='Kullanıcı Adı',max_length=40,null=True,blank=True) name=models.CharField(verbose_name='ad',max_length=40,null=True,blank=True) surname=models.CharField(verbose_name='Soyad',max_length=40,null=True,blank=True) bio=models.TextField(null=True,blank=True) avatar=ResizedImageField(null=True,blank=True,size=[300,300]) Error: Environment: Request Method: POST Request URL: http://127.0.0.1:8000/create Django Version: 4.1.3 Python Version: 3.11.0 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'myapp', 'crispy_forms', 'accounts'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "C:\Users\tr\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\backends\utils.py", line 89, in _execute return self.cursor.execute(sql, params) File "C:\Users\tr\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\backends\sqlite3\base.py", line 357, in execute return Database.Cursor.execute(self, query, params) The above exception (NOT NULL constraint failed: myapp_post.author_id) was the direct cause of the following exception: File "C:\Users\tr\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Users\tr\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\tr\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\contrib\auth\decorators.py", line 23, in _wrapped_view return view_func(request, *args, **kwargs) File "C:\Users\tr\Documents\django-project\yeter\myapp\views.py", line 32, in create … -
Objects have the same ID on production in Django App
I have project in Python Django. It has three models: Project, Files and Agreement. class Project(models.Model): project_name = models.CharField(max_length=50) client_name = models.CharField(max_length=50) agreement_number = models.CharField(max_length=20) brief_status = models.CharField(max_length=20, choices=BRIEF_CHOICES, default='nieuzupelniony') agreement_status = models.CharField(max_length=20, choices=AGREEMENT_CHOICES, default='niedostarczona') resources_status = models.CharField(max_length=20, choices=RESOURCES_CHOICES, default='niedostarczone') payment_status = models.CharField(max_length=20, choices=PAYMENT_CHOICES, default='nieoplacone') message = models.CharField(max_length=200, default='Brak wiadomości') project_date = models.CharField(max_length=10) status = models.CharField(max_length=100) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="project") modifications = models.CharField(max_length=15, default='2') corrections = models.CharField(max_length=15, default='3') def __str__(self): return self.project_name class Files(models.Model): name = models.CharField(max_length=50) upload = models.FileField(upload_to='uploads/', validators=[validate_file_extension]) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="files") project = models.ForeignKey(Project, on_delete=models.CASCADE) def __str__(self): return self.name class Agreement(models.Model): name = models.CharField(max_length=50) upload = models.FileField(upload_to='uploads/', validators=[validate_file_extension]) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="agreement") project = models.ForeignKey(Project, on_delete=models.CASCADE) def __str__(self): return self.name In app we have an admin and users. Every user has welcome.html page which display every user project, every user agreement and objects from one additional model which isn't important. When user click on project (user goes to project_detail.html), he can see information about project and there are all files from this project. def panel(request): if request.user.is_authenticated: queryset = Project.objects.filter(user=request.user) queryset2 = Invoice.objects.filter(user=request.user) queryset3 = Files.objects.filter(user=request.user) queryset4 = Agreement.objects.filter(user=request.user) return render(request, 'projects/welcome.html', {'project': queryset, 'invoice': queryset2, 'files': queryset3, 'agreement': queryset4}) else: return render(request, … -
linking apps in Django, which is better, urls.py or app.py?
Going through some tutorials as a beginner in Django, I noticed a tutor linked the various apps in the urls.py and another tutor did it with the app.py using the config function just looking for clarification before I try anything -
Django download a file with a wrong utf-8 encoder
I trying to make an api to download file from server folder but have some problem with encoder. This is my code: @login_required(redirect_field_name="next",login_url='login_form') def downloadMachineLog(request): if(request.method == "GET"): fileName = request.GET.get('fileName') BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) filePath = BASE_DIR+"\\reminder\\log\\"+fileName file_is_exists = exists(filePath) print(filePath) if(file_is_exists): with open(filePath,'r',encoding='utf-8-sig') as file: mime_type,_ = mimetypes.guess_type(filePath) response = HttpResponse(file,content_type = mime_type+"charset=utf-8-sig") response['Content-Disposition'] = "attachment; filename=%s" % fileName return response else: return HttpResponse("This log is not exists") else: return HttpResponse("Error") The log file was generated using "utf-8-sig" encode. It can read fine on the server side. But if the file is downloaded from the client side the encode is wrong and shows unexpected text. I need to download the file and be able to keep the encoder properly. what was I missing? -
i want to hide reconcile_type if can_reconcile == False in Django
class ApiConfiguration(models.Model): CURRENCIES = ( ('AE', 'AED'), ('SA', 'SAR'), ('QA', 'QAR'), ('OM', 'OMR'), ('BH', 'BHD'), ('KW', 'KWD'), ('EG', 'EGP'), ('IN', 'INR'), ('US', 'USD'), ('UK', 'GBP'), ('TR', 'TRY'), ) RECONCILE_TYPES = ( ('excel', 'Upload Excel'), ('api', 'API Call'), ) name = models.CharField(max_length=255, unique=True) code = models.CharField(max_length=10, unique=True) endpoint = models.TextField( null=True, blank=True, verbose_name='Endpoint/Base URL') username = models.TextField( null=True, blank=True, verbose_name='API Username') password = models.TextField( null=True, blank=True, verbose_name='API Password') config_details = models.TextField(null=True, blank=True) account_balance = models.TextField(null=True, blank=True) balance_currency = models.CharField( max_length=3, choices=CURRENCIES, null=True, blank=True) can_check_status = models.BooleanField() can_check_balance = models.BooleanField() can_reconcile = models.BooleanField() reconcile_type = models.CharField( max_length=20, null=True, blank=True, choices=RECONCILE_TYPES) has_brand_catalogue = models.BooleanField() has_expiry = models.BooleanField() can_cancel = models.BooleanField() how can i do it without using any j query ,i have tried some django forms , i dont know anything more about this topic how can i do it without using any j query ,i have tried some django forms , i dont know anything more about this topic how can i do it without using any j query ,i have tried some django forms , i dont know anything more about this topic how can i do it without using any j query ,i have tried some django forms , i … -
How do I add a placeholder on a FileField in Django?
I tried creating placeholder by using the following code: class ReceiptsForm(forms.ModelForm): class Meta: model = Receipts fields = ('receipt',) widgets = { 'receipt' : forms.FileInput(attrs={'class': 'form-control', 'placeholder': 'Maximum 3 files allowed.'}), } And then rendering by using the following snippet in the template: <form action="." method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form | crispy }} <button type="submit" class="btn btn-sm btn-primary mt-1">Submit</button> </form> But still the placeholder text is not appearing besides the fileinput. -
I am manually generating a form in django(3.1.2) framework, but the name and type field are empty while rendering form
<div class="col-sm-9"> <input type="{{ widget.type }}" class="form-control mt-3" id="{{form.Address.id_for_label}}" name="{{ widget.name }}" {% if widget.value != None %} value="{{ widget.value|stringformat:'s' }}"{% endif %} {% include "django/forms/widgets/attrs.html" %} /> </div> name and type field are empty. so i cannot pass the form data to request.POST. <div class="col-sm-9"> <input type="" class="form-control mt-3" id="id_Address" name="" /> </div> -
Django app with Azure AD account identity provider deployment to Azure Web app service fails
Background I am trying to deploy a Django web app with Azure AD as the account identity provider to Azure Web app services following the Microsoft tutorial. My app is registered on the Azure AD portal. It works well in development on localhost. Problem However, when i deploy it to Azure Web app services, it fails because it requests a redirect URI starting with http while Azure AD requires that any non localhost server must have a redirect URI starting with https. Specifically, it requests a redirect URI as http://myapp.com/auth/redirect. But, i am only allowed to register URI https://myapp.com/auth/redirect in Azure AD. This problem was addressed in a related Stackoverflow question The solution given was to "Run server with ./manage.py runserver_plus --cert /tmp/cert localhost:8000". This works great on localhost, but i am having trouble deploying it to Azure web app service. My deployment file stored in .github/workflows/deploy_on_<myapp>.yml has the deploy job defined as follows: deploy: runs-on: ubuntu-latest needs: build environment: name: 'Production' url: ${{ steps.deploy-to-webapp.outputs.webapp-url }} steps: - name: Download artifact from build job uses: actions/download-artifact@v2 with: name: python-app path: . - name: 'Deploy to Azure Web App' uses: azure/webapps-deploy@v2 id: deploy-to-webapp with: app-name: 'fno-calculator' slot-name: 'Production' publish-profile: ${{ secrets.AZUREAPPSERVICE_PUBLISHPROFILE_<secret> … -
How to get django session data with javascript?
i save session data in django with key 'theme' : request.session['theme'] = 'light' Then i want to get 'theme' session data in javascript with this code: sessionStorage.getItem("theme"); but i can't get theme data. How can I do this?