Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Get values in real time in Django
I have made a sketch of how my project should look like. The user can communiticate with a virtual assistant over the web browser. The backend is Django. How to get values from the database in real time in Django? I've heard about Rest API, but I am not sure if that is the right thing to do. It is possible to use queries like website.com/?variable=value, but that is NOT what I want, because that slows down the time to "update" the user's screen and speakers. The frontend and backend is Django. The user should be able to communicate with Morpheus (there are other characters as well) when the "conversate" button is clicked. -
How can I display all fields from a Many-to-Many Model in Django Admin
I have the following Models: class ModelA(models.Model): some_field_A = models.CharField() some_other_field_A = models.CharField() class ModelB(models.Model): some_field_B = models.CharField() many_to_many_relation = models.ManyToManyField(ModelA) In admin.py I am using filter_horizontal to edit the ManyToManyField: class ModelB(admin.ModelAdmin): model = ModelB filter_horizontal = ('many_to_many_relation',) but it shows only some_field_A and I want it to show both fields from ModelA, because the entries in ModelA are unique depending on both fields and as you can see from the picture there are multiple entries with the same value (i.e. some_field_A = EUV) but they have different values for some_other_field_A: -
Celery 5.0.4 with Django 3.1.4 - OperationalError: Error 101 connecting to localhost:6379. Network is unreachable
I am having an issue with Django and Celery integration whereby it seems the settings for the RESULT_BACKEND and BROKER_URL keys are not being honored. I am running Django and Celery successfully in Docker with django-celery-beat without issue. Scheuduled tasks are running as expected. The issue I am having is when calling a @task function through a Django Signal. When this runs (triggered from Django Rest Framework); I get the following error: OperationalError: Error 101 connecting to localhost:6379. Network is unreachable. This would be expected because I dont run redis locally but within another container. Any ideas on why the configuration is not being used? I have confirmed that the environment variables are being loaded correctly and seen by both celery and Django. Compose File app-redis-prod: image: redis:alpine app-worker-prod: environment: - PLATFORM=prod - CERT_DIR=/run/certificates - DB_SSL_MODE=require - BROKER_URL=redis://rocx-redis-prod:6379 - RESULT_BACKEND=redis://rocx-redis-prod:6379 settings.py CELERY_BROKER_URL = os.environ.get('BROKER_URL', 'redis://localhost:6379') CELERY_RESULT_BACKEND = os.environ.get('RESULT_BACKEND', 'redis://localhost:6379') CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TIMEZONE = 'UTC' CELERY_ENABLE_UTC = True celery.py app = Celery('MYAPP') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print(f"Request {self.request!r}") Any ideas would be greatly appreciated! -
PyCharm complains template not found if template path is given in render function
PyCharm error inspection complains template not found error in django project if the template path is given as string in render function. It does not show error if the path is stored as variable before and that variable is passed in render. In any ways the site works correctly. Project Structure is configured correctly, TEMPLATE_DIRS, TEMPLATE_LOADERS in settings.py also configured. -
Why can't I clear or change field on inline formset, but I can only add, after clicking submit button?
I am new to Django and I am trying to create a view that uses a form with fields, another form with an image and file field, and a third inline formset form with two fields that uploads an image and video with the option to add more after submit, all in the same view. The problem I am currently experiencing is that I am able to add videos to my inline formset, but I am not able to clear or change those fields and I would like to know if it is my view that is causing it. Thanks! View: def edit(request, id): all_objects = get_object_or_404(Profile, id=id) ProfileFormset = inlineformset_factory(Profile, MultipleFileUpload, fields=('image', 'video',), extra=1) if request.method == 'POST': form1 = EditProfile(request.POST or None, instance=all_objects) form2 = ProfileUpdateForm(request.POST, request.FILES, instance=all_objects) formset = ProfileFormset(request.POST, request.FILES, instance=all_objects) if form1.is_valid() and form2.is_valid(): form1.save() form2.save() formset.save() return HttpResponseRedirect(".") form1 = EditProfile(instance=all_objects) form2 = ProfileUpdateForm(instance=all_objects) formset = ProfileFormset(instance=all_objects) context = { 'form1': form1, 'form2': form2, 'formset': formset } return render(request, 'accounts/edit.html', context)``` -
why does Materialize not work on Django native server?
I made a materialize registration form and it works outside of the Django project but as soon as I run it on the Django web-server it does not work. Additional info - I am using bootstrap elsewhere in the project, I don't know if that interferes with thought would let you know. If you need any more details please let me know, and this is only my 2nd ever question so if I do anything wrong please correct me :) -
I cannot access the admin page
when I started the local server for django framework project and wanted to enter the admin page, I got this error: **TypeError at /admin/ Cannot mix str and non-str arguments Request Method: GET Request URL: http://127.0.0.1:8000/admin/ Django Version: 3.1.5 Exception Type: TypeError Exception Value: Cannot mix str and non-str arguments Exception Location: C:\Program Files\Python39\lib\urllib\parse.py, line 122, in _coerce_args Python Executable: C:\Program Files\Python39\python.exe Python Version: 3.9.1** -
Foreign Key value assigning in Django
I am working on a project in Django where two custom build user model is used. Industry Employee Here every Industry user will entry some of their Employee's data, and later on Employee will verify and finish to create his account. my models.py: class myCustomeUser(AbstractUser): id = models.AutoField(primary_key=True) username = models.CharField(max_length=20, unique="True", blank=False) password = models.CharField(max_length=20, blank=False) is_Employee = models.BooleanField(default=False) is_Inspector = models.BooleanField(default=False) is_Industry = models.BooleanField(default=False) is_Admin = models.BooleanField(default=False) class Industry(models.Model): user = models.OneToOneField(myCustomeUser, on_delete=models.CASCADE, primary_key=True, related_name='industry_releted_user') name = models.CharField(max_length=200, blank=True) owner = models.CharField(max_length=200, blank=True) license = models.IntegerField(null=True, unique=True) industry_extrafield = models.TextField(blank=True) class Employee(models.Model): user = models.OneToOneField(myCustomeUser, on_delete=models.CASCADE, primary_key=True, related_name='employee_releted_user', blank=True) #industry = models.OneToOneField(Industry, on_delete=models.CASCADE, related_name='employee_releted_industry') industry = models.ForeignKey(Industry, on_delete=models.CASCADE) i_id = models.IntegerField(null=True, blank=False, unique=True) name = models.CharField(max_length=200, blank=False, null=True) gmail = models.EmailField(null=True, blank=False, unique=True) rank = models.CharField(max_length=20, blank=False, null=True) employee_varified = models.BooleanField(default=False, blank=True) Now I wrote the following code in views.py to create an Employee's entry by Industry user when the Industry user signed in from their account: @method_decorator(industry_required, name='dispatch') class industryDetails(DetailView): model = Industry template_name = 'app/industryDetails.html' def get_queryset(self): return Industry.objects.filter(user=self.request.user) def get_object(self): return get_object_or_404(Industry, user=self.request.user) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['inserted_text'] = "inserted text from EmployeeDetails of views.py" return context def employeeRegister_byIndustry(request): employeeRegister_dict={ 'insert_me' : "hello … -
How to Integrate Django WEB Application with Microsoft Azure For Authentication
I have developed a web application based on Django Framework, but i want my application to get authenticated by Azure Single Sign on, Please suggest the method or tutorials to achieve this -
How is the correct way to send a json serializer
I am practicing with serializers and I find an error because I want to send json from my queryset and the error it generates is context must be a dict rather than JsonResponse, I read the documentation and it says that setting the safe parameter to false allows sending any object serializer: This is my view: class TypeTaskListView(ListView): template_name = 'tasks/type_task.html' queryset = TypeTask.objects.all().order_by('-pk') def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) data = serializers.serialize('json', context['object_list']) return JsonResponse(data, safe=False) -
How to use multi-tenant functionality in django
Im trying to create a project that should have multi-tenancy ability but i want it a bit customized. So here is my whole schema I want an organization to signup whenever someone lands on my main site, they will be given a landing page (handled in view, no worries about this) eg: www.test.com (this will be my public url) Lets say company puts the name "abc" in form and signs up for my site. Now I want to create a tenant like abc.test.com (tenant url) and also database (postgres) should have an organization table in public schema and an abc table in private schema This is my main goal of the project. Now I have achieved most of it. DB schemas are handled and everything is done by using django-tenants package by tomturner. What I cant achieve is the functionality to differenciate automatically between my public and private urls. Like if someone hits "www.test.com" should land on my main site if someone hits "abc.test.com" should land on my private urls. I know I have to write a middleware for this (which is given in django-tenants) but still im not able to achieve it. By the way im following https://github.com/django-tenants/django-tenants/tree/master/examples/tenant_multi_types/tenant_multi_types_tutorial this … -
django.core.exceptions.ImproperlyConfigured: SpatiaLite requires SQLite to be configured to allow extension loading Django
I've tried this solution but I am getting Segmentation fault: 11 when migrating in Django. When I remove PYTHON_CONFIGURE_OPTS when installing Python, I am getting this error. django.core.exceptions.ImproperlyConfigured: SpatiaLite requires SQLite to be configured to allow extension loading -
Django-rest-auth urls Page not found
settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', # drf, rest_auth, allauth 'rest_framework', 'rest_framework.authtoken', 'rest_auth', 'allauth', 'allauth.account', 'allauth.socialaccount', 'rest_auth.registration', # apps 'board_subject_restful', ] REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly' ], 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.TokenAuthentication', ] } SITE_ID = 1 urls.py urlpatterns = [ path('admin/', admin.site.urls), path('api-auth/', include('rest_framework.urls')), path('', include('board_subject_restful.urls')), path('rest-auth/', include('rest_auth.urls')), path('rest-auth/registration/', include('rest_auth.registration.urls')), ] When attempting to connect to rest-auth/ url, the following error occurs. *api-auth/ rest-auth/registration/ The same error also occurred. enter image description here -
Handling JWT Authentication for Soft Deleted Users in Django Rest Framework
I'm trying to make a username available once a user deletes their account. By default the username is unique meaning the username won't be available even after the account is soft deleted. This is, by default, the setup that comes with django out of the box. class CustomUser(AbstractUser): username = models.CharField( _('username'), max_length=150, unique=True, help_text=_('Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.'), validators=[UnicodeUsernameValidator()], error_messages={ 'unique': _("A user with that username already exists."), }, ) is_active = models.BooleanField( _('active'), default=True, help_text=_( 'Designates whether this user should be treated as active. ' 'Unselect this instead of deleting accounts.' ), ) is_active is used here to mark a model as deleted. So that I can be able to take advantage of UniqueConstraint and add a condition, I have to drop the uniqueness of the username. class CustomUser(AbstractUser): username = models.CharField( _('username'), max_length=150, unique=False, help_text=_('Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.'), validators=[UnicodeUsernameValidator()], error_messages={ 'unique': _("A user with that username already exists."), }, ) is_active = models.BooleanField( _('active'), default=True, help_text=_( 'Designates whether this user should be treated as active. ' 'Unselect this instead of deleting accounts.' ), ) class Meta: constraints = [ models.UniqueConstraint( fields=['username'], name='active_username_constraint', condition=models.Q(is_active=True) ) ] This … -
how to add the existing google analytics account to my website in python django
Actually i have multiple users in my website. Everyone have google analytics account, how to fetch the details of the account only by clicking the login with google analytics button. -
Current path didn't match any of these
I'm trying to make it so that after a user register, it will redirect to the login page again but I got an error. Base.html: <button class="button"><a href="{% url 'login' %}?next={{ request.path }}"> LOGIN </a></button> <div> {% if user.is_authenticated %} Hello, {{ user.get_username }} <a href="{% url 'logout' %}?next={{ request.path }}">Log Out</a> {% else %} {% if 'login' in request.path %} <a href="{% url 'login' %}?next={{ '/' }}">Log In</a> {% endif %} {% endif %} </div> project/urls.py: from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('home/', include('drinks.urls')), path('accounts/', include('django.contrib.auth.urls')), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) settings.py: LOGIN_REDIRECT_URL = '/' STATIC_URL = '/static/' app/urls.py: from django.urls import path urlpatterns = [ path('register', registration_controller.index, name='register'), ] registration_controller.py: from django.core.mail import send_mail from django.http import HttpResponseRedirect from django.contrib.auth.models import User from django.shortcuts import render from django.conf import settings def index(request): msg = '' if request.method == 'POST': req = request.POST.dict() username = req['username'] password = req['password'] email = req['email'] try: user = User.objects.get(username=username) msg = 'Username or E-Mail is already Registered' except User.DoesNotExist: user = User.objects.create_user(username, email, password) user.save() msg = '' send_mail( 'Registration Successful', 'You are now an official member … -
Blocked Set-Cookie in development environment DRF SessionAuthentication + React
I have a very specific question that I haven't found within the many questions regarding this topic. I have a DRF + React web application which I recently changed from Token Authentication to Session Authentication for server side expiration. In production this works great, upon login I receive two Set-Cookies, a session id and a csrftoken. However, in my development environment, the Set-Cookies are blocked as This Set-Cookie was blocked because it had the 'SameSite=Lax' attribute but came from a cross-site response which was not the repsonse to a top-level navigation.. I tried changing the SameSite setting to none, in which case Chrome requires secure cookies, which I don't think is possible in my dev environment. I tried disabling Cookies without SameSite must be secure in chrome://flags. Listing localhost in CSRF_TRUSTED_ORIGINS solves the CSRF, but then the login issue remains. Although I don't think this is relevant, a lot of solutions here mention to add {withCredentials: true} to the requests, this however does not solve my issue as I do receive the Set-Cookie headers, they're just blocked... -
Django Superuser cant change user permission - change user type to staff
I am creating a Django Project with python 3.6 & Django V 2.2 . Now in the Django Admin panel ( Super User) cant convert a user type to staff . also it is not able to edit some user fields also. I have tried DB.Sqlite on my Local Host and PostgreSQL DB ( PG Admin on ) Apache2 Server. Kindly provide me any solution for my problem. I have been described all related codes below. also find the attached file for my problem. Django Admin shows success message. But No result on action (https://i.ibb.co/tDstxff/django-adminerror.png)Error after change user to staff My Project files are : models.py #ProApp/Models from django.db import models from django.contrib.auth.models import AbstractUser from django.contrib.auth.models import AbstractBaseUser, BaseUserManager from django.conf import settings from django.db.models import Sum from django.db.models.signals import pre_save, post_save from django.dispatch import receiver from datetime import date import datetime User = settings.AUTH_USER_MODEL #Create your models here class CustomUserManager(BaseUserManager): def _create_user(self, username, email, password=None, **extra_fields): """Create and save a User with the given email and password.""" if not email: raise ValueError('The given email must be set') email = self.normalize_email(email) user = self.model(email=email, username=username, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, username, password): if not username: raise ValueError('missing … -
Recreating a file-based POST request from Django-Rest-Framework test in curl
I have a test case using The test library from Django. In my test I have the following: class TestLoadCurve(TestCase): def setUp(self): self.client = Client() self.test_user = User.objects.create_user('test_user', 'a@b.com', 'test_user') self.client.login(username="test_user", password="test_user") def test_post_loadcurve_as_xlsx(self): response = self.client.post( reverse('loadcurves-list'), {'file': open("app/tests/loadcurve_files/loadcurve.xlsx", "rb"), "name": "testuploadloadcurve"}, ) self.assertEqual(response.status_code, status.HTTP_201_CREATED) And the (simplified) endpoint looks like this: class LoadCurveViewSet( mixins.CreateModelMixin, mixins.RetrieveModelMixin, mixins.ListModelMixin, viewsets.GenericViewSet ): ... def create(self, request, *args, **kwargs): up_file = request.FILES['file'] ... return Response(status.HTTP_201_CREATED) This test works. But I want to re-create the POST request that it makes using curl for some documentation. I have only made it so far: curl --user <myuser>:<mypass> -X POST -H --data-urlencode "payload={\"file\": $(cat app/tests/loadcurve_files/loadcurve.xlsx), \"name\": \"curlloadcurve\"}" http://localhost:5100/loadcurves/ Using the debugger I am able to stop the processing at the line up_file = request.FILES['file'], at which point I realize that both request.FILES and request.data are both totally empty. Am I not making the POST request correctly? I was following this answer Python version is 3.6.9 Django version is 3.1.3 -
Django - perform action on Profile while creating User
I was looking for solution for my problem here, but it didnt solve my problem. I want to create user's profile while their signing up. To signup I use CreateView class UserRegisterView(generic.CreateView): form_class = SignUpForm template_name = 'registration/register.html' success_url = reverse_lazy('login') #this method doesn't work and I get # `Profile.user" must be a "User" instance` def form_valid(self,form): Profile.objects.create(user=self.request.user) My Profile model looks like: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) #rest of fields like bio, social urls etc My main point is to automatically create user's profile when their create their account. What is the best way to solve this? -
Validations errors are not raising in clean function, Why?
Well I'm using the Userprofile form with the UpdateView and the errors are not raising even if my condition is true. What is the possibility of this unwanted behavior. forms.py. class UserProfileForm(forms.ModelForm): class Meta: model = UserProfile fields = ("avatar","username","first_name","last_name","age","gender") # fields = ("avatar",) Gender = ( ('one','Male'), ('two','Female'), ) widgets ={ 'age' : forms.TextInput(attrs={'class':'form-control'}), 'gender' : forms.Select(choices=Gender,attrs={'class': 'form-control'}), } # TRIED THIS AS WELL # def clean_age(self): # age = self.cleaned_data["age"] # print(age,'hm here') # if age < 18: # print(age,'hm here') # raise forms.ValidationError("You're age should be 18 plus") # return age def clean(self): cleaned_data = super().clean() age = cleaned_data.get('age') print('haye',age) if age < 18: print(age,'hm here') # raise forms.ValidationError("You're age should be 18 plus") age = "You're age should be 18 plus" self.add_error('age',age) raise forms.ValidationError("You're age should be 18 plus") Please tell me how can i fix this issue and raise errors on unvalid details. If more information is require then tell me in a comment section, I'll update my question with that information. -
foreign key mismatch - "app_employee" referencing "app_mycustomeuser"
I am working with a custom build user model in Django. My app name is app. my models.py: class myCustomeUser(AbstractUser): id = models.AutoField(primary_key=True) username = models.CharField(max_length=20, unique="True", blank=False) password = models.CharField(max_length=20, blank=False) is_Employee = models.BooleanField(default=False) is_Inspector = models.BooleanField(default=False) is_Industry = models.BooleanField(default=False) is_Admin = models.BooleanField(default=False) class Industry(models.Model): user = models.OneToOneField(myCustomeUser, on_delete=models.CASCADE, primary_key=True, related_name='industry_releted_user') name = models.CharField(max_length=200, blank=True) owner = models.CharField(max_length=200, blank=True) license = models.IntegerField(null=True, unique=True) industry_extrafield = models.TextField(blank=True) class Employee(models.Model): user = models.OneToOneField(myCustomeUser, on_delete=models.CASCADE, primary_key=True, related_name='employee_releted_user') industry = models.OneToOneField(Industry, on_delete=models.CASCADE, related_name='employee_releted_industry') i_id = models.IntegerField(null=True, blank=False, unique=True) name = models.CharField(max_length=200, blank=False, null=True) gmail = models.EmailField(null=True, blank=False, unique=True) rank = models.CharField(max_length=20, blank=False, null=True) employee_varified = models.BooleanField(default=False) class Inspector(models.Model): user = models.OneToOneField(myCustomeUser, on_delete=models.CASCADE, primary_key=True, related_name='inspector_releted_user') inspector_extrafield = models.TextField(blank=True) class Admin(models.Model): user = models.OneToOneField(myCustomeUser, on_delete=models.CASCADE, primary_key=True, related_name='admin_releted_user') admin_extrafield = models.TextField(blank=True) There was also a AUTH_USER_MODEL = 'app.myCustomeUser' in my settings.py. I have drop my full database, then I run makemigrations and it reported totally normal as No changes detected in app 'app'. But after that when I run migrate command it shows following error in my terminal: Operations to perform: Apply all migrations: app Running migrations: Applying contenttypes.0001_initial... OK Applying contenttypes.0002_remove_content_type_name... OK Applying auth.0001_initial... OK Applying auth.0002_alter_permission_name_max_length... OK Applying auth.0003_alter_user_email_max_length... OK Applying auth.0004_alter_user_username_opts... OK Applying … -
error 403 csrf token when using multiple post method with action attribute
i got a page how have multiple POST method , so i used the action attribute in ajax to recognize each of the post method , but when i tried to use it on the form how add a model into the database (client model), it said 403 error invalid or missing csrf token, but when i remove the action and let only the REQUEST.METHOD == 'POST', it work , so i didnt understand why the csrf token is not working when i use the action , i solved the problem by getting directly the values of input form but is better if i use the automated feature of django forms so their is my old code . ajax request: $(document).ready(function(){ var csrfToken = $("input[name=csrfmiddlewaretoken]").val(); //$("#alert-container").hide(); //console.log(csrfToken); $("#btn-submit").click(function() { var serializedData = $("#ClientForm").serialize(); console.log("hey hey clients!"); $.ajax({ url: $("ClientForm").data('url'), data :{serializedData,action: 'client'}, type: 'post', success: function(response) { console.log(response.client.name); console.log($("#ClientList")) } }) $("#ClientForm")[0].reset() }); }); html form : <form class="contact-form" id="ClientForm" data-url="{% url 'addclient' %}" method="POST"> {% csrf_token %} <div class="form-group"> <label for="name" class="sr-only">Name</label> {{ form.name }} </div> <div class="form-group"> <label for="email" class="sr-only">Email</label> {{ form.email }} </div> <div class="form-group"> <button type="button" id="btn-submit" class="btn btn-success btn-md">Add Client </client> </div> </form> View.py: def … -
How to make obj.save() without reversing object values in the db in django
I have recursive function and obj.save() is inside it. how to prevent the query from db at every iteration. -
error "ORDER BY not allowed in subqueries of compound statements". In dango while using Union fuction
"ORDER BY not allowed in subqueries of compound statements." in Django while using Icontains to join two querysets, problem comes when i join a third query set Such as slug with some special characters My Views; if len(query)>78: myposts = Blogpost.objects.none() else: post_title = Blogpost.objects.filter(title__icontains=query) posts_content = Blogpost.objects.filter(content__icontains=query) posts_overview= Blogpost.objects.filter(overview__icontains=query) myposts = post_title.union(posts_content, posts_overview) if myposts.count() == 0: messages.warning(request, "No search results found. Please enter again.") context = {'myposts': myposts,'query':query} return render(request, 'blog/search.html', context)```