Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to Sort values of a qury in Django based on the quantity of child table?
Hello guys i have a Product Class that have a child class ProductColors this is my two class : class Product(models.Model): category = models.ForeignKey(Category, related_name='products', on_delete=models.CASCADE) name = models.CharField(max_length=255) slug = models.SlugField(unique=True, allow_unicode=True) description = models.TextField() price = models.PositiveIntegerField() available = models.BooleanField(default=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) discount = models.PositiveIntegerField(default=0) offer_end = models.DateTimeField(blank=True, null=True) user_likes = models.ManyToManyField(User, related_name="product_likes", blank=True) and : class ProductColor(models.Model): class ColorChoices(models.TextChoices): RED = "#f50b0b","قرمز" BLUE = "#0844f3","آبی" YELLOW ="#f7f704", "زرد" GREEN = "#22f704","سبز" PINK = "#f704e8","صورتی" PURPLE = "#901f89","بنفش" GRAY = "#9c939c","خاکستری" WHITE = "#ffffff","سفید" BLACK = "#000000","سیاه" ORANGE = "#f2780c","نارنجی" BROWN = "#513924","قهوه ای" GLASS = "#f3f3f2", "بی رنگ" product = models.ForeignKey(Product, related_name='colors', on_delete=models.CASCADE) color = models.CharField(choices=ColorChoices.choices, max_length=255) quantity = models.PositiveIntegerField(default=0) def __str__(self): return f"{self.product.name} - {self.color}" i am trying to sort products based on first -available and then the quantity of colors from higher quantity to zero i try to do this with this method : from django.db.models import Count, When, Case, IntegerField products = Product.objects.all().order_by('-available', 'name') products = products.annotate( has_zero_quantity=Case( When(colors__quantity=0, then=1), When(colors__quantity__gt=0, then=0), output_field=IntegerField(), ) ) but i stuck and i cant find the correct way anyone can help for solution ? -
Django admin pannel redirect to /accounts/login/?next=/admin/
Whenever I open my django admin pannel it redirects to the following URL /accounts/login/?next=/admin/ I'm using DRF and all my DRF APIs running properly but my admin pannel is not opening every time it is redirecting to above URL. But I didn't setup any above URL in my project setup. -
Django - Allauth doesnt use the custom signup form
I work with Django-Allauth and React as a FE. I added a parameter called name for for the Custom User I created, I've overridden the SignupForm in Forms.py to save it, and just like the documentation said I changed the settings.py to have ACCOUNT_FORMS = {'signup': 'XXXX.forms.CustomSignupForm'} But the form does not get initiated when signing up - i added prints that don't go through. A user is being created - but probably with the default form, and doesn't add the additional parameter I added. I checked and the frontend sends the payload properly. I have this in forms.py class CustomUserCreationForm(UserCreationForm): name = forms.CharField(max_length=30, required=True, help_text='Enter your name.') class Meta: model = CustomUser fields = ("email", "name") class CustomSignupForm(SignupForm): name = forms.CharField(max_length=40, required=True, help_text='Enter your name.') def __init__(self, *args, **kwargs): print("CustomSignupForm is being initialized") super().__init__(*args, **kwargs) def save(self, request): print("im working") user = super().save(request) user.name = self.cleaned_data['name'] user.save() return user urls.py urlpatterns = [ path("admin/", admin.site.urls), path('', include('XXXX.urls')), path('accounts/', include('allauth.urls')), path("_allauth/", include("allauth.headless.urls")), ] I also tried using an ACCOUNT_ADAPTER in settings, and this is how the adapter looks in adapters.py class CustomAccountAdapter(DefaultAccountAdapter): # def get_signup_form_class(self): # return CustomSignupForm But it didn't use the form. Also tried to edit the CustomUserManager, … -
Any way to keep the cards always inside the background image?
I want the cards to remain inside of the background image no matter of the screen size, and it's not working with me. Here's my content code {% block content %} <style> .custom-skills-section { background: url('{{ background_image }}') center center / contain no-repeat; border-radius: 10px; padding: 20px; margin: 0 auto; width: 100%; max-width: 1600px; height: 1200px; } .custom-skill-card-shadow { height: 150px; display: flex; align-items: center; justify-content: center; } .custom-skill-card-content { border-radius: 8px; box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1); background-color: #f0f4f8; display: flex; align-items: center; justify-content: center; width: 100%; height: 100%; } .custom-skill-title { font-size: 1em; font-weight: 600; color: #333; text-align: center; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; width: 100%; } </style> <div class="d-flex justify-content-center align-items-center" style="min-height: 100vh;"> <div class="custom-skills-section"> <h2 class="text-center text-white py-4">My Skills</h2> <div class="container"> <div class="row"> {% for skill in skills %} <div class="col-lg-4 col-md-6 col-12 mb-4 custom-skill-card"> <div class="custom-skill-card-shadow"> <div class="custom-skill-card-content"> <h4 class="custom-skill-title">{{ skill.name }}</h4> </div> </div> </div> {% endfor %} </div> </div> </div> </div> {% endblock content %} Hello, I'm my idea is to put the cards inside the note board to appear like old school. but the cards always get out from the note board. on smaller screens they get out from up … -
The events in fullcalendar sometimes duplicate on my database when i move them to another date/time. How can i solve this?
I'am using fullcalendar 6.1.14 in django 4.2.11. I have a function defined to update the delivery date of an item where the number of the document of the item is the same as the event id and the year is the year that it is changing it from and i even have a check for it to not add already existing NumDoc + Year combinations, but sometimes, ramdomly, it duplicates the event in the database when i drag them to a new date and i have no idea how to solve this. I'am using Microsoft MySQL Server Mangement as database manager. Function to Move Events in views.py @csrf_exempt def update_delivery_date(request): if request.method == 'POST': event_id = request.POST.get('id') new_start_date = request.POST.get('new_start_date') year = request.POST.get('year') # Check if the user has the allowed groups if not (request.user.groups.filter(name__in=['Expedicao', 'Dir Logistica', 'Logistica']).exists() or request.user.is_superuser): return JsonResponse({'success': False, 'error': 'User does not have permission to move events'}, status=403) try: with transaction.atomic(): # Find the specific event by DocNum and Year event = EncomendasCalendar.objects.select_for_update().get(NumDoc=event_id, Ano=year) # Check if there is already another event with the same DocNum and Year if EncomendasCalendar.objects.filter(NumDoc=event_id, Ano=year).exclude(NumDoc=event_id).exists(): print("Duplicate") return JsonResponse({'success': False, 'error': 'An event with the same DocNum and Year already … -
Django ModelForm doesn't update instance but fails with IntegrityError
I'm having some really weird issue with a ModelForm. Instead of saving the instance, it attempts to create the instance with the same primary key. class Upload(models.Model): file = models.FileField(upload_to=get_foundry_upload_name, null=False, blank=False) filename = models.CharField(max_length=256, null=True, blank=True) foundry = models.ForeignKey(Foundry, on_delete=models.CASCADE) family = models.CharField(max_length=256, null=True, blank=True) family_select = models.ForeignKey(Family, null=True, blank=True, on_delete=models.CASCADE) style = models.CharField(max_length=256, null=True, blank=True) style_select = models.ForeignKey(Style, null=True, blank=True, on_delete=models.CASCADE) processed = models.BooleanField(default=False) created = models.DateTimeField("Created", auto_now_add=True) class UploadProcessForm(ModelForm): class Meta: model = Upload fields = ( "filename", "family", "family_select", "style", "style_select", ) def upload_process_row(request, foundry, id): i = get_object_or_404(Upload, id=id, foundry=foundry) upload_form = UploadProcessForm(instance=i) if request.method == "POST": upload_form = UploadProcessForm(request.POST, instance=i) if upload_form.is_valid(): upload_form.save() return render(request, "foundry/upload_process.row.html", { "f": upload_form }) django.db.utils.IntegrityError: duplicate key value violates unique constraint "foundry_upload_pkey" DETAIL: Key (id)=(1) already exists. I'm certain this is some super trivial mistake, but I just cannot spot where I'm going wrong; imo this looks exactly like the textbook example. The upload_form.save() always attempts to create a database entry, and with the instance's primary key. I'd just want to update the existing instance (that's the whole point of a ModelForm, no?). I've wiped the database table and migrations and recreated them fresh, just to be sure. -
Django Under the Impression that I'm Missiing Positional Arguements
So Django is currently under the impression that I am missing positional arguments when I'm putting together a help section for a website. This includes help articles which are sourced from the Django model. Everything works as expected until I include the unique help article reference number into my views.py file. Django believes that positional arguments are missing when this is simply not true. As you will see in my MRE below, there are no missing positional arguments. The error message is as follows: help_center_article_index() missing 1 required positional argument: 'support_article_reference' MRE: #utils.py import requests, random, string def generate_unique_number(charlimit): random_string = ''.join(random.choices(string.digits, k=charlimit)) # Generates a random string return f"{random_string}" #models.py from .import utils class SupportArticles(models.Model): class TargetGroup(models.TextChoices): FOR_DEVELOPERS = 'developers','Developers' FOR_Clients = 'clients','Clients' FOR_FX_Providers = 'fx-providers','FX Providers' support_article_reference = models.CharField(max_length=50, default=utils.generate_unique_number(15), editable=False) support_article_title = models.CharField(max_length=255, verbose_name="Support Article Title") support_article_body = models.TextField(max_length=5000,verbose_name="Support Article Body") support_article_tags = models.CharField(max_length=100,default="Separate each tag category with a comma (,)", verbose_name="Support Topic Tags") support_article_group = models.CharField(max_length=15,choices=TargetGroup.choices,default=TargetGroup.FOR_Clients) #views.py from django.shortcuts import render, get_object_or_404 def help_center_article_index(request, group, support_article_reference): support_article_object = SupportArticles.objects.filter(support_article_group = group, support_article_reference = support_article_reference) if support_article_object.exists(): meta_property_title = support_article_object.first().support_article_group) else: meta_property_title = "No articles available for this group" context = { 'meta_property_title' : meta_property_title, 'meta_property_description' : … -
Django check if a user is connected to wi-fi
I would like to check if a user is connected to wi-fi. If the user is connected to WiFi than they would be able to upload a video. If the user is not connected to WiFi than they would not be able to upload a video. I am not checking for internet instead I am checking for WiFi since cellular data counts as internet. The reason I don’t want Cellular data is because it is weak for video uploads and creates load problems which I would like to block in all. -
How to connect to a RabbitMQ cluster with Django?
In the documentation: https://github.com/Bogdanp/django_dramatiq/blob/master/django_dramatiq/apps.py It gives the following example: DEFAULT_BROKER = "dramatiq.brokers.rabbitmq.RabbitmqBroker" DEFAULT_BROKER_SETTINGS = { "BROKER": DEFAULT_BROKER, "OPTIONS": { "host": "127.0.0.1", "port": 5672, "heartbeat": 0, "connection_attempts": 5, }, "MIDDLEWARE": [ "dramatiq.middleware.Prometheus", "dramatiq.middleware.AgeLimit", "dramatiq.middleware.TimeLimit", "dramatiq.middleware.Callbacks", "dramatiq.middleware.Retries", "django_dramatiq.middleware.AdminMiddleware", "django_dramatiq.middleware.DbConnectionsMiddleware", ] } But does not say about connecting to a cluster with multiple nodes in case of fail-over. I know in the shell you can do something like this: credentials = pika.PlainCredentials(getenv('RMQ_USER'), getenv('RMQ_PASS')) parameters = [ pika.ConnectionParameters(host=getenv('RMQ_1'), port=getenv('RMQ_PORT_1'), credentials=credentials, virtual_host=getenv('VIRTUAL_HOST')), pika.ConnectionParameters(host=getenv('RMQ_2'), port=getenv('RMQ_PORT_2'), credentials=credentials, virtual_host=getenv('VIRTUAL_HOST')), pika.ConnectionParameters(host=getenv('RMQ_3'), port=getenv('RMQ_PORT_3'), credentials=credentials, virtual_host=getenv('VIRTUAL_HOST'), connection_attempts=5, retry_delay=1) ] But i dont know how to do it from the Django settings. -
all users are displayed as "Active" even though they are supposed to be inactive, [closed]
list.html <p>Active Status: {% if datas.employee.is_active %}Active{% else %}Inactive{% endif %}</p> models.py class Employee(models.Model): is_active = models.BooleanField(default=True) def delete(self): self.is_active = True self.save() ) -
Django Migration Error: admin.0001_initial is applied before its dependency users.0001_initial
I'm building a Django application with a custom user model, and I'm getting a migration error. I've already created my initial migrations but when trying to apply them, I get a dependency error. Error Message django.db.migrations.exceptions.InconsistentMigrationHistory: Migration admin.0001_initial is applied before its dependency users.0001_initial on database 'default'. here is my My Settings Configuration (settings/base.py): AUTH_USER_MODEL = 'users.User' DJANGO_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] THIRD_PARTY_APPS = [ 'rest_framework', 'django_filters', 'corsheaders', 'django_extensions', 'simple_history', 'phonenumber_field', ] LOCAL_APPS = [ 'apps.users.apps.UsersConfig', 'apps.courses.apps.CoursesConfig', 'apps.calendar_app.apps.CalendarAppConfig', ] INSTALLED_APPS = DJANGO_APPS + THIRD_PARTY_APPS + LOCAL_APPS What I've tried: Running python manage.py makemigrations users Running python manage.py migrate Both commands result in the same error. How can I fix this without deleting my database? -
Sending an array from jQuery to a Django view
I am making a very small application to learn Django. I am send a nested array from jQuery and trying to loop it in my Django view. The jQuery code is as follows: $(document).on('click','#exModel',function () { const sending = []; $("table tr").each(function () { var p1 = $(this).find("th label").html(); var p2 = $(this).find("td input").attr('id'); var p3 = $(this).find("td input").val(); const build = []; build.push(p1, p2, p3); sending.push(build); console.log(sending); }); $.ajax({ url: '../coreqc/exModel/', data: {'sending': sending}, type: 'post', headers: {'X-CSRFToken': '{{ csrf_token }}'}, async: 'true', success: function (data) { console.log("I made it back") //dom: 'Bfrtip', } }); }); The above works and takes the following form in the console: Note that the 3rd value is intentionally empty as I sent the form with no values in the fields to get the console read out. [Log] [["Product A", "1", ""], ["Product B", "2", ""], ["Product C", "3", ""], ["Product D", "4", ""], ["Product E:", "5", ""], ["Product F", "6", ""], ["Product G", "7", ""], ["Product H", "8", ""], ["Product I", "9", ""], ["Product K", "10", ""], …] (36) (coreqc, line 491) [Log] I made it back # This is the success text in the above jQuery code It is making it to … -
detected dubious ownership in repository
I have a django project called my_project containing a database. In order to run the website with apache, I had to modify the access rights and ownership with sudo chown www-data:www-data my_project/ sudo chmod 755 my_project/ At least this is how I got it to work. But now, when I run git pull I get the following error message: fatal: detected dubious ownership in repository Can I just suppress this error message or is this a security issue? Please let me know if I have to configure something differently. -
The image is not being stored in the media folder in Django, but the database contains the image name
views.py employee = Employee.objects.create( user=request.user, # Assigning the current user first_name=request.POST.get('employee_firstname'), middle_name=request.POST.get('employee_middlename'), last_name=request.POST.get('employee_lastname'), email=request.POST.get('employee_email'), land_phone_number=request.POST.get('employee_landphone'), mobile_phone_number=request.POST.get('employee_mobile'), gender=request.POST.get('gender'), hire_date=request.POST.get('hire_date'), position=position, address=address, date_of_birth=request.POST.get('dob'), img=request.FILES.get('imgg'), # Make sure you're using request.FILES for image files ) models.py class Employee(models.Model): img = models.ImageField(upload_to='pics') settings.py STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] MEDIA_ROOT = os.path.join(BASE_DIR, 'media') `# Define Media URL `MEDIA_URL = '/media/' urls.py urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) add_user.html <div class="contact-img"> <input type="file" id="imgg" name="imgg" class="form-control" accept="image/*"> list.html <img src="{{ datas.employee.img.url }}" alt="User Avatar" class="user-avatar"> "Why is this not being stored in the media/pics folder?" -
Azure App Service (oryx) does not use the set startup command
I want to deploy a Django DRF application to a azure App Service using artifacts (zip deployment) the artifact gets sucessfully uploaded from azure devops but the execution of the container fails since not all required packages are installed. Since my python packages are managed with pipenv I use a custom startup.sh script to start my App Service the file looks like this: python -m pip install --upgrade pip pip install pipenv pipenv install pipenv run python manage.py migrate pipenv run gunicorn --workers 2 --threads 4 --timeout 60 --access-logfile \ '-' --error-logfile '-' --bind=0.0.0.0:8000 \ --chdir=/home/site/wwwroot kez_backend.wsgi and I set it in my CD pipeline like this: but when I look at the logs of my App service the startup.sh script is not used and a custom one is create by oryx. Since oryx also creates a virtualenviroment and can't handle Pipfiles dependencys are missing. Application Logs: 2024-10-23T22:34:29.046573859Z _____ 2024-10-23T22:34:29.046642461Z / _ \ __________ _________ ____ 2024-10-23T22:34:29.046646861Z / /_\ \\___ / | \_ __ \_/ __ \ 2024-10-23T22:34:29.046650061Z / | \/ /| | /| | \/\ ___/ 2024-10-23T22:34:29.046653661Z \____|__ /_____ \____/ |__| \___ > 2024-10-23T22:34:29.046656961Z \/ \/ \/ 2024-10-23T22:34:29.046659861Z A P P S E R V I C E O … -
Why when I login in django, it throws error that username or password doesn't exists
I have this in terminal 'invalid_login': 'Please enter a correct %(username)s and password. Note that both fields may be case-sensitive.', 'inactive': 'This account is inactive.'} [ but, I have saved my username and password via browser, setting very common username and password that is impossible to write wrong may problem lay in form that is used during registration, or it happens because of registration form, or it happens because of models? My models from django.db import models from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) first_name = models.CharField(max_length=255, blank=True) last_name = models.CharField(max_length=255, blank=True) bio = models.CharField(max_length=255, blank=True) image = models.ImageField(blank=True) Forms: from django import forms from django.contrib.auth.models import User from users.models import Profile from django.contrib.auth.forms import AuthenticationForm, UserCreationForm class ProfileRegistrationForm(UserCreationForm): username = forms.CharField(required=True, max_length=30, widget=forms.TextInput(attrs={'placeholder': 'Enter username'})) email = forms.EmailField(required=True, widget=forms.EmailInput(attrs={'placeholder': 'Enter email'})) password1 = forms.CharField(widget=forms.PasswordInput(attrs={'placeholder': 'Enter password'}), label="Password") password2 = forms.CharField(widget=forms.PasswordInput(attrs={'placeholder': 'Confirm password'}), label="Password") class Meta: model = User fields = ['first_name', 'last_name','username', 'email', 'password1', 'password2'] def save(self, commit=True): user = super().save(commit=False) user.email = self.cleaned_data['email'] if commit: user.save() profile = Profile(user = user, first_name = self.cleaned_data['first_name'], last_name = self.cleaned_data['last_name']) if commit: profile.save() return profile def clean_username(self): username = self.cleaned_data['username'].lower() new = User.objects.filter(username=username) if new.count(): raise forms.ValidationError("User already … -
Optimal Approach for Training an AI Model to Correct Errors in Multipolygon Coordinates (Django REST Framework GIS)
I need to select an AI model and a Python library that would be the most optimal for training. I have coordinates represented as a Multipolygon field from the djangorestframework-gis library, and they have small errors within different ranges—approximately 0.75 to 1 meter. Additionally, I have correct coordinates for the same land plots. The model needs to learn to find the difference between the correct and incorrect data and, based on that, discover an algorithm to determine the error for future correction of the incorrect coordinates. -
Next.js Project Works in One Branch, API Requests Fail in Another
I'm working on a project using Next.js where I have two separate branches. The code works perfectly in one branch, but I'm encountering issues with API requests in the other branch. The code in both branches is almost identical, but in the non-working branch, the data I send is being accepted as empty on the backend, and I'm getting an error. Here’s the code I’m using: The data I’m sending to the API: sending data {title: 'test4', company: 'test', city: 'test2', country: 'tst', description: 'asdasda', ...} The error I receive: error: 'null value in column "title" of relation "core_exp..."' I'm only able to log into my project with part of the code, but I'm encountering issues when trying to update the form fields. Things I've tried to resolve the issue: Checked the .env files; they have the same values. Ensured that the library versions are the same. Verified that the API endpoints are correct. Checked that the Redux state is being updated properly. I compared most of my code and did not find any significant differences. Even on some pages, I observe that although I receive a 200 response from the backend, the changes I made are not being updated. … -
upload file in background process in django drf (get this error : Object of type TemporaryUploadedFile is not JSON serializable)
this is my create function: def create(self,request,*args,**kwargs): serializer = ArchiveSerializer( data = request.data, context = {"request":request} ) serializer.is_valid(raise_exception=True) filename=serializer.validated_data.pop('file') serializer.save() id = serializer.validated_data.get("id") save_file_in_background.delay(id,filename) return Response(serializer.data, status=status.HTTP_201_CREATED) and this is the tasks.py from celery import shared_task from django.core.files.base import ContentFile from .models import Archive @shared_task def save_file_in_background(id,filename): try: archive = Archive.objects.get(pk=id) if filename: archive.file.save(filename, ContentFile(filename)) archive.save() except Archive.DoesNotExist: pass but when try to add object and upload the file get this error: Object of type TemporaryUploadedFile is not JSON serializable except to upload file in background but get this error: "Object of type TemporaryUploadedFile is not JSON serializable" -
Django session doesn't work in Chrome Incognito mode
I have 3 views like this: def download_file(request, doc): if not request.session.get('is_authenticated'): return redirect(f"{reverse('pingfed_auth')}?next={request.get_full_path()}") return downloadfile(doc) def pingfed_auth(request): original_url = request.GET.get('next') or 'home' request.session['original_url'] = original_url return redirect('Some third party authentication') def redirect_pingfed_auth(request): if request.method == 'POST': request.session['is_authenticated'] = True request.session['username'] = get_username_from_saml(request.POST.get('SAMLResponse')) return redirect(request.session['original_url'] if 'original_url' in request.session else 'home') Where pingfed_auth start the authentication and redirect_pingfed_auth is the callback URL from that thrid-party authentication. However, the session doesn't work in chrome Incognito mode. I can't see any session from browser console, and I can't get redirect correctly. But I do see the session is stored properly in the database. Is that because Incognito mode block the session after redirect to third party site or something else? -
Django DB Foreign Key on_delete=CASCADE combined with null=True
What happens if a Django model contains both - on_delete=CASCADE and null=True: class MyModel(models.Model): ID = models.AutoField(primary_key=True) SomeInfo = models.BooleanField(default=False) SomeInfo2 = models.BooleanField(default=False) ID_FK1 = models.ForeignKey(OtherModel1, on_delete=models.CASCADE, null=True) ID_FK2 = models.ForeignKey(OtherModel1, on_delete=models.CASCADE, null=True) I see entries in the DB of MyModel with ID_FK2 being NULL which is not supposed to happen. -
Django-Nginx-React: How to fix ERR_CERT_COMMON_NAME_INVALID and Self-Signed Certificate Issues
I am working on a project using SimpleJWT tokens stored in HttpOnly cookies for authentication. The architecture involves a Django backend, an Nginx server, and a React+Vite frontend. Below is the configuration setup: I have created a self-signed Certificate Authority (CA). I issued two separate certificates signed by the same CA: one for the Nginx server (serving the Django backend) and one for the React+Vite app When I run my React+Vite app on Google Chrome and try to call the login API /api/auth/login/ of the Djagno backend, I receive the following error: POST https://172.x.x.x/api/auth/login/ net::ERR_CERT_COMMON_NAME_INVALID Additionally, I set up a Node.js project to test the same API by making Axios requests. In this case, I get the Error: self-signed certificate in certificate chain However, if I run the Node.js project with NODE_TLS_REJECT_UNAUTHORIZED='0', the API works fine, and I can see the HttpOnly cookies and the correct response from Django. It seems to be related to the self-signed certificates, but I’m unsure how to resolve this for Chrome to correctly accept the certificates and allow setting cookies. I’m also looking for a solution that doesn't involve disabling certificate validation with NODE_TLS_REJECT_UNAUTHORIZED=0. Questions: How can I resolve the ERR_CERT_COMMON_NAME_INVALID in Chrome? How … -
Django channels authentication with http post and use websockes after
I am working on a project where we have been using crud with a rest api, standard stuff. Now we want to switch to websockets as we want to have realtime updates. Think airline reservation calender. When someone clicks on a box in calender it needs to be blocked on every connected user. I see a lot of examples of people giving examples of authentication over the websocket. But I find creation of web-socket before login to a system wasted full. So ideally I would like to authenticate the user via JWT over an HTTP POST and get a token and if use it authenticated then create a websocket with the token that i get from JWT. Before I get into details. Is this the write way to do or should one create a websocket connetion right away and do the whole api stuff over websocket including the initial auth(username ,password stuff) . Thanks -
i got TypeError: UserManager.create_superuser() missing 1 required positional argument: 'username'
I want to create super user just from email and password so it should create super user without username. I am using custom user model and when i try to create superuser i got this error TypeError: UserManager.create_superuser() missing 1 required positional argument: 'username' This is my manager.py file from django.contrib.auth.base_user import BaseUserManager class UserManager(BaseUserManager): use_in_migrations = True def _create_user(self, email, password, **extra_fields): if not email: raise ValueError('The given email must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **extra_fields): extra_fields.setdefault('is_superuser', False) return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password, **extra_fields): extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_staff', True) if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True') return self._create_user(email, password, **extra_fields) This is my models.py class User(AbstractUser) """ Abstract User of django auth user model. """ uuid = models.UUIDField(default=uuid.uuid4, unique=True, null=False) email = models.EmailField(_("email address"), unique=True) middle_name = models.CharField(max_length=120, blank=True) image = models.ImageField(upload_to='user_profile/', blank=True) department = models.CharField(blank=True, choices=Department.choices, max_length=2) designation = models.CharField(max_length=120, blank=True) last_logout = models.DateTimeField(null=True) is_superuser = models.BooleanField(default=False) view = models.TextField(blank=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] -
Django Cloned Project does not give tables after migrating
I cloned a project that I want to modify and experiment with, and I have all the necessary credentials. However, I'm encountering issues while following the steps outlined in the ReadMe.md file since I cloned it: Clone the project. Create a .env file and add the following information: Database variables: DATABASE_NAME: Database name DATABASE_USER: Database user DATABASE_PASSWORD: Database password DATABASE_HOST: Database host DATABASE_PORT: Database port Authentication variables for the Telnyx API: Telnyx_v2_key: Telnyx API v2 key x-api-token: Telnyx API v1 token x-api-user: Telnyx API v2 user email Create a virtual environment: python -m venv ./venv Activate the environment: source venv_telnyx-invoicing/bin/activate.csh Install requirements: pip install -r requirements.txt Create a logs directory: mkdir logs Make migrations: python manage.py makemigrations Migrate: python manage.py migrate I’m currently stuck at the migration step. When I try to run python manage.py makemigrations, I receive the following error: Traceback (most recent call last): File "C:\Users\DominykasPavlijus\Desktop\Telnyx-Invoicing-1\venv\Lib\site-packages\django\db\backends\utils.py", line 105, in _execute return self.cursor.execute(sql, params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ psycopg2.errors.UndefinedTable: relation "Project_tenant" does not exist LINE 1: ...nant"."id", "Project_tenant"."billing_group" FROM "Project_t... My settings.py file appears to be configured correctly: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': os.getenv('DATABASE_NAME'), 'USER': os.getenv('DATABASE_USER'), 'PASSWORD': os.getenv('DATABASE_PASSWORD'), 'HOST': os.getenv('DATABASE_HOST'), 'PORT': os.getenv('DATABASE_PORT'), } } This is the model that …