Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django form.is_valid() points
I have submit form with: <textarea name="entry" cols="40" rows="10" placeholder="Entry context..." class="area-fld" maxlength="30" required id="id_entry"> # CSS CSS is a language that can be used to add style to an [HTML](/wiki/HTML) page. </textarea> This code: def new(request): if request.method == "POST": form = NewEntry(request.POST) if form.is_valid(): The form.is_valid() is False! All other fields are OK valued. I found the problem is in the values are in textarea. I need the form validation (required fields) are checked server-side, but above value be approve. What is the points of the form.is_valid()? Which values are not approve? How can handle this problem? I have read this Django documentation -
Problem with getting objects based on ManyToManyField relation
I have Meal model and Ingredient, Meal have ManyToMany relation to Ingredient. I try to get objects that match by Ingredients models.py class Meal(models.Model): name = models.CharField(max_length=250) description = models.TextField(blank=True, null=True) recipe = models.TextField() is_published = models.BooleanField(default=False) user = ForeignKey(User, verbose_name='User', on_delete= models.CASCADE) difficulty = ForeignKey('Difficulty', on_delete=models.PROTECT, null=True) ingridients = models.ManyToManyField('Ingridient') ico = models.CharField(max_length=500, blank=True, null=True) class CategoryIngridients(models.Model): name = models.CharField(max_length=100, db_index=True) def __str__(self): return self.name class Ingridient(models.Model): name = models.CharField(max_length=100, db_index=True) category = ForeignKey('CategoryIngridients', on_delete=models.CASCADE, null=True) def __str__(self): return self.name serializers.py class MealSerializer(serializers.ModelSerializer): category = serializers.StringRelatedField() difficulty = serializers.StringRelatedField() #ingridients = serializers.StringRelatedField() user = serializers.StringRelatedField() class Meta: model = Meal fields = "__all__" class IngrigientSerializer(serializers.ModelSerializer): category = serializers.StringRelatedField() class Meta: model = Ingridient fields = "__all__" views.py class TestCraft(APIView): def post(self, request): ingridients_tmp = request.data['ingredients'] ingrid = Ingridient.objects.filter(id__in=ingridients_tmp) print(ingrid) queryset = Meal.objects.filter(ingridients__in=ingrid) print(queryset) serializer = MealSerializer(queryset, many=True) return Response(serializer.data) If I POST json: {"ingredients":[1,2]} This view return, but they are repeating: [ { "id": 1, "difficulty": "Medium", "user": "vleo", "name": "gfgd", "description": "", "recipe": "...", "is_published": true, "ico": "", "ingridients": [ 1, 2, 3, 4, 5, 6 ] }, { "id": 5, "difficulty": "Easy", "user": "vleo", "name": "залупа", "description": "[eqyz", "recipe": "n.,sr", "is_published": false, "ico": "", "ingridients": [ 1, … -
How to convert MediaRecorder stream in Django into wav without disk storage?
I am trying to convert the bytes_data received by the channels receive() method using a WebsocketConsumer. This is the JavaCode: navigator.mediaDevices.getUserMedia({ audio: true }).then((stream) => { const mediaRecorder = new MediaRecorder(stream, {mimeType: 'audio/webm' }) console.log(stream) chatSocket.onopen = () => { mediaRecorder.addEventListener("dataavailable", (event) => { if (event.data.size > 0 && chatSocket.readyState == 1) { chatSocket.send(event.data) } }) // chatSocket.onopen close mediaRecorder.start(250) } On the server side I now want to convert the bytes_data into a wav file so that I can send these short audio snippets via speech_recognition to the recognize_google api. I tried to use pydub to convert the bytes_data but so far I had no success. The channels GeneralConsumer(WebsocketConsumer) class now receives the bytes_data and uses this function to convert and send it to google: def transcriber(bytes_data: bytes): r = sr.Recognizer() audio = AudioSegment.from_raw( bytes_data, sample_width=2, frame_rate=16000, channels=1) buffer = io.BytesIO() audio.export(buffer, format="wav") buffer.seek(0) with sr.AudioFile(buffer) as source: audio = sr.AudioData(source.stream.read(), sample_rate=16000, sample_width=2) try: transcription = r.recognize_google(audio, language="en-USA").lower() except sr.UnknownValueError as e: print(e) return transcription But that does not work. I have tried some variations and others I simply don't understand. A comprehensive solution would be appreciated. -
Pycryptodome PBKDF2 same password and salt, different hash
I am using PBKDF2 to hash a key challenge (a uuid is generated on the server, encrypted using the user's public key, then the user decrypts the challenge and sends it to the server for api access). When the uuid is generated it is supposed to be hashed, then stored in the db, then when the user sends the decrypted uuid, the server must hash it to compare with the stored hash. When I tested this, the user sends the correct uuid, and the salt is the same (stored alongside the hash), but the hash is different. What could cause this? See code and sample values below. Hashing function: from Crypto.Hash import SHA512 from Crypto.Protocol.KDF import PBKDF2 from Crypto.Random import get_random_bytes def PBKDF_HASH(salt, plain, length): hashed = PBKDF2(plain, salt, length, count=1000000, hmac_hash_module=SHA512) print('HASHD: ') print(base64.b64encode(hashed)) return base64.b64encode(hashed) #hash is base64 encode for db storage Challenge generator: def challengeGenerator(): uuid = secrets.token_hex(64) print(uuid) salt = get_random_bytes(64) print(salt) hash = PBKDF_HASH(salt, uuid, 128) #uuid is encrypted and hash + salt are stored in db User Authentication Test: print(user_uuid) #decrypted uuid sent in request salt = #salt retrieved from db print(salt) hash = PBKDF_HASH(salt, user_uuid, 128) #hash is compared to the hashed uuid … -
django eventstream - only empty data
I installed and followed the guide from the git, but I hit a wall once I try to execute a send_message() call using the shell. I rewrote the asgi.py: application = ProtocolTypeRouter({ "http": URLRouter([ path("msgs/", AuthMiddlewareStack(URLRouter(django_eventstream.routing.urlpatterns)), { "format-channels": ["test"] }), re_path(r"", get_asgi_application()), ]), }) and I created the entries in urls.py: urlpatterns = [path("msgs/", include(django_eventstream.urls), {'format-channels': ["test"]})] I also added the static ressources to my static directory and I can access them on any page that includes my base.html. But when I open the local msgs channel at 127.0.0.1\msgs\ I only see: When opening a shell in a second terminal and using send_event("test", "message", {"text": "hello"}) I see no indication whatsoever that anything is sent out to the frontend. Also the JS sample code from the repo fetches nothing on the main page when sending out data in a loop with starting django (using the fantastic scheduler huey here): @periodic_task(crontab(minute = "*/1")) def test(): send_event('test', 'message', {'text': 'hello world'}) print("hello world...") I see the output of print() but not the result of send_message() on the frontend. Also, there is no implication that my scheduled or manually run send_message() actions result in anything on the \msgs\ channel - the timing does … -
Why I get this error when I trie to do the migrations on Django 3.2.6?
I was trying to update mi DB using the comand python manage.py makemigrations after of delete all the files of migrations in my Django project, because when I try to do the changes on my db doesnt apply This is my model class ciudades(models.Model): ciudad_nombre = models.CharField(max_length=50) estado = models.CharField(max_length=50) def __str__(self): return self.name class Meta: db_table = 'ciudades' verbose_name ='Ciudad' verbose_name_plural = 'Ciudades' This is the error that I get Traceback (most recent call last): File "/Users/dorianraygoza/Downloads/doha-erp/manage.py", line 22, in <module> main() File "/Users/dorianraygoza/Downloads/doha-erp/manage.py", line 19, in main execute_from_command_line(sys.argv) File "/Users/dorianraygoza/Downloads/doha-erp/venv/lib/python3.11/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/Users/dorianraygoza/Downloads/doha-erp/venv/lib/python3.11/site-packages/django/core/management/__init__.py", line 395, in execute django.setup() File "/Users/dorianraygoza/Downloads/doha-erp/venv/lib/python3.11/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/dorianraygoza/Downloads/doha-erp/venv/lib/python3.11/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) ^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/dorianraygoza/Downloads/doha-erp/venv/lib/python3.11/site-packages/django/apps/config.py", line 124, in create mod = import_module(mod_path) ^^^^^^^^^^^^^^^^^^^^^^^ File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1206, in _gcd_import File "<frozen importlib._bootstrap>", line 1178, in _find_and_load File "<frozen importlib._bootstrap>", line 1149, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 690, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 940, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "/Users/dorianraygoza/Downloads/doha-erp/venv/lib/python3.11/site-packages/django/contrib/auth/apps.py", line 8, in <module> from .checks import check_models_permissions, check_user_model File "/Users/dorianraygoza/Downloads/doha-erp/venv/lib/python3.11/site-packages/django/contrib/auth/checks.py", line 8, in … -
Negative indexing is not supported in django
I am trying to upload image and show the same in my site but instead i am getting this error my current django-mptt version is 0.5.1 views.py- def home(request): print('here you go ') images=[] images=image_classification.objects.all() url=images[len(images)-1].pic.url return render(request,'home.html',{'print':'everything is ok','image':url}) #handles uploaded images def uploadImage(request): print('image handling ') img= request.FILES['image'] image=image_classification(pic=img) image.save() return HttpResponseRedirect('/') inside models.py from django.db import models class image_classification(models.Model): pic=models.ImageField(upload_to='images') and the error i am facing Traceback (most recent call last): File "C:\Users\prasa\Desktop\Pytorch-Django\venv\Lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Users\prasa\Desktop\Pytorch-Django\venv\Lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\prasa\Desktop\Pytorch-Django\MainApp\ImageClassifier\views.py", line 10, in home url=images[len(images)-1].pic.url File "C:\Users\prasa\Desktop\Pytorch-Django\venv\Lib\site-packages\django\db\models\query.py", line 425, in __getitem__ raise ValueError("Negative indexing is not supported.") Exception Type: ValueError at / Exception Value: Negative indexing is not supported. -
static files are are not working in django
I want to display an image on my site but static file are not being found this is my directory my url: STATIC_URL = 'static/' and my html: {% load static %} -
In Django, I'm having trouble getting the id from HTML; the error is: ( Field "id" expected a number but got )
When the user selects the translator name, I want to access the selected translator in Django by the id and store the information in an appointment table in the database, but there is an error when he tries to mach the id the error is: Field 'id' expected a number but got ''. HtML code: <section style="margin-top: 10%;"> <form method="POST" action="/waite" > {% csrf_token %} <select id="translator" name="translator"> {% for i in pro %} <option value="{{ i.id }}"> {{ i.name }}</option> {% endfor %} </select> <button type="submit">Send request</button> </form> </section> in django view.py: def waitePage(request): if request.method == 'POST': id = request.POST.get("translator") translator = Manager.objects.get(user_id=id) translatorName= translator.name #get the name of the translator translatorID= translator.id #get the id of the translator current_user = request.user #to get the user current_userId = current_user.id #for storing user id customer = Customer.objects.get(id=current_userId) #to get the info of translator customerID=customer.id customerName=customer.name appointment = Appointment.objects.create( customerName=customerName, customerID=customerID, translatorID=translatorID, accepted=False,) appointment.save() return render(request,'waitePage.html') The error comes from: translator = Manager.objects.get(user_id=id) Do you guys have any idea how I can solve it? Do you guys have any idea how I can solve it? -
Slug not recognized
The urls.py file created, containing the app_name = "articles" which is not recognized in the "template_base.html" established as model template. NoReverseMatch at /articles/ Reverse for 'article' with keyword arguments '{'slug': ''}' not found. 1 pattern(s) tried: \ ['articles/(?P\<slug\>\[-a-zA-Z0-9\_\]+)/\\Z'\] The affected line is : \<h2\>\<a href="{% url 'articles:article' slug=article.slug %}"\>{{ article.titre }}\</a\>\ </h2\> 3 times I try to perform the same code as in the lesson but I need your help. urls.py from django.contrib import admin from django.urls import path, include from articles import views app_name = "articles" urlpatterns = [ path('', views.articles_view, name='articles'), path('<slug:slug>/', views.article_view, name='article') ] template_base.html <!DOCTYPE html> <html lang="fr"> <head> <meta charset="UTF-8"> <title>{% block titre %}{% endblock %}</title> </head> <body> <ul style="list-style: none"> <li style="display: inline-block; padding: 10px 20px;"> <a href="{% url 'home' %}">Accueuil</a> </li> <li style="display: inline-block; padding: 10px 20px;"> <a href="{% url 'articles:articles' %}">Articles</a> </li> <li style="display: inline-block; padding: 10px 20px;"> <a href="{% url 'contact' %}">Contact</a> </li> </ul> {% block contenu %} {% endblock %} </body> </html> view.py from django.shortcuts import render from django.http import HttpResponse from articles.models import Article def articles_view(request): articles = Article.objects.all() return render(request, 'articles/list.html', context={'articles': articles}) def article_view(request, slug): return HttpResponse("Page d'article") -
Django filter on list of column values
I'm using Django 3.2 and Postgres 13. I have a simple model: from django.db import models class Member(models.Model): user = models.ForeignKey("User", on_delete=models.CASCADE) group = models.ForeignKey("Group", on_delete=models.CASCADE) class Meta: constraints = [ models.UniqueConstraint( fields=["user", "group"], name="unique_user_group_tuple" ) ] The important info here is the UniqueConstraint, which also creates a unique index. Let's say I have a list of (user_id, group_id) tuples: member_tuples = [(1, 1), (2, 1), (2, 4)] I would like to retrieve all existing Member objects matching these tuples, while using the index. In PG, I would write: SELECT * from members where (user_id, group_id) in ((1, 1), (2, 1), (2, 4)); My question is: how to get something similar in Django ? Obviously, my main concern is to keep calling the unique_user_group_tuple index, to avoid a sequential scan For now, the best solution I found is to do: filters = Q() for user_id, group_id in member_tuples: filters |= Q(user_id=user_id, group_id=group_id) existing_members = Member.objects.filter(filters) which translates to SELECT * from members WHERE (issue_id = 1 AND group_id = 1) OR (issue_id = 2 AND group_id = 1) OR (issue_id = 2 AND group_id = 4); This also queries the index, but it does not creates the query I expect. … -
CSS Rating Start not checking after click
CSS /* Hide Radio button */ .rate > input{ display: none; } .rate{ display: inline-block; border: 0; } .rate > label{ float: right; } /* Showing the stars */ .rate > label:before{ display: inline-block; font-size: 1.1rem; font-family: FontAwesome; content: "\f005"; margin:0; padding:0.3rem .2rem; cursor: pointer; } /* Half star */ .rate .half:before{ content: "\f089"; position: absolute; padding-right: 0; } /* Click and hover */ input:checked ~ label, label:hover ~ label{ color: #ffb503; } /* Hover highlight */ input:checked + label:hover, input:checked ~ label:hover, input:checked ~ label:hover ~ label, label:hover ~ input:checked ~label{ color: #cc9000; } I try to click on starts and remains saved at least on frontend to see them as checked but after i click one start it don't remain with that color, instead it remains the same as the beginning. How to fix it so after i click to see the input ( to see the stars colored ) -
Django website error 500 when uploading while using AWS
I am running a Django website on an EC2 instance while having my static files on S3 Bucket Storage and every time I try to upload something the post request returns Error Code 500 Internal Server Error. The code works locally with the bucket storage, but it doesn't work with the EC2 instance. -
Django developtment page does not load on Cloud server
i have bought an ionos cloud (linux/ubuntu) server with: 1v Core Cpu and 1gb of RAM When i try to host the developtment server (with manage.py runserver) everythin works fine, but when i then try to connect to that server, there is simply a problem loading the page, as if this page isnt avaible. Note that i didnt install anything else than Django and the requirements for my Project, so no ngix or something. But what i did is i have set up an UFW firewall to block every port except of port 8000 (on which i am running the testserver) If you guys have any ideas or questions pls let me know. PS: its 100% not my Internet connection. PLS and Thank you.:) -
Jupyter Notebook workbench Integration
i want to integrate JupyterNotebook AI bench in Data Science Toolkit/website. where we have listing of existing Notebooks Create Your Own Notebooks Change on existing Notebooks Parameters Schedule and Run Notebooks I checked the solution that, host the Jupyter notebook somewhere, and call in your web page through iframe, but I think after this we cant be able to customize it what did you suggest the best practice for this ? Which React JS package did you suggest for this type of integration? or we need to develop the code from scratch for Front End Thanks. Which JS library did you suggest for this type of integration ? -
Django tooltip translation not working with white spaces
I am translating an html tooltip using i18n which does not show when it is between translation tags {% translate ... %} unless spaces are removed. Code without translate tag: <th scope="col">{% trans '% Name' %} <span class="tt" data-bs-placement="bottom" title= 'Some normal text (NT) with spaces.'><i class="bi bi-question-circle-fill hover-only" style="font-size: 1.2rem;"></i></span></th> The code with translation tag shows only the first word before the white space. <th scope="col">{% trans '% Name' %} <span class="tt" data-bs-placement="bottom" title= {% translate 'Some normal text (NT) with spaces.' %}><i class="bi bi-question-circle-fill hover-only" style="font-size: 1.2rem;"></i></span></th> When the white spaces are removed with _, the whole text shows even if between the {% translate .. %} tag. <th scope="col">{% trans '% Name' %} <span class="tt" data-bs-placement="bottom" title= {% translate 'Some_normal_text_(NT)_with_spaces.' %}><i class="bi bi-question-circle-fill hover-only" style="font-size: 1.2rem;"></i></span></th> Anyone knows how to show the whole text with white spaces? -
MQTT and data reading
I have 3 temperature sensors and I want to read their data and put it on a dashboard to monitor it in real time, how to do it? I want to use MQTT protocol, Python and Django or Flask. Are there tutorials videos where to start? Need help. Is it possible to create such a platform for use at home? Is it possible to create such a platform for use at home? I have 3 temperature sensors and I want to read their data and put it on a dashboard to monitor it in real time, how to do it? I want to use MQTT protocol, Python and Django or Flask. Are there tutorials videos where to start? Need help. Is it possible to create such a platform for use at home? -
How to remove relation from django model with ManyToMany field?
How to remove relation from model with ManyToMany field? I've got a model with ManyToManyField relation. I need to remove relation but not data from the following model: class TxHomes(models.Model): user = models.ManyToManyField(settings.AUTH_USER_MODEL) home_id = models.PositiveIntegerField(primary_key=True, unique=True, null=False) name = models.CharField(max_length=255, null=True) geo_name = models.CharField(max_length=255, null=True) payload = models.JSONField() Django ORM got tables generated: -- auto-generated definition create table main_txhomes ( home_id integer unsigned not null primary key, name varchar(255), geo_name varchar(255), ... ); create table main_txhomes_user ( id primary key autoincrement, txhomes_id ..., user_id ... ); When I apply to do that with a following code TxHomes.objects.filter( home_id__in=TxHomes.objects.filter(user=USER_ID).values('home_id') ,user=USER_ID).delete() i got entire data deleted from main_txhomes I want to keep data in main_txhomes table, what i need is to delete relations from main_txhomes_user table. How to do that? -
Django-ckeditor showing content as textarea
I'm working with django ckeditor now and I can't display content that can be saved normally and is displayed in the admin panel. Content is always displayed as textarea As you can see at the image, editor is working properly, also if i go to admin panel everything is OK, but if i want to display content of "body" ({{ form.body|safe}}), it will display only textarea of HTML code. models.py class Stage(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) game_id = models.ForeignKey(Game, on_delete=models.CASCADE) name = models.CharField(max_length=128) sequence = models.IntegerField(null=False) body = RichTextUploadingField(config_name='LeftFields', blank=True, null=True) def get_questions(self): return Question.objects.filter(stage_id = self.id) def __str__(self): return str(self.name) forms.py class StageForm(ModelForm): class Meta: model = Stage fields = ['body','name'] widgets = { 'name': TextInput(attrs={ 'class': "left_input", 'style': "width: 69.3%;", }), } views.py @login_required(login_url='/signin') @user_passes_test(lambda u: u.is_staff) def edit(request, gameid,id): stage = Stage.objects.get(pk=id) if request.method == 'POST': form = StageForm(request.POST, instance=stage) if form.is_valid(): form.save() return redirect('/edit/' + gameid + '/' + id) form = StageForm(instance=stage) return render(request, "homeSuperuser/edit_stage.html", {'stage': stage, 'form': form,'gameid':gameid}) edit_stage.html <!doctype html> <html> <head> {% load static %} <link rel="stylesheet" href="{% static 'css/edit_pages.css' %}" /> <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons" /> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script> <script type="text/javascript" src="{% static 'js/edit.js' %}"></script> </head> <body> … -
Should I use Django, Spring Boot or React?
there are 4 of us in the company and I am the only software guy. We are going to make a web app for a client where orders are going to be taken into account and manufacturing orders (MO) are created in an optimal way. Our client is going to provide us with the data to train an artificial intelligence model that will create the manufacturing orders in an optimal way. The data will be: employees (schedule, calendar...), orders that are created, and manufacturing processes (MP) with their respective dependencies in terms to other MPs. I am thinking about creating the AI with python and deploying it. Then create a web (I don't know which technologies to use. If frontend React or do it all with Spring Boot or Django) and make requests to the AI API. I have no experience with React and with the other two I have very little experience. Which technology should I use? I would also appreciate any help regarding artificial intelligence since I only know that I am going to use Python for it. I think the best solution is to use Django since I understand Python and the project is in a bit … -
Passing a list to Django template from include
I have an include tag for template that needs to render a list passed from include tag. https://docs.djangoproject.com/en/4.1/ref/templates/builtins/#include {% include "list.html" with animal_list=["Cat","Dog"] %} -
Need to edit django get request to include list of models given a list of id's
I'm currently creating the backend for a website in which users can add public events/gatherings to their favorites list. I'm currently creating a model in Django which models a user created account named Account. I want to implement it so that Account includes a field called "favorites" which stores the id's of the Events that the specific account added to their favorites. class Account(models.Model): username = models.CharField(max_length=20, null=True) first_name = models.CharField(max_length=30, null=True) last_name = models.CharField(max_length=30, null=True) email = models.EmailField(max_length=254, null=True) phone_number = models.CharField(max_length=254, null=True) class Favorites(models.Model): favorite = models.PositiveIntegerField(null=True) account = models.ForeignKey(Account, related_name='favorites', on_delete=models.CASCADE, null=True) def __str__(self): return f"{self.favorite}" class Events(models.Model): event_image = models.ImageField(null=True) # will have to figure out where this image is uploaded to event_name = models.CharField(max_length=50, null=True) event_date_time = models.DateTimeField(max_length=50, null=True) event_location = models.CharField(max_length=50, null=True) event_description = models.TextField(null=True) Currently I can send a post request of this form, for this example this specific account favorited Events with id of 15 and 17. { "username": "Name", "first_name": "John", "last_name": "Doe", "email": "Johndoe@gmail.com", "phone_number": "6666666666" "favorites": [{favorite: "15"}, {favorite: "17"}] } However after sending a post request like that I want to have my get request be of this form { "username": "Name", "first_name": "John", "last_name": "Doe", "email": "Johndoe@gmail.com", … -
Unable to authenticate using cookie-based authentication in Django React
I am trying to run a Django server and React app with cookie-based authentication. The authentication is being done using django-graphql-jwt and Apollo Client. The authentication process works correctly and I am receiving a JWT token, but the cookies are not being set. Here is my setting files: basic.py # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'users', 'todolist', # Pip packages 'stripe', 'corsheaders', "graphene_django", 'graphql_jwt', 'graphql_jwt.refresh_token.apps.RefreshTokenConfig', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', # Corsheaders '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', 'whitenoise.middleware.WhiteNoiseMiddleware', # Whitenoise #"django_graphql_ratelimit.middleware.ParseClientIpMiddleware", # Django graphql ratelimit ] # Password validation AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] development.py import os DEBUG_VALUE = os.getenv('DEBUG') SECRET_KEY = os.getenv('SECRET_KEY') # Server is running in production if DEBUG_VALUE == False or DEBUG_VALUE == 'False': # HTTPS settings CSRF_COOKIE_HTTPONLY = False CSRF_COOKIE_SECURE = True SESSION_COOKIE_SECURE = True SECURE_SSL_REDIRECT = True # HSTS settings SECURE_HSTS_SECONDS = 31536000 # 1 year SECURE_HSTS_PRELOAD = True SECURE_HSTS_INCLUDE_SUBDOMAINS = True # Corsheaders CORS_ALLOW_CREDENTIALS = True CORS_ALLOWED_ORIGINS = [ 'http://127.0.0.1:8000', 'http://localhost:3000', 'https://my-todo-app-frontend-site.netlify.app' ] ALLOWED_HOSTS = [ '127.0.0.1', '.vercel.app', 'www.my-todo-app-frontend-site.netlify.app' ] # Whitenoise STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' ROOT_URLCONF = 'backend.urls' WSGI_APPLICATION = 'backend.wsgi.application' … -
django unique constraint fails
I am creating a book model, and with that model, there is a isbn variable that should have the unique constraint set to true which should stop there from being duplicate isbn values in my database. however when unit testing this model, the test_isbn_must_be_unique() test fails to raise the validation error even though I have set unique to be true in the book model. I was expecting the test to pass since I had set unique to be true in the list of constraints for the isbn variable. however, the test fails. `# models.py file from django.core.validators import RegexValidator from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): username = models.CharField( max_length=30, unique=True, validators=[RegexValidator( regex=r'^@\w{3,}$', message='Username must consist of @ followed by at least three alphanumericals' )] ) first_name = models.CharField(max_length=50, blank=False) last_name = models.CharField(max_length=50, blank=False) email = models.EmailField(unique=True, blank=False) bio = models.CharField(max_length=520, blank=True) class Book(models.Model): isbn = models.CharField(max_length=13, unique=True, null=False, blank=False) book_title = models.TextField(blank=False, max_length=500) book_author = models.CharField(blank=False, max_length=255) year_of_publication = models.CharField(max_length=13, blank=False) publishers = models.CharField(blank=False, max_length=255) image_url_s = models.CharField(blank=False, max_length=255) image_url_m = models.CharField(blank=False, max_length=255) image_url_l = models.CharField(blank=False, max_length=255)` `"Testing Book Model" from django.test import TestCase from django.core.exceptions import ValidationError from clubs.models import Book class BookModelTestCase(TestCase): def setUp(self): … -
'User' object has no attribute 'user_type' - Django Custom User model issue
I've created a custom user abstract model and profile model to collect additional information once the user registers. I am collecting "User type: Employer/employee" at the time of registration but this doesn't seem to be recognized in the profile view. Despite the user being correctly added into the DB (I checked via Admin). For example, I created user: asus23910 (employer user type). But when I login and redirect to http://127.0.0.1:8000/employer_profile/asus23910/, I get following error: 'User' object has no attribute 'user_type'C:\Users\ASUS\PycharmProjects\Content\content\content\views.py, line 112, in employer_profile_view 1. Here's my employer_profile_view.py code: def employer_profile_view(request, username): user = User.objects.get(username=username) if user.user_type != User.EMPLOYER: # Redirect to the correct profile page if the user type is not employer return redirect('employee_profile', username=request.user.username) if request.method == 'POST': form = EmployerProfileForm(request.POST, instance=user.employerprofile) if form.is_valid(): employer_profile = form.save(commit=False) employer_profile.user = user employer_profile.save() return redirect('employer_profile', username=request.user.username) else: form = EmployerProfileForm(instance=user.employerprofile) context = { 'form': form, 'username': username, } return render(request, 'employer_profile.html', context) 2. Employer Profile model and connector class EmployerProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) user_type = models.CharField( max_length=10, choices=User.USER_TYPE_CHOICES, default=User.EMPLOYER ) first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) title = models.CharField(max_length=255) company_name = models.CharField(max_length=255) company_logo = models.ImageField(upload_to='company_logos/') company_location = models.CharField(max_length=255) company_website = models.URLField() company_twitter = models.URLField() #one-2-one connector @receiver(post_save, sender=User) def …