Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django application can access DB models but Pytest can't (invalid object name)
I'm using Pytest to write unit tests for a Django application. The application itself has no issue working with its databases, and it can read and write data completely fine with any method. When testing, database access using a cursor object works totally fine as well. However, whenever I try to access one of the databases in a test via a model object, I get this error: django.db.utils.ProgrammingError: ('42S02', "[42S02] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Invalid object name '<table I'm trying to access>'. (208) (SQLExecDirectW)") Here's a minimal test that causes this issue - it produces the error above, using the table name Students_with_Holds: @pytest.mark.django_db(databases=['Coursematch']) def test_db_access(self): testobj = StudentsWithHolds.objects.using('Coursematch').create( person_id_number = 'testPIDnum', hold_type_code = 'test' ) assert testobj.person_id_number == 'testPIDnum' assert testobj.hold_type_code == 'test' Attempting to perform the exact same procedure using a cursor object, as shown below, does not cause the issue: @pytest.mark.django_db(databases=['Coursematch']) def test_db_access_cursor(self): with connections['Coursematch'].cursor() as cursor: insert_query = """ INSERT INTO Coursematch.dbo.Students_with_Holds (person_id_number,hold_type_code) VALUES ('testPIDnum','test') """ cursor.execute(insert_query) check_query = """ SELECT person_id_number,hold_type_code FROM Coursematch.dbo.Students_with_Holds WHERE person_id_number = 'testPIDnum' """ cursor.execute(check_query) assert cursor.fetchone() == ('testPIDnum','test') Any suggestions on how to stop this from happening? I've made sure that my models are all migrated, and that … -
connection to server on socket "/var/run/postgresql/.s.PGSQL.5432" failed when i want to connect to django database container from celery task
I'm working on a django application with docker. I have a celery container which uses another redis container as brocker and backend. My postgres database is also in another container. Everything works well. But when I try to perform database operations in tasks, celery returns me: connection to server on socket "/var/run/postgresql/.s.PGSQL.5432" failed here is my docker-compose version: '3' services: app: container_name: ozangue build: context: . command: > sh -c "python manage.py wait_for_db && python manage.py makemigrations && python manage.py migrate && python manage.py runserver 0.0.0.0:8000" ports: - 8000:8000 volumes: - ./electron:/electron - ./data/web:/vol/web environment: - SECRET_KEY=devsecretkey - DEBUG=1 - DB_HOST=db - DB_NAME=xxxxx - DB_USER=xxxxxx - DB_PASS=ozanguedb@2022 - CELERY_BROKER=redis://redis:6379/0 - CELERY_BACKEND=redis://redis:6379/0 depends_on: - db - redis celery: container_name: celery-worker restart: always build: context: ./celery command: celery -A electron worker -l info -E depends_on: - app - redis redis: image: redis:7.0.5-alpine container_name: redis expose: - 6379 db: image: postgres:13-alpine container_name: database environment: - POSTGRES_DB=xxxxxxxx - POSTGRES_USER=xxxxxxx - POSTGRES_PASSWORD=xxxxxxxx celery.py os.environ.setdefault("DJANGO_SETTINGS_MODULE","electron.settings") app = Celery('electron', broker='redis://redis:6379/0',backend='redis://redis:6379/0') app.config_from_object("django.conf:settings",namespace="CELERY") app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) settings CELERY_BROKER_URL = os.environ.get("CELERY_BROKER","redis://redis:6379/0") CELERY_RESULT_BACKEND = os.environ.get("CELERY_BROKER","redis://redis:6379/0") CELERY_ACCEPT_CONTENT = ['json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TIMEZONE = 'Africa/Libreville' How to solve this problem please? -
How do I filter requests objects by date range in Django?
I've got a function for looping like this: saved_date = request.GET.get('date') start_date = request.GET.get('start_date') end_date = request.GET.get('end_date') if saved_date is not None: queryset = Contact.objects.filter( createdAt__istartswith=saved_date).values_list('phone', flat=True) elif start_date and end_date is not None: queryset = Contact.objects.filter( createdAt__range=[start_date, end_date]).values_list('phone', flat=True) So, I need to filter the objects by a date range, including the end date. How do I filter all the objects that have a date between start_date and end_date? -
Postman CLI collection run not using cookieJar correctly
I'm trying to use postman with a Django API and I'm writing some tests for the API. However I'm encountering an issue with postman when run through the console using postman collection run <collection_id>. I'm using Postman's cookieJar to set and get cookies between requests but I have two of them and it is only adding one when running using the command. This behaviour doesn't happen when run through postman itself. Here's the test script that runs the code for adding the cookies: console.log(pm.request) if (pm.request.url == "http://localhost:8000/api/auth/login/" && pm.request.method == "GET"){ const cookieJar = pm.cookies.jar() let temp = pm.response.headers; let temp2 = temp.filter(item => item["key"]=== "Set-Cookie") let temp3 = temp2[0].value let temp4 = temp3.slice(10,42) cookieJar.set("localhost", "csrftoken", temp4); console.log("Ran tests script") } if (pm.request.url == "http://localhost:8000/api/auth/login/" && pm.request.method == "POST"){ const cookieJar = pm.cookies.jar() pm.response.forEachParent(console.log(pm.response)) let temp5 = pm.response.headers; let temp6 = temp5.filter(item => item["key"]=== "Set-Cookie") let temp7 = temp6[0].value let temp8 = temp6[1].value let temp9 = temp7.slice(10,42) let temp10 = temp8.slice(10,42) console.log(temp9) console.log(temp10) cookieJar.set("CLI1", "csrftoken", temp9); cookieJar.set("CLI2", "sessionid", temp10); } The output for the console.logs near the bottom do show that there are values, even when run through the CLI but for some reason the second cookie isn't set … -
Implement of dependent dropdown of district and branches in an application form created using django models and forms
I created a model of district and branch and application form .In this I used FOreignkey for branch and district in application form model.I want dependent dropdown of district and branch in which if we select one district it's dependent branch would be shown in the branch field.how it is possible I added 5 district to admin.but when I add branches to admin nothing happen in display html page.please give the way to implement dependent dropdown using foreign key and in forms what can I do.please give the urls and views also -
django migration with multiple languages
It seems makemigrations command is affected by django language (django.mo, django.po etc). I have two projects. One is upstream and the other origin is forked version of upstream. Upstream's LANGUAGE_CODE is ko-kr and that of origin is en. In upstream when I run makemigrations, provided that I have django.mo file under locale/ko/LC_MESSAGES no changed detected. Now I head to origin whose language is en. I have locale/en/LC_MESSAGES/django.mo file. When I run makemigrations I see a long list of migration files. But with a close look, all of them are about changes of verbose_name, choices label etc. When one has django project that supports more than one languages, how does one make it recognise its language and prevent it from making unnecessary migration files? -
'RecursionError: maximum recursion depth exceeded' when I try to run a server
I'm fairly new to django and webdev and I've run different servers before, but for some reason, whenever I try to run a server for this project, I get this: File "C:\Users\Jooom\Envs\djangenv\Lib\site-packages\django\core\checks\urls.py", line 24, in check_resolver return check_method() ^^^^^^^^^^^^^^ File "C:\Users\Jooom\Envs\djangenv\Lib\site-packages\django\urls\resolvers.py", line 496, in check messages.extend(self._check_custom_error_handlers()) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Jooom\Envs\djangenv\Lib\site-packages\django\urls\resolvers.py", line 514, in _check_custom_error_handlers signature = inspect.signature(handler) ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Jooom\AppData\Local\Programs\Python\Python312\Lib\inspect.py", line 3327, in signature return Signature.from_callable(obj, follow_wrapped=follow_wrapped, ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Jooom\AppData\Local\Programs\Python\Python312\Lib\inspect.py", line 3071, in from_callable return _signature_from_callable(obj, sigcls=cls, ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Jooom\AppData\Local\Programs\Python\Python312\Lib\inspect.py", line 2500, in _signature_from_callable obj = unwrap(obj, stop=(lambda f: hasattr(f, "__signature__") ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Jooom\AppData\Local\Programs\Python\Python312\Lib\inspect.py", line 774, in unwrap while _is_wrapper(func): ^^^^^^^^^^^^^^^^^ File "C:\Users\Jooom\AppData\Local\Programs\Python\Python312\Lib\inspect.py", line 768, in _is_wrapper return hasattr(f, '__wrapped__') and not stop(f) ^^^^^^^ RecursionError: maximum recursion depth exceeded there's a lot more text before this, but I figured that'd be too much to post here. I should point out that i recently did a system reset on my pc and this is my first django code since then. Any help at all would be appreciated tried to run a server, expected a server to run like it normally would, but got a recursion error instead -
Is it possible to send file and data in same POST request using python request library?
I want to send file as well as data in same POST request. is it possible? I tried with python request library but ended up receiving either file or data but not both at the same time. import requests files = { 'upload_file': open('creds.txt','rb') } values = { "collection_name": "detete-test-1", "source": { "data": { "data1": "some random string" } } } url = 'http://localhost:8000/v1/source/test' r = requests.post(url, json=values, files=files) print(r) Tried above code but i was just receiving ImMemoryUploadedFile object in django not the data. -
UnboundLocalError at /create-assignment/ATMser cannot access local variable 'context' where it is not associated with a value
I have the blow view def assign_item_view(request, pk): item = Item.objects.get(Serial_no=pk) if request.method == "POST": form = AssignmentForm(request.POST, instance=item) if form.is_valid(): form.save() return HttpResponseRedirect('/user') else: form = AssignmentForm(instance=item) context = {"item": item,"form": form} # move this line here return render(request, "workshop/Add_assignment.html", context) `def assign_item_view(request, pk): item = Item.objects.get(Serial_no=pk) if request.method == "POST": form = AssignmentForm(request.POST, instance=item) if form.is_valid(): form.save() return HttpResponseRedirect('/user') else: form = AssignmentForm(instance=item) context = {"item": item,"form": form} # move this line here return render(request, "workshop/Add_assignment.html", context)` I got the below Erro UnboundLocalError at /create-assignment/ATMser cannot access local variable 'context' where it is not associated with a value -
Intermittent Character Encoding Issue with Django, Celery, and SendGrid
I've been working with a setup that uses Django alongside Celery for dispatching emails, and we've integrated SendGrid for this purpose. However, I've come across a peculiar issue that I hope someone might shed some light on. Sometimes, when sending out emails, characters with diacritics, specifically "ì", are being displayed as another character, in this case, "ě". I've double-checked and ensured that all software configurations are set to utf-8 encoding, but this inconsistency persists. Has anyone encountered a similar issue or have any suggestions on how to debug or fix this? Example: "Martedě" instead of "Martedì" Martedě" instead of "Martedì The templates are saved in utf-8 encoding html files. This is the code used to send emails: message = render_to_string( "emails/booking_canceled/cliente_to_client.html", { "first_name": booking.customer_first_name, # ... }, ) email = EmailMessage( subject=subject, body=message, from_email=DEFAULT_FROM_EMAIL, to=[booking.customer_email], headers={"Content-Type": "text/html; charset=UTF-8"}, ) email.content_subtype = "html" email.send() logger.info( "[booking_code: %s][customer_email: %s] Sent.", booking.code, booking.customer_email, ) Thank you in advance for any assistance! -
Django - NoReverseMatch (admin panel)
I wrote a function to display a button in the admin panel to parse a file and save questions to the database. Here's a part of the views.py: def upload_questions_view(request): blocks = Blocks.objects.all() if request.method == 'POST': file = request.FILES.get('questions_file') block_id = request.POST.get('block') block = Blocks.objects.get(id=block_id) if file: try: parsed_data = parse_excel_survey(file.temporary_file_path()) for data in parsed_data: if data.type == "ask": ask = Asks( position=data.cl1, block=block, ask=data.question, important=data.cl3, answerable=data.answerable, multiplier=data.cl5, ) ask.save() messages.success(request, 'Data uploaded!') except Exception as e: messages.error(request, f'Error: {e}') else: messages.error(request, 'File error.') return redirect('admin:main_asks_changelist') context = { 'blocks': blocks } return render(request, 'admin/upload_questions.html', context) Here's the change_list_template.html: {% extends "admin/change_list.html" %} {% load i18n %} {% block object-tools-items %} <li> <a href="{% url 'admin:upload_questions' %}" class="addlink"> {% trans "Upload Excel" %} </a> </li> {{ block.super }} {% endblock %} Here's a part of admin.py: class AsksAdmin(admin.ModelAdmin): inlines = [CriteriesInline] list_filter = ('block', 'ask', 'position', 'important', 'multiplier') list_display = ('block', 'ask', 'position', 'important', 'multiplier') change_list_template = 'admin/change_list_with_upload.html' def get_urls(self): urls = super().get_urls() custom_urls = [ path('upload_questions/', self.admin_site.admin_view(upload_questions_view), name='upload_questions'), ] return custom_urls + urls def upload_questions(self, request): return redirect('admin:upload_questions') upload_questions.short_description = "Download Excel" actions = [upload_questions] A button to upload files appeared in the admin panel, but there's an … -
Django channels using RedisPubSubChannelLayer fails to receive
I was testing RedisPubSubChannelLayer for a simple send/receive, but the test fails using pytest. (it passes with RedisChannelLayer) Test class class TestRedis(TestCase): # test if RedisChannelLayer communicates async def test_channels_send_receive(self): channel_name = '45jfngoegnolkmlrmbhrfmh' channel_layer = channels.layers.get_channel_layer() payload = {'type': 'hello'} await channel_layer.send(channel_name, payload) print(f"channel_layer.send done") result = await channel_layer.receive(channel_name) print(f"channel_layer.receive done") self.assertEqual(payload, result) Would you help me understand what I'm doing wrong? If I simply change "BACKEND": "channels_redis.pubsub.RedisPubSubChannelLayer" to "BACKEND": "channels_redis.core.RedisChannelLayer" the test passes, but otherwise, only "channel_layer.send done" prints and hangs on receive I'm using Ubuntu 22.04.3 LTS python 3.10.12, redis_version:6.0.16 channels-redis==4.1.0 Django==4.2.4 channels==4.0.0 pytest==7.4.2 pytest-asyncio==0.21.1 pytest-django==4.5.2 -
build API for support pagination and non-paginate on django rest framework
As I work on Django-rest-framework. I want the API to support dynamic pagination. For example, if user need pagination they can use an endpoint /api_url?offset=0&limit=10(should return with the format that can let the user know the current page and have the next page or not) and if they don't want pagination they just request without params /api_url. I need it to work with django_filters so it won't make many requests to SQL. I expect to get solition or sample code to about this problem. -
Check_password doesn't work in my Django login system
I am trying create login system when user signup it register successfully users data in database when user signin, the check_password method not work it wil give the else statement meassage Like 'password mismatch'. Can anyone help me to find the answer thankyou in advance I am also used built-in authenticate funtion to authenticate the use but it is also not work from django.http import HttpResponse from django.contrib import messages from django.shortcuts import render from.forms import loginform from.models import Logindata import re import mysql.connector from django.contrib.auth.hashers import make_password,check_password def signin(request): if request.method=='POST': username=request.POST.get('Username') password=request.POST.get('Password') try: user=Logindata.objects.get(Username__contains=username) except Logindata.DoesNotExist: return HttpResponse(f" login failed") if user.check_password(password) : return HttpResponse('login successful') else: return HttpResponse("password mismatch") return render(request,'Signin.html') def signup(request): if request.method=='POST': user=loginform(request.POST) if user.is_valid(): username=user.cleaned_data['User'] password=user.cleaned_data['Password'] Repassword=user.cleaned_data['ConfirmPassword'] mydb=mysql.connector.connect(host='localhost',user='root', password='',database='loginststem') cursordb=mydb.cursor() sql='select*from loginapp_logindata where BINARY Username=%s' cursordb.execute(sql,[(username)]) Result=cursordb.fetchone() if Result: messages.error(request,"Username already exists") return render(request,'Signup.html',{'form':user}) if len(password)==8: if re.search('[A-Z]',password): if re.search('[a-z]',password): if re.search('[0-1]',password): if password==Repassword: Logindata.objects.create(Username=username, Password=make_password(password)) messages.success(request,'your are Register succesfully') return render(request,'Signin.html',{'form':user}) else: messages.error(request,'Pasword Must be Same') return render(request,'Signin.html',{'form':user}) else: messages.error(request,"Atleast one Numeric value") return render(request,'Signin.html',{'form':user}) else: messages.error(request,"Atleast one lowercase value") return render(request,'Signin.html',{'form':user}) else: messages.error(request,"Atleast one uppercase value") return render(request,'Signin.html',{'form':user}) else: messages.error(request," password must be 8 characters") return render(request,'Signin.html',{'form':user}) else: user=loginform() return render(request,"Signup.html",{'form':user}) … -
pylint_django "Instance of 'ForeignKey' has no ... member"
I'm working on a project in python with django and recently I decided to modify the way the models were stored in one of the apps. With the help of django documentation, I deleted the models.py file and created a models folder in which I put all my models in files and created a _init_.py file in which I import all my models. This solution works but now pylint no longer seems to understand ForeignKeys. this is my app tree: apps myapp models _init_.py mymodel.py mymodel2.py if i run pylint i can see some E1101. let's take an example: i have a model subnet in subnet.py: class Subnet(models.Model): def __str__(self): return self.nom + "(" + self.cidr + ")" net = models.ForeignKey("Network", on_delete=models.CASCADE, related_name="subnets") def get_parent_cidr(self): return self.net.cidr this model have a reference to the network models in network.py: class Network(models.Model): def __str__(self): return self.company.name + " - " + self.nom + " - " + str(self.cidr) cidr = models.CharField(max_length=18) this network object have a cidr field, all seems to be fine but when i run pylint with the pylint_django plugin, this one send me an error: project/apps/myapp/models/subnet.py:74:15: E1101: Instance of 'ForeignKey' has no 'cidr' member (no-member) What did I do … -
in github actions, how to give the django process permission to create a directory?
for every user image, i create a directory and store the image there.This works as intended on my machine in automated tests and manual use but when i push to the Github, the Github actions raise bellow error which indicates it can not create the required directory to run the tests. PermissionError: [Errno 13] Permission denied: '/src/media/profile_image' -
join some table twice in Django ORM
I have two models class Customer(AbstractBaseModel): uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, db_column='uuid') name = models.CharField(max_length=55) class CustomerAddress(AbstractBaseModel): uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, db_column='uuid') customer = models.ForeignKey(Customer, on_delete=models.DO_NOTHING, related_name='addresses', db_column='customer_uuid') country_code = models.CharField(max_length=3) type = models.CharField(max_length=8, choices=[('shipping', 'shipping'), ('billing', 'billing')]) User can filter customers using two fields: billing_country and shipping_country, they can fill either one or both fields. If user fills both fields, I have to join to CustomerAddress table twice. I do this in raw SQL like this: SELECT * FROM customer c LEFT OUTER JOIN address shipping_address ON shipping_address.customer_uuid = c.uuid AND shipping_address.type = 'shipping' LEFT OUTER JOIN address billing_address ON billing_address.customer_uuid = c.uuid AND billing_address.type = 'billing' and append WHERE clauses if user uses filters like this: # billing_country and shipping_country are sanitized at this point filters = [] if billing_country: filters.append(f"billing_country_code = '{billing_country}'") if shipping_country: filters.append(f"shipping_country_code = '{shipping_country}'") where_part = 'WHERE ' + ' AND '.join(filters) How can I do this using Django ORM? -
Best practices for masking sensitive data on django
In a django project, I am sending requests to third party services and keeping a log of these requests, but I want to censor some sensitive data (password, token, etc.) when saving to the database. I wrote a Handler, which works correctly, but I could not do the masking part. I tried with logging.Filter, but it was not the right approach. When I wanted to try logging.Formatter, I could not save to the database because the returned record was a string, not an object. What is the best way to mask this kind of data? Is it to write a masking function in the handler or some other method? I cannot use third party package because it is a company project -
How to fix Django "ModuleNotFoundError: No module named 'application'" on AWS ElasticBeanstalk?
I faced this issue as well. In my case I was getting a 502 nginx error after deploying to AWS EB using eb deploy and my environment had a red flag. My AWS EB was using Amazon Linux. my verion of django is 4.1.3, python version is 3.9 (also tried with 3.11). option_settings: aws:elasticbeanstalk:container:python: WSGIPath: gnt.wsgi:application project dir. -root-folder -apps -requirements.txt -.ebextensions -django.config -gnt -wsgi.py -settings.py -
Not getting browsable interface at http://127.0.0.1:8000/api
Not getting browsable interface at http://127.0.0.1:8000/api But getting on http://127.0.0.1:8000/api/login and on http://127.0.0.1:8000/api/register first i am also not getting on api/register and api/login then i changed as_view to this as_view() i forget to put () auth_app.urls from django.urls import path from .views import RegistrationAPIView,LoginAPIView,LogoutAPIView urlpatterns=[ path('register/',RegistrationAPIView.as_view(),name='register'), path('login/',LoginAPIView.as_view(),name='login'), path('logout/',LogoutAPIView.as_view(),name='logout'), ] auth_project.urls from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('api/',include('auth_app.urls')) ] i have included rest_framework in installed apps -
PostgreSQL database structure help (multiple database, multiple schema)
Im developing a web application. I have Django for my backend and using PostgreSQL for my database. I am not sure if this is the best approach or not but: I want to create a database for each company and in that database schema for each project within that company. recommendations? I want to create a database for each company and in that database schema for each project within that company. -
Avoid code duplication between django Q expression and as python code
I have a very complex property on a model ALLOWED_STATES = {1,2,3} class X(models.Model): a = models.BooleanField() b = models.ForeignKey('Y', on_delete=model.CASCADE) c = models.IntegerField() d = models.IntegerField() @property def can_delete(self) # this goes on for 6 and clause return self.a and self.b.c and self.c in ALLOWED_STATES and self.d != 5 and .. I also need this property in an annotate() call and filter() #in one endpoint qs = X.objects.filter(...).annoate(can_delete=ExpressionWrapper(Q(a=True, b__c=True, c__in=ALLOWED_STATES,...) & ~Q(d=5), output_field=models.BooleanField()) I wonder if there is a way to unify these forms of this same property into one, without calling can_delete in python after I've fetched the rows. These two forms have become a bit of a maintainability issue as PM keeps on changing the definition of can_delete. -
Pytest error in tests for Single choice question in Django
This is going to be Pytest for single choice question. It cannot be completed due to two reasons - the first one is that the test cannot choose any option from available language_name fields: views.py class AddSingleChoiceQuestionView(View): template_name = "single_choice_form.html" def get(self, request): form = SingleChoiceQuestionForm() return render(request, self.template_name, {"form": form}) def post(self, request): if request.user.is_staff: form = SingleChoiceQuestionForm(request.POST) print(request.POST) print(form.is_valid()) print(form.errors) if form.is_valid(): question = form.save() # Ermitteln Sie die ausgewählte Option aus den Checkboxen selected_option = int(request.POST.get("correct_option")) for i in range(1, 6): option_text = request.POST.get(f"option_{i}") is_correct = i == selected_option # Überprüfen Sie, ob diese Option die ausgewählte ist question.singlechoiceoption_set.create(option_text=option_text, is_correct=is_correct) # return HttpResponseRedirect("success_page") hier doesn't work return redirect("success_page") return render(request, self.template_name, {"form": form}) else: return redirect("index") Conftest.py import pytest from django.contrib.auth.models import User @pytest.fixture def staff_user(db): user = User.objects.create_user(username='staffuser', password='staffpassword', is_staff=True) return user @pytest.fixture def regular_user(db): user = User.objects.create_user(username='testuser', password='testpassword') return user test_views.py for single chocie import pytest from django.test import Client from django.urls import reverse from ..models import MultiQuesModel, Answer, SingleChoiceQuestion from django.contrib.auth.models import User from ..views import AddMultiQuestionView from ..forms import AddMultipleForm, SingleChoiceQuestionForm @pytest.mark.django_db class TestAddSingleChoiceQuestion: @pytest.mark.singlechoice def test_add_single_choice_question(self, client, staff_user): client.login(username='staffuser', password='staffpassword') url = reverse("singleform") # Ersetzen Sie "singlechoice_form" durch den tatsächlichen Namen Ihrer … -
Can not make a user model for both superuser and regular users. Django/Mysql
There is an auth_users table in the database which is built in. If I login any superuser then that superusers information is stored in the auth_user table. There is also another table named authorization_userprofile (authorization is the app name) which stores all the regular users information. This is my model.py from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin from django.db import models class UserProfileManager(BaseUserManager): def create_user(self, phone_number, password=None, **extra_fields): if not phone_number: raise ValueError('The Phone Number field must be set') user = self.model(phone_number=phone_number, **extra_fields) user.set_password(password) # Hash the password user.save(using=self._db) return user def create_superuser(self, phone_number, password=None, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) return self.create_user(phone_number, password, **extra_fields) class UserProfile(AbstractBaseUser, PermissionsMixin): phone_number = models.CharField(max_length=15, unique=True) first_name = models.CharField(max_length=255, default='') # Added first name field last_name = models.CharField(max_length=255, default='') # Added last name field dob = models.DateField(null=True, blank=True) # Added Date of Birth field email = models.EmailField(max_length=255, default='') # Added email field address = models.TextField(default='') # Added address field is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) # other fields if any ... objects = UserProfileManager() USERNAME_FIELD = 'phone_number' # Unique related name to avoid clashes with auth.User model groups = models.ManyToManyField('auth.Group', related_name='user_profiles', blank=True) user_permissions = models.ManyToManyField('auth.Permission', related_name='user_profiles', blank=True) # other fields if any ... This is in … -
populate a select with data from the database
I need to fill in a select with data from the bank. I have a description field and a category field, I need django to fill the select with the categories when opening the registration form. I recently started using django and have been facing this difficulty. Does anyone have a light at the end of the tunnel? cadproduto.html <label for="exampleFormControlInput1">Categoria:</label> <select class="form-control select" id="exampleFormControlSelect1"> {% for categoria in ListaDeCategorias %} <option value="{{categoria.id}}">{{categoria.descricaocategoria}}</option> {% endfor %} </select> forms.py from django import forms from .models import CadastroProduto class ProdutoForm(forms.ModelForm): class Meta: model = CadastroProduto fields = ('descricaoresumida', 'precoprincipal', 'enviabalanca') views.py @login_required def ListagemCategorias(request): ListaDeCategorias = models.CadastroCategoria.objects.all() return render(request, 'listagemcategorias.html', {'ListaDeCategorias': ListaDeCategorias})