Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can't connect my django backend with Postgrsql
In my dockerized project, I'm trying to connect my Django app with Postgresql but it keeps giving me this error: File "/home/cr_user/.local/lib/python3.9/site-packages/psycopg2/__init__.py", line 122, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) django.db.utils.OperationalError: could not translate host name "db" to address: Temporary failure in name resolution My compose.yml version: '3.9' services: db: container_name: db image: postgres:13 ports: - '5432:5432' env_file: - ./server/.env volumes: - dbdata:/var/lib/postgresql/data/ networks: - cr_nginx_network cr_api: container_name: cr_api build: context: ./server dockerfile: Dockerfile command: python manage.py runserver 0.0.0.0:5000 ports: - "5000:5000" volumes: - ./server:/cr_server depends_on: - db volumes: dbdata: pgadmin_data: networks: cr_nginx_network: driver: bridge My settings.py DEBUG = True ALLOWED_HOSTS = ["*"] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': os.environ.get("POSTGRES_NAME"), 'USER': os.environ.get("POSTGRES_USER"), 'PASSWORD': os.environ.get("POSTGRES_PASSWORD"), 'HOST': 'db', 'PORT': 5432 } } The postgres container is running without a problem but I can't see causing the issue. -
NoReverseMatch: Reverse for '<data>' with arguments <args> not found. 1 pattern(s) tried
Extremely new Django learner here. I am working on a personal project and got this error. views.py def download_video(request): ... return redirect(reverse('download_status', args=[True, None, str(name)])) def download_status(request, download_success, download_error=None, video_id=None): ... context = { 'download_success': download_success, 'download_error': download_error, 'new_filename': video_id, 'entries_page': paginated_subs, 'video_id': video_id } return render(request, 'download_status.html', context) Basically, it is a request from download_video method to redirect to another page that will display the subs list in a paginated manner. urls.py urlpatterns = [ path('download/', views.download_video, name='download_video'), path('data/<video_id>/', views.download_status, name='download_status'), ] download_status.html {% load static %} <!-- displayer.html --> ... pagination support code ... I have tried the pagination code and it works, but for the current organization of code, it is giving me this error: ERROR:django.request:Internal Server Error: /video_downloader/download/ Traceback (most recent call last): File "C:\Users\leofi\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Users\leofi\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Academics\video_downloader\views.py", line 105, in download_video return redirect(reverse('download_status', args=[True, None, str(name)])) File "C:\Users\leofi\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django\urls\base.py", line 88, in reverse return resolver._reverse_with_prefix(view, prefix, *args, **kwargs) File "C:\Users\leofi\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django\urls\resolvers.py", line 828, in _reverse_with_prefix raise NoReverseMatch(msg) django.urls.exceptions.NoReverseMatch: Reverse for 'download_status' with arguments '(True, None, '480OGItLZNo')' not found. 1 pattern(s) tried: ['video_downloader/data/(?P<video_id>[^/]+)/\\Z'] I have tried looking at the docs and … -
How to solve this blog problems?
I made this blog which has some major problems I list them down below I appreciate it if you'd help me with either one you know the solution for if I need to add any other codes please let me know 1- when I login as different users and write a post it always mentions only one of my accounts as the author it doesn't write the current user's username as the author and I can see and delete all the other users posts when I login only one of the accounts 2-when I write a post the spaces between the lines and all that is correct but when I post it it all just displays beneath each other with no space 3- I cannot make this footer stretch to the width of the webpage and when I include it in my base.html it changes the styling of the other parts I think due to its CSS 4- when I go to my detail page the buttons on the navbar stretch down base.html {% load static %} <!DOCTYPE html> <html> <head> <title> {% block title %}{% endblock %} </title> <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script> … -
how to use google identity services with django-react
ive really read a hundreds outdated questions and blog posts but still cant seem to find a way. i tried using django-social-auth, django-all-auth and so much tutorials. on react im using https://www.npmjs.com/package/@react-oauth/google and i still dont understand alot of things: like does oauth2 work with the jwt token sent from google and from react. how am i supposed to get the data of a jwt token if it was signed by a google secret key that i dont know (or perhaps its the client secret?) and how am i supposed to have a password for user using a user model, unless a 3rd party packages helps with that -
"First question displaying twice consecutively in a Django form; subsequent questions work as expected"
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Personality Test</title> <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script> {% load static %} <style> html { height: 100%; background-image: url('{% static questions.0.background_image_path %}'); /* Use the background image of the first question or adjust as needed */ background-size: cover; background-position: center; background-repeat: no-repeat; } .question label { font-family: '楷体', 'Microsoft YaHei', Arial, sans-serif !important; margin-top: 10px; display: block; background-color: #403f3f; /* Dark grey background color for options */ border-radius: 8px; padding: 10px; cursor: pointer; color: #fff; /* Text color for options */ } body { margin: 0; padding: 0; font-family: Arial, sans-serif; } .question-container { /* Remove background color */ padding: 40px; border-radius: 10px; margin: px; display: flex; flex-direction: column; align-items: center; } .question { margin-bottom: 40px; display: none; text-align: center; position: relative; background-image: url('{{ question.background_image_path }}'); background-size: cover; background-position: center; background-repeat: no-repeat; } .text-box { margin-bottom: 10px; background-color: white; border-radius: 8px; padding: 10px; box-shadow: 0 0 10px rgba(0, 0, 0, 0.1); /* Optional: Add a subtle shadow */ } .tick-mark { opacity: 0; visibility: hidden; transition: opacity 0.5s ease-in-out; } img { max-width: 80%; /* Ensure images don't exceed their container width */ height: auto; /* Maintain image aspect ratio */ border-radius: 8px; … -
The value disappears but still save in database
I have a registration form for a Python/Django project that uses Vue.js. I save the form correctly, but when trying to edit, I can see that the value is loaded properly, but it disappears very quickly, as if Vue.js/JavaScript is erasing it. When inspecting the field, I can see that its value receives the correct value from the registration, but the field becomes blank. <script> function capitalizeWords(string) { if (!string) return string; const words = string.split(' '); const capitalizedWords = words.map((word) => { if (word.length > 1) { return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase(); } else { return word.toUpperCase(); } }); return capitalizedWords.join(' '); } var app = new Vue({ el: '#app', delimiters: ['[[', ']]'], data: { street: '', district: '', city: '', state: '', country: '', cnpj: '', name: '', trade_name: '', cnae: '', opening_date: '', selectedBank: '', bank: '', bank_code: '', nameInBankAccount: '', cnpjInBankAccount: '', postal_code: '', isLoading: false, isPostalCodeFound: true, isCNPJFound: true, display_form_address: false, display_form_bank: false, hasError: '{{ error }}' }, beforeMount: function () { this.street = this.$el.querySelector('#id_address-0-street').value this.district = this.$el.querySelector('#id_address-0-district').value this.city = this.$el.querySelector('#id_address-0-city').value this.state = this.$el.querySelector('#id_address-0-state').value this.country = this.$el.querySelector('#id_address-0-country').value this.cnpj = this.$el.querySelector('#id_company-cnpj').value this.name = this.$el.querySelector('#id_company-name').value this.trade_name = this.$el.querySelector('#id_company-trade_name').value this.cnae = this.$el.querySelector('#id_company-cnae').value this.opening_date = this.$el.querySelector('#id_company-opening_date').value this.getError(); }, watch: { … -
How can I add entries to my Model in Django, that are linked to a user using Firebase?
I am using React with FireBase to create users account on my Frontend. I am creating a table to track a users weight and it appears like this, from django.db import models from django.utils.translation import gettext_lazy as _ class Units(models.TextChoices): KILOGRAM = 'kg', _('Kilogram') POUND = 'lbs', _('Pound') class WeightTracking(models.Model): date = models.DateField() weight = models.IntegerField() units = models.CharField(choices=Units.choices, max_length=3) def _str_(self): return f'On {self.date}, you weighed {self.weight}{self.units}' The problem is, I have no idea how to track this to a user that is logged in. How can I add an entry that is linked to a user. FireBase gives me a UID for the user which I can send to the django backend, but doesn't Django have a default id column? How can I customize it or what is the best approach to linking an entry to a user for my future queries. Thanks! -
Django server does not accept cookies
When I try to send a POST request to the DJANGO app hosted on the server, with included credentials in the Axios request or with a Postman app, I cannot access cookies in the app, because cookies are never sent. Axios config looks like this: export function genericApiHost(host: string) { const headers = { "Content-Type": "application/json", Accept: "application/json", // "Access-Control-Allow-Origin": true, }; return axios.create({ baseURL: `${host}`, headers: headers, withCredentials: true, }); } If I include the allow origin header I get a CORS error, otherwise, cookies are not sent. This is part of the Django app settings: CORS_ALLOW_ALL_ORIGINS = True CORS_ALLOW_CREDENTIALS = True CSRF_COOKIE_SECURE = False CSRF_COOKIE_HTTPONLY = False CSRF_TRUSTED_ORIGINS = ['*'] ALLOWED_HOSTS = ["*"] With the settings I listed here, the application works correctly locally, but when the code is uploaded to the nginx server, it doesn't work -
Django - How to solve error "SIGPIPE: writing to closed pipe/socket/fd"
My web app sends out an email to users utilizing a standard format per django.core.mail.message.EmailMessage. It is received fine by most ISPs and browsers---but with one ISP, the emails are not being received by the users and these 2 related error messages are appearing on the PythonAnywhere server that I use: SIGPIPE: writing to a closed pipe/socket/fd (probably the client disconnected) on request [a specific URL in your web app] uwsgi_response_writev_headers_and_body_do(): Broken pipe [core/writer.c line 306] during [a specific URL in your web app] My research suggests it could be a server time-out issue related to nginx and uwsgi--but I don't think I have either installed; this is a wsgi application. My gut suggests it could be this specific ISP blocking my emails because I've been testing so much and it considers them spam. Is that plausible? Any thoughts on the likely cause of these errors or how I could resolve? -
Django primary key AutoField does not update when creating an object with explicit id
Suppose I have a model A in Django that uses the default primary key AutoField. Due to a transition process, I have created some objects of A with an explicit id, using A.objects.create(id=legacy_id). Coincidentally, these legacy ids start from 1. Then, when trying to create new objects without setting an explicit id, Django gives the error django.db.utils.IntegrityError: duplicate key value violates unique constraint "topics_reply_pkey" . It seems it is trying to create the object from id=1. If I added 20 objects with ids from 1 to 20, I expect that when using A.objects.create without an explicit pk, it would create the object with id 21. Why is this problem happening, and how can I solve it? -
Using DRF and django-tenants together in the same project
I'm currently building a multi tenancy app with django-tenants. However I also want to run my REST API in the same project as django-tenants. This is where the problem arises, if I were to make my API a shared tenants app every tenant subdomain ends up having their own API. For example, all registered tenants adopt the API routes as part of their subdomain: tenant1.example.com/api, tenant2.example.com/api, etc. I don't want my API to be underneath each tenant, I want to just run it on one domain, preferably api.example.com Does anyone have any advice on how to set this up? How are other people handling this in their projects? -
ManyToOne dropdown in Django admin inline
I have a Django project for keeping track of computers and parts. I have several different models set up for various types of parts, and they have a foreign key pointing to a model for a built computer. As it stands I can only assign a computer to a part, but I would like to do the opposite. Given something like the following: models.py class Computer(models.Model): pass class PartType1(models.Model): name = models.CharField(max_length=200) installed_in = models.ForeignKey(Computer, on_delete=models.SET_NULL, null=True) class PartType2(models.Model): name = models.CharField(max_length=200) installed_in = models.ForeignKey(Computer, on_delete=models.SET_NULL, null=True) I created some inlines hoping that would work: admin.py class PartType1Inline(admin.StackedInline): model = PartType1 class PartType2Inline(admin.StackedInline): model = PartType2 @admin.register(Computer) class ComputerAdmin(admin.ModelAdmin): inlines = (PartType1Inline, PartType2Inline, ) But this only allows me to create new parts from the Computer page. Because a computer can have an arbitrary number of a specific type of part (RAM modules as an example) I can't add the foreign keys to the Computer class. I've tried using OneToOne fields on the Computer class, but that requires adding a bunch of fields that usually end up going unused, and is not as flexible. What I would really like is a simple dropdown allowing me choose existing objects from PartType1, … -
dj-rest-auth verification email give me wrong url
I implemented the email authentication function using dj rest auth, but it worked fine locally, but when I deployed it, the authentication email URL came out strangely. I registered my backend domain in admin's site>site. this is my settings.py EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend" EMAIL_HOST = "smtp.gmail.com" EMAIL_PORT = "587" EMAIL_HOST_USER = "my_email@gmail.com" EMAIL_HOST_PASSWORD = "app_password" EMAIL_USE_TLS = True DEFAULT_FROM_EMAIL = EMAIL_HOST_USER STATIC_URL = "/static/" ACCOUNT_CONFIRM_EMAIL_ON_GET = True ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_EMAIL_VERIFICATION = "mandatory" EMAIL_CONFIRMATION_AUTHENTICATED_REDIRECT_URL = ( "/" ) ACCOUNT_EMAIL_CONFIRMATION_EXPIRE_DAYS = 1 ACCOUNT_EMAIL_SUBJECT_PREFIX = "WowYouToo" and this is my accounts/views.py class ConfirmEmailView(APIView): permission_classes = [AllowAny] def get(self, *args, **kwargs): self.object = confirmation = self.get_object() confirmation.confirm(self.request) return HttpResponseRedirect("accounts/") def get_object(self, queryset=None): key = self.kwargs["key"] email_confirmation = EmailConfirmationHMAC.from_key(key) if not email_confirmation: if queryset is None: queryset = self.get_queryset() try: email_confirmation = queryset.get(key=key.lower()) except EmailConfirmation.DoesNotExist: return HttpResponseRedirect("accounts/") return email_confirmation def get_queryset(self): qs = EmailConfirmation.objects.all_valid() qs = qs.select_related("email_address__user") return qs class CustomRegisterView(RegisterView): serializer_class = CustomRegisterSerializer permission_classes = [permissions.AllowAny] class CustomTokenObtainPairView(TokenObtainPairView): serializer_class = CustomTokenObtainPairSerializer the url in verification email is 'http://backend/accounts/confirm-email/Mzk:1r99pa:fG8rVgPl5q4WBQzs3saCYGKeVsquqwlvcFtwPvys3Wg/' I tried to add URL_FRONT in settings.py and changed every HttpResponseRedirect urls...I also changed domain using shell but that 'http://backend/' never changed. -
GENERATED ALWAYS AS at MariaDB in Django
I have a column in mariadb called operator_tax_info, with the following structure, CREATE TABLE `operator_tax_info` ( `id` int(11) NOT NULL AUTO_INCREMENT, `created` datetime(6) NOT NULL, `modified` datetime(6) NOT NULL, `visible` tinyint(1) NOT NULL, `operator_id` int(11) DEFAULT NULL, `geolocation` point NOT NULL, `data` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL CHECK (json_valid(`data`)), `fiscal_number` varchar(255) GENERATED ALWAYS AS (json_unquote(json_extract(`data`,'$.fiscal_number'))) STORED, PRIMARY KEY (`id`), KEY `operator_tax_info_operator_id_0c173d85_fk_companies_operator_id` (`operator_id`), SPATIAL KEY `operator_tax_info_geolocation_id` (`geolocation`), KEY `fiscal_number` (`fiscal_number`), CONSTRAINT `operator_tax_info_operator_id_0c173d85_fk_companies_operator_id` FOREIGN KEY (`operator_id`) REFERENCES `companies_operator` (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=639 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci as you can see the column fiscal_number is a generated column from data column which is a json field, that column was recently added, to get fiscal_number from the json, and also as backend we use Django 3.2 as our ORM, with the following Model definition: class OperatorTaxInfo(BaseModel, SoftDeletionModel): operator = models.ForeignKey( 'companies.Operator', related_name='operator_tax_info_operator', on_delete=models.DO_NOTHING, null=True) data = JSONField(default=dict) geolocation = geomod.PointField('Geo_localizacion', default=Point(0, 0)) class Meta: db_table = 'operator_tax_info' So my question is there a way to map this column from mariadb to Django, or how to generate this column from Django using migrations and indexes, without losing speed from db, because I have trying using a @property decorator to map and annotate this … -
URL Appending instead of redirecting
When I click the link on my HTML page, instead of redirecting to the clicked url it appends to the current one and displays an error (404). How can I solve this and redirect to the correct url? HTML Table where the link is displayed: {% for acesso in acessos_medicos %} <tr class="linha-tabela"> <td>{{acesso.identificacao}}</td> <td>{{acesso.status}}</td> <td><a href="{{acesso.url}}">{{acesso.url}}</a></td> </tr> {% endfor %} models.py: @property def url(self): return f'http:127.0.0.1:8000/exames/acesso_medico/{self.token}' path in urls.py: path('acesso_medico/<str:token>', views.acesso_medico, name="acesso_medico") -
I want to make sure that if the user answers the question correctly, then points are added to him, and the total number of points is saved in the db
I want to make sure that if the user answers the question correctly, then points are added to him, and the total number of points is saved in the db, but the problem is that the wrong type is constantly or something else is wrong It's a model, but it's probably not needed. class Task(models.Model): title_task = models.CharField(verbose_name="Заголовок", max_length=128) description_task = models.TextField(verbose_name="Задание") created_at_task = models.DateTimeField(auto_now_add=True) update_at_task = models.DateTimeField(auto_now=True) user = models.ForeignKey(to=User, verbose_name="Пользователь", on_delete=models.CASCADE) image_task = models.ImageField(verbose_name="Обложка", upload_to="advertisements/", blank=True, null=True) right_answer = models.CharField(verbose_name="Верный ответ",default=1, max_length=128) class Meta: db_table = 'tasks' def __str__(self): return f"task(id = {self.id}, title = {self.title_task})" @admin.display(description="дата создания") def created_date_task(self): if self.created_at_task.date() == timezone.now().date(): created_time_task = self.created_at_task.time().strftime("%H:%M") return format_html("<span style = 'color:blue;'>Сегодня в {} </span>",created_time_task) else: return self.created_at_task.strftime("%d:%m%y в %H:%M") @admin.display(description="дата обновления") def update_date_task(self): if self.update_at_task.date() == timezone.now().date(): update_time_task = self.update_at_task.time().strftime("%H:%M") return format_html("<span style = 'color:blue;'>Сегодня в {} </span>", update_time_task) else: return self.update_at_task.strftime("%d:%m%y в %H:%M") @admin.display(description="Изображение") def image_mini_task(self): if self.image_task: return format_html("<img src='{}' style = 'width:40px;'>", self.image_task.url) def get_absolute_url(self): return reverse('task', kwargs={"pk": self.pk}) another model, but it is already available to users class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) points = models.IntegerField(verbose_name="Баллы", default=0) viev.py @login_required(login_url=reverse_lazy("login")) def task(request, pk): answer = request.POST.get("answer") points = int(Profile.objects.values_list("points", flat=True).get(pk = )) tasks = … -
Facing an issue to update an existing object in Django 4
I'm working with a Diagnostic tool, I'm trying to update an existing instance of the database, I'm rendering a group of data corresponding to the device which being repaired, I have a second section of my render which shows a group of fields which must be updated by the Diagnosticador, those are the fields which will be updated. For some reason I keep getting orden_de_diagnosticoDiagnostico with this Orden de diagnóstico already exists.. Which is kinda obvious, since I'm looking to update an existing object. Can't find the reason for this to turn the form into invalid. Have tried multiple approaches, get, get_or_create, defining hidden fields emulating another page which already works in a similar way and nothing works. Looking forward to go over this form is invalid error due an object already existing. Models class Diagnostico(models.Model): orden_de_trabajo = models.ForeignKey(Cargaseries, on_delete=models.CASCADE, default=None, to_field='orden_de_trabajo', verbose_name='Orden de Trabajo', null=True) orden_de_diagnostico = models.CharField(db_column='orden_de_diagnostico',max_length=5, verbose_name='Orden de diagnóstico', primary_key=True, unique=True) # Field name made lowercase. Field renamed to remove unsuitable characters. numero_de_serie = models.CharField(db_column='numero_de_serie', max_length=45, verbose_name='S/N', null=True) diagnosticador = models.CharField(max_length=45, verbose_name='Diagnosticador', null=True) condicion_caja = models.ForeignKey('Condicioncaja', db_column='condicion_caja_id',on_delete=models.CASCADE, to_field='condicion_caja', verbose_name='Condicion Caja', default='Elige el estado de la caja', null=True) marca_cargador = models.CharField(verbose_name='marca_cargador', max_length=45, null=True) # Field name made lowercase. … -
Python-Streamlit Security
I'm using Streamlit for a web app. I built a system authenticator with streamlit_authenticator. When users log in, they can view specific data. I made a connection between Streamlit and MySQL. In this database, there are usernames and passwords, as well as specific data for users. Is this approach safe for deployment on the internet? Do you know other ways? For example, I tried with Django, but its difficult to integrate this with Streamlit. -
Django: My context variable with a zip list only works with one for loop. If I want to use the same variable in a different loop it doesn't work
In views.py I have the variable mylist = zip(set1,set2,set3) In templates I do {% for val1, val2, val3 in mylist%} {% endfor %} It works fine. However, if I duplicate the condition it fails. Is it normal? Let's say I have the following: # this is my page some text {% for val1, val2, val3 in mylist %} {{forloop.counter}} {% endfor %} more text {% for val1, val2, val3 in mylist %} {{forloop.counter}} {% endfor %} more text # final text of page The first loop will work, and the second one will be empty. It seems as though I can only use once mylist. I didn't experience this issue with simple lists (as far as I remember) -
Django: default value for select element in django form
Let's say I have a model and a form: class Industry(models.Model): title = models.CharField(max_length=100) class SelectIndustryForm(ModelForm): industry = ModelChoiceField(label='Industry', required=True, queryset=Industry.objects.all(), widget=forms.Select(attrs={'class': 'form-select', 'name': 'industry'})) I created a bunch of objects of the Industry class, and among them there is an object with the title "Unspecified". Is it possible to make this option a default value in the HTML select element (the one where you need to choose an option in the drop-down list) when the form loads? -
Django Abstractuser login fuction problem
I am trying to use Django AbstractUser model to create my own user model, Everything seems to be working fine but my single login/register form seems to be having a problem and that is the Register function works fine and registers the users but they are not getting logged in. my account Model file is as below : class MyUserManager(BaseUserManager): def create_user(self, shenase, password=None, **other_fields): if not shenase: raise ValueError("shenase is required...!") user = self.model(shenase=shenase, **other_fields) user.set_password(password) user.save() return user def create_superuser(self, shenase, password=None, **other_fields): other_fields.setdefault('is_staff', True) other_fields.setdefault('is_superuser', True) other_fields.setdefault('is_active', True) if other_fields.get('is_staff') is not True: raise ValueError('Superuser muse have is_staff=True') if other_fields.get('is_superuser') is not True: raise ValueError('Superuser muse have is_superuser=True') return self.create_user(shenase, password, **other_fields) def random_string(): return str(random.randint(1000000, 9999999)) class MyUser(AbstractUser): username = None shenase = models.CharField(max_length=11, unique=True) eshterak = models.CharField(max_length=7,default=random_string, null=True, blank=True, unique=True) created_at = models.DateTimeField(auto_now_add=True, null=True, blank=True) objects = MyUserManager() USERNAME_FIELD = 'shenase' REQUIRED_FIELDS = [] backend = 'account.mybackend.ModelBackend' and my views file is : def register_view(request): form = forms.RegisterForm if request.method == "POST": try: if "shenase" in request.POST: shenase = request.POST.get('shenase') user = MyUser.objects.get(shenase=shenase) user.save() request.session['user_shenase'] = user.shenase return HttpResponseRedirect(reverse('account:welcome')) except MyUser.DoesNotExist: form = forms.RegisterForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.is_active = False user.save() request.session['user_shenase'] = … -
Can you please tell me how createview is working here ? I mean there is no link in action in form. the how clicking submit is not causing any error?
I am learining how to make a blog app using django. my doubt is createview is inserting data in the database but how does clciking on save button is not rasiing any error there is no link in actio= .enter image description here i have previously made some websites with falsk. so we should provide a link for action so that form data is sent on that link and behind my code has some logic to insert taht recived data in databse. but here no link in action? so how does createview does this? -
Django isn't showing my form error messages
I have a problem when I'm trying to show messages: When I submit the form and use the is_valid(), the only error that show me is password mismatch error (even when the problem isn't the password) here is my code: Form: from django.contrib.auth import forms class Create_user_form(forms.UserCreationForm): error_css_class = "is-invalid" required_css_class = "required-field" class Meta: model = User error_messages = { "dni": { "unique": ("Documento ya registrado."), }, "username": { "unique": ("CUIT/CUIL ya registrado."), }, } fields = ("username", "nombre", "apellido", "dni", "edad") Models : class Datos_Adicionales(models.Model): nombre = models.CharField( unique=False, null=True, default="", max_length=32, ) apellido = models.CharField( unique=False, null=True, default="", max_length=32, ) dni = models.CharField( unique=True, null=False, default="", max_length=32, ) edad = models.IntegerField( unique=False, null=False, default=-1, ) class Meta: abstract = True class User(AbstractUser, Datos_Adicionales): username: models.CharField( unique=True, null=False, verbose_name= "Nombre de Usuario", max_length=32, ) password: models.CharField( unique=True, null=False, max_length=32, ) class Meta: db_table = "usuario" verbose_name = 'Usuario' verbose_name_plural = ' Usuarios' ordering = ['id'] Django => 4.2.7 Sorry but I don't know what more to say... Sorry but I don't know what more to say... Sorry but I don't know what more to say... Sorry but I don't know what more to say... -
How to define public permissions in the base class of django model and generate different codename for each subclass
django-4.2.6+python3.10 This is my base model class: from django.db import models class BaseModel(models.Model): class Meta: abstract = True permissions = [ ("restore", "Restore deleted obj"), ] This is my subclass: class One(BaseModel): name = models.CharField("name for you", max_length=200) class Two(BaseModel): name = models.CharField("name for you", max_length=200) After I executed python manage.py makemigrations and python manage.py migrate It generates such records in the auth_permission table of the database: auth_permission This is not what I want, because their codename is the same, which will lead to confusion. Because I have many such subclasses, all with the same type of permissions, but for different models, I don't want to repeat the definition in each subclass I hope that after running those two commands, it can generate different codename for each model in the database, such as: Generate a permission with the codename restore_one for the one model, and generate a permission with the codename restore_two for the two model. expected I tried to find the answer in the official documentation of django, but I got nothing. Perhaps we can start with the python manage.py makemigrations command. Can anyone tell me how to do it? -
Trouble Using Django Rest Framework 3.0 with Django 3.2 and Python 3.9
I am currently working on an assigmnet that requires working with specific versions of Django, DRF, and Python. Django Rest Framework (DRF) version >3.0 Django version >3.2 Python version >3.9 However, when attepting to use DRF version 3.0, I encountered the following error: django.template.library.InvalidTemplateLibrary: Invalid template library specified. ImportError raised when trying to load 'rest_framework.templatetags.rest_framework': No module named 'django.core.urlresolvers' I found that upgrading DRF to a version beyond 3.0 resolves this issue. However, the assignment specifically mandates using DRF 3.0. Could you please provide guidance or suggestions on how to address this error while ensuring compliance with DRF 3.0? Any help or insights would be greatly appreciated. Thank you!