Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Doubts about Django models primary_key and UniqueConstraint for composite primary key
Usually primary key means also unique (and more conditions like not null, etc.). If I have UniqueConstraint with 2 fields, including the primary key, I have 2 unique conditions (one because the primary key and another because the constraint). So that's is not the same than having a composite primary key with only one unique condition. For example, with this code: class MyClass (models.Model): field1=models.IntegerField(primary_key=True) field2=models.IntegerField() UniqueConstraint(fields=['field1', 'field2'], name='ConstraintName') Can I insert these values (1,1) and (1,2) since the field1 value is repeated and the primary key should be unique? In that case, what's the real meaning of primary key on Django models? Doesn't it imply a unique condition? Thanks a lot and regards. -
Adding frontend (Next.js/React) to django-oscar
I want to create an ecommerce app using django-oscar framework and self-build frontend. The docs explain how to change the website appearance but the base is build with bootstrap and standard django templates. To completely change storefront I just point at another folder in my project directory and create duplicated templates with the same name (for example if in framework there is product page then I need to create product_details.html template and code there). Now- I want to use Next.js (since React itself isn't great in terms of SEO) to build the storefront. What should be my approach? I don't know a lot of Next.js yet, in React I guess I would just generate .js file for every template (index.js for main page, product_details.js for products etc.). The REST API isn't a problem, there is django-oscar DRF version ready to use. -
Build failed when I build a docker container (Ubuntu 22.04 LTS), Error: Client.Timeout exceeded while awaiting headers
When I am building a docker container this error occurs: Get "https://registry-1.docker.io/v2/": net/http: request canceled while waiting for connection (Client.Timeout exceeded while awaiting headers) ERROR: Service 'migrate' failed to build : Build failed It's worked perfectly before, now I am getting this error. -
Django CRUD the data is not visible even though it is added in database
I am new to django and postgresql,I am currently doing CRUD and I have been able to make the create and insert page,I am able to ad the details as it appearas in the database but it isnt appearing in the read page here's the code in views.py def show_cat(request): showcategory = Categories.objects.filter(isactive=True) #print(showall) serializer = CategoriesSerializer(showcategory,many=True) #print(serializer.data) return render(request,'polls/show_cat.html',{"data":serializer.data}) def insert_cat(request): if request.method == "POST": insertcategory = {} insertcategory['category_name']=request.POST.get('category_name') insertcategory['category_description']=request.POST.get('category_description') form = CategoriesSerializer(data=insertcategory) if form.is_valid(): form.save() print("hkjk",form.data) messages.success(request,'Record Updated Successfully...!:)') return redirect('categories:show_cat') else: print(form.errors) return redirect('categories:show_cat') else: insertcategory = {} form = CategoriesSerializer(data=insertcategory) if form.is_valid(): print(form.errors) return render(request,'polls/insert_cat.html') urls.py from django.urls import path from categories import views from django.urls.conf import include from django.conf import settings from django.conf.urls.static import static urlpatterns=[ path('',views.show_cat,name="show_cat"), path('insert_cat/',views.insert_cat,name="insert_cat"), path('edit_cat/',views.edit_cat,name="edit_cat"), path('del_cat/',views.del_cat,name="del_cat") ] I have tried everything possible but I am not able to display the data on the 'read'page,please help -
Creating a game picking web app in django
I am having issues in writing code for my game picking app, I managed to get a model form working for admin game insertion to database (matchweek, game, result etc) but I am having trouble with writing a form and logic for user picks. I would like user to choose a week (I did this part) and then the form should have all games for that week, user and user picks. The logic is that you get one point for each game guessed right in a week, and than the user with most points gets 25 points for the summary point table. I am trying to get this gamepicking form working with formsets but I am not really sure anymore if my database logic is okay, I have a table called Bet containing user,game_id (FK) ,user pick. I am really stuck on this part. -
Why Django Commands are working well outside the virtual environment and doesn't work inside virtual environment
I recently installed Django on my machine, I installed virtualenv, virtualenv-wrapper and i even customized the ~/.bashrc file but; Some commands like "python3 manage.py startapp" give me an error when inside the virtual environment but do work outside the virtual environment, I wanna know why? why is it that django commands dont run in zsh shell but do run in bash shell? Note:: Am writing all the commands in the folder containing manage.py and the django local server is already running And please don't downvote my question because I really wanna know? My working terminal1 My working terminal2 -
In django, Redirection is not working after performing edit and delete
I am trying to perform Edit and Delete functionality in Django. After edit and delete it is not redirecting me to the URL provided in parameters. Rather it stays on current URL. I want to redirect to adduser page but it redirecting me to edituser and deleteuser after performing edit and delete.I am sharing code for edit function here. urls.py path('edituser/<uid>', views.edituser, name="edituser"), views.py def edituser(request, uid): if request.method == "POST": if request.POST.get('firstname') and request.POST.get('lastname'): saverecord = AddContact() saverecord.id = uid saverecord.f_name = request.POST.get('firstname') saverecord.l_name = request.POST.get('lastname') saverecord.save() viewRecords = AddContact.objects.filter(subscribe='subscribe') return HttpResponseRedirect(reverse("adduser"), {'adduser': viewRecords, args=(AddContact.pk)) else: viewRecords = AddContact.objects.filter(subscribe='subscribe') messages.error(request, "Error During Editing of User") return render(request, "adduser.html", {'adduser': viewRecords}) Adduser.html Edit and Delete button <a href="#userEditModal-{{forloop.counter}}" data-toggle="modal" class="btn btn-primary"><span class="fa fa-pencil"></span> Edit</a> <a href="{% url 'deleteuser' id=vr.id %}" class="btn btn-danger" data-target="success-modal-delete"><span class="fa fa-trash"></span> Delete</a> Edit model {% for vr in adduser.adduser.all %} <div class="modal fade" id="userEditModal-{{forloop.counter}}" tabindex="-1" role="dialog" aria-labelledby="largeModal" aria-hidden="true"> <div class="modal-dialog modal-lg modal-dialog-centered"> <div class="modal-content"> <form method="POST" action="{% url 'edituser' uid=vr.id %}" class="needs-validation" novalidate> {% csrf_token %} <div class="modal-header"> <h5 class="modal-title">Edit User Data</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <!--Form Start--> <div class="form-row"> <div class="form-group col-md-6"> <label for="FirstName">First Name<span style="color:#ff0000">*</span></label> <input type="text" … -
Why am I not able to reset the django admin password?
I run this command python manage.py changepassword <project_name> to change the password and once I set the password and retype it for the confirmation it just says your password didn't match even though the passwords were exactly the same. I tried many times and still couldn't reset it. what is the problem exactly and the solution to it?enter image description here -
Add filesize validation for django form file upload
I am using django for file upload, it accepts excelfile as external_id_file and parse in def clean_external_id_file class UserGroupCreateForm(forms.Form): class Meta: model = LineUserGroup fields = ("group_name", "is_selected_all_user") def clean_external_id_file(self): external_id_file = self.cleaned_data.get('external_id_file') if external_id_file is not None: try: external_id_dict = get_data(external_id_file) except Exception as e: self.add_error( "external_id_file", f"please check if this is correct excel file") return try: sheets = list(external_id_dict.keys()) data = external_id_dict.get(sheets[0])[1:] if len(sheets) > 0: external_id_list = [str(x[1]) for x in data] except: self.add_error( "external_id_file", f"not correct excel file") return However in this case, I want to limit the file size for example 2MB. I have some basic question. I can add some validation in this form ?(I prefer this way) or I should make something in javascript? Any help appreciated. -
Django login problems
I can register new user. But after logout, I cannot login again .It shows user does not exist. But when I checked admin panel I get hashed password. forms.py class UserLoginForm(forms.Form): email = forms.EmailField() password = forms.CharField(widget=forms.PasswordInput) def clean(self, *args, **kwargs): email = self.cleaned_data.get("email") password = self.cleaned_data.get("password") if email and password: user = authenticate(email=email, password=password) if not user: raise forms.ValidationError("User Does Not Exist.") if not user.check_password(password): raise forms.ValidationError("Password Does not Match.") if not user.is_active: raise forms.ValidationError("User is not Active.") return super(UserLoginForm, self).clean(*args, **kwargs) views.py def login_view(request): # users will login with their Email & Password if request.user.is_authenticated: return redirect("/") else: title = "Login" form = UserLoginForm(request.POST or None) if form.is_valid(): email = form.cleaned_data.get("email") password = form.cleaned_data.get("password") # authenticates with Email & Password user = authenticate(email=email, password=password) login(request, user) return redirect("/") context = {"form": form, "title": title } return render(request, "accounts/login.html", context) -
How to update data in Database when status_choise removed from models
In models I had status choices for status = models.CharField(max_length=50, default="FIELD_1", choices=STATUS) like this: STATUS = ( ('FIELD_1', _('value FIELD_1')), ('FIELD_2', _('value FIELD_2')), ('FIELD_3', _('value FIELD_3')), ('FIELD_4', _('value FIELD_4')), ('FIELD_5', _('value FIELD_5')), ) I have removed ('FIELD_5', _('value FIELD_5')), and ('FIELD_4', _('value FIELD_4')), from choices. How can I update database status value in Database to FIELD_1 when it was FIELD_5 or FIELD_4 -
405 (Method Not Allowed) DJANGO REST
Minha aplicação roda perfeitamente localhost, mas quando eu subo para o servidor, que é um Windows server, o método PUT, POST, simplesmente para de funcionar e acusa '405 (Method Not Allowed)', entre várias tentativas, mexendo no webconfig, uma hora consegui fazer um POST, mas já mexi tanto que não sei mais como voltar... meu webconfig webconfig -
How to convert beforefilter from cakephp to Django?
I am moving website created in cakephp to Django rest framework. In cakephp, every controller has parent class as AppController. There is beforefilter in AppController which is checking authentication/permission and depending on permission other function is being called to set value of public variable present in that class. class AppController extends Controller { public temp1 = ''; public temp2 = array(); public function beforeFilter(){ } } I want to create it using Django Rest Framework and send json response to the react app. As far as login authentication is concerned, I used simple-jwt. class index(APIView): def get(self,request): data = {} return JsonResponse(data) Do I need to implement AppController in django separately, create function beforefilter() and call beforefilter() every time I create any api and What about checking whether user is authenticated or not ? Is there any simpler method to apply beforefilter? -
My unit tests don't work with multiple databases
I'm working on a project where there are two databases, and I need to create unit tests for my models and etc. these are my databases: DATABASES = { 'default': {}, 'auth_db': { 'NAME': 'name' 'ENGINE': 'django.db.backends.postgresql', 'USER': 'user' 'PASSWORD': 'password' 'PORT': 5432 'HOST': 'localhost }, 'base': { 'NAME': 'name, 'ENGINE': 'django.db.backends.postgresql', 'USER': 'user', 'PASSWORD': 'password', 'PORT': 5432, 'HOST': 'locahost, } } At first I'm creating only the unit tests of the models from django.test import TestCase from base.models import User class UserModelTest(TestCase): @classmethod def setUpTestData(cls): # Set up non-modified objects used by all test methods User.objects.create(first_name='Big', last_name='Bob') def test_first_name_label(self): author = User.objects.get(id=1) field_label = author._meta.get_field('first_name').verbose_name self.assertEqual(field_label, 'first name') But when I do sudo python3 manage.py test, it returns me the error: AssertionError: Database queries to 'base' are not allowed in this test. Add 'base' to base.tests.test_models.UserModelTest.databases to ensure proper test isolation and silence this failure. When I was working with just one database, it wasn't giving a problem, however, when I separated it, I had this problem. I've looked everywhere and haven't found a solution. -
Disable email for bad request in django but still log to file
Someone recently tried to hack our Django server. They sent a lot of bad requests which triggered a lot of emails. How can we disable the emails but still log the bad requests? We have this the block below for DisallowedHosts so I expect something similar for bad requests. LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'null': { 'class': 'logging.NullHandler', }, }, 'loggers': { "django.security.DisallowedHost": { "handlers": ["null"], "propagate": False, }, }, } -
Set Django send_mail backend host with Gmail
I have been trying search many files to set send_mail backend with Gmail host. Here is my settings: EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend" EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = 'myemail' EMAIL_HOST_PASSWORD = 'mypassword' DEFAULT_FROM_EMAIL = 'myemail' It doesn't work...I find someone mentioned to set Gmail Account with "less secure app". So I tried, but it didn't work. On google website, it says:"To help keep your account secure, from May 30, 2022, Google no longer supports the use of third-party apps or devices which ask you to sign in to your Google Account using only your username and password." (refer to: https://support.google.com/accounts/answer/6010255?hl=en). Regardless of all, I still tried to use python3 manage.py shell, and got the error: SMTPAuthenticationError: (535, b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8 https://support.google.com/mail/?p=BadCredentials jj4-20020a170903048400b0016a2b68823esm9889669plb.141 - gsmtp') Could anyone help me, thanks a lot! -
How to use GROUP BY in Django without using values()?
I am trying to GROUP BY with Django ORM: sub = ( Participant.objects .values('category') .annotate( average=Avg(F('price')), ) ) It works as expected BUT the queryset does not contains instances of the model anymore. If contains dicts because values() has been called. How can do a group by query and get a regular queryset (with model instances) ? -
Django Admin - Change Model Page - URLs with UUID instead of ID
I have a BaseModel class that all my models inherit with a uuid like so: class BaseModel(models.Model): ''' Extension of base model class ''' uuid = models.UUIDField(unique=True, default=uuid4, editable=False) ... How can I change the django admin behavior such that I can access the change page for an instance using the object UUID instead of the ID? Presently: .../admin/my_app/my_model/7/change/ Preferred: .../admin/my_app/my_model/b6a98f1d-6b26-4399-8d68-62ec1ce12c41/change/ -
Django not connecting to PlanetScale , SSL error
Trying to use planetscale for my db platform for a Django app that i am building. However i'm running into some errors django.db.utils.OperationalError: (2026, "SSL connection error: no valid certificates were found, CAFile='*************', CAPath=''. One or more of the parameters passed to the function was invalid. Error 2148074333/0x8009035D") The configuration was copied straight from planetscale DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': env('DB_NAME'), 'HOST': env('DB_HOST'), 'PORT': env('DB_PORT'), 'USER': env('DB_USER'), 'PASSWORD': env('DB_PASSWORD'), 'OPTIONS': {'ssl': {'ca': env('MYSQL_ATTR_SSL_CA')}} } } -
Django REST framework authentication does not work with Class based view
I'm using DRF (3.12.4) with SimpleJWT for authentication. It is working with function based view but not working with Class based view. For Class based view, there is no effect and the request passed without authentication. Here is my function based view @api_view(['POST']) @permission_classes([IsAuthenticated]) def test_function_view(request): return JsonResponse({"message": "test ok"}, safe=False, status=200) Here is my class based view class TestClassView(APIView): authentication_classes = [JWTAuthentication] permission_classes = [IsAuthenticated] def post(request): return JsonResponse({"message": "post ok"}, safe=False, status=200) def get(request): return JsonResponse({"message": "get ok"}, safe=False, status=200) Settings REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework_simplejwt.authentication.JWTAuthentication', ], } URLs path('api/v1/agents/performancetest/testclass', TestClassView.post), path('api/v1/agents/performancetest/testfunction', test_function_view), In class based view, the authentication made no effect, so when send GET request without authentication, it passed, and for POST request, it got CRSF error because of no authentication. Forbidden (CSRF cookie not set.): /api/v1/agents/performancetest/testclass HTTP POST /api/v1/agents/performancetest/testclass 403 [0.02, 127.0.0.1:59664] HTTP GET /api/v1/agents/performancetest/testclass 200 [0.00, 127.0.0.1:59664] Is there anything I missed here or any clue? Thank you. -
How to convert a Django UUID to integer within a queryset annotate?
I'm trying to convert UUIDs to integers within an annotate. So like: Item.objects.values_list('pk', flat=True).annotate(int_of_pk=int('pk')) which throws error: ValueError: invalid literal for int() with base 10: 'pk' or like: from django.db.models import IntegerField from django.db.models.functions import Cast Item.objects.values_list('pk', flat=True).annotate( int_of_pk=Cast('pk', output_field=IntegerField()) ) which throws error: File "/path/ve/lib/python3.7/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.CannotCoerce: cannot cast type uuid to integer LINE 1: ...em"."uuid", ("item"."uuid")::integer ... ^ Any ideas pop out at you? Your time is greatly appreciated! -
Pycharm unable to resolve Django reference
I pulled a project from my GitHub to my laptop. After I install my requirements.txt file Pycharm is giving me an error "unresolved reference 'contrib/middleware'" in settings.py despite having Django installed and support enabled. The project is working in Pycharm, I'm just getting my text highlighted and imports aren't working. I've deleted the virtual environment, deleted the project, and pulled it again and I'm getting the same errors -
What would be the Python cmd to fetch the logged in user 's full name on windows and MAC
I am using PowerShell and executing the below command to find user details through AD. Get-ADUser -Identity username -Server domain I need to find alternate for the above command in python which can be executed to find the first name of the user and lastname. I am using windows domain and MAC . Help will be really appreciated -
Django Rest API JWT authentication - No active account found with the given credentials
I have a question concerning the Django Rest Framework JWT auth protocol. This issue has been coming up a lot but no suggested solution has worked for me yet. When I try this command: http post http://127.0.0.1:8000/api/token/ username=username password=password or curl -X POST -d "username=username&password=password" http://localhost:8000/api/token/ to obtain the access/refresh tokens as suggested in many tutorials, I get this error: { "detail": "No active account found with the given credentials" } I have created a superuser My users are all is_active = True My passwords are hashed in the database I have AUTH_USER_MODEL = 'my_app_name.User' in settings.py The username/password are 100% correct. Here is my User model: class User(LifecycleModelMixin, AbstractUser): public_id = models.UUIDField(unique=True, default=uuid.uuid4, editable=False) company_name = models.CharField(max_length=100, blank=True) job_title = models.CharField(max_length=30, blank=True) street_address = models.CharField(max_length=100, blank=True) street_address2 = models.CharField( verbose_name="Street address 2", max_length=100, blank=True ) city = models.CharField(max_length=100, blank=True) state = models.CharField(max_length=50, blank=True) zip = models.CharField(max_length=50, blank=True) phone_number = PhoneNumberField(blank=True) is_active = models.BooleanField(default=True, null=True, blank=True) email_subscribed = models.BooleanField(default=True, null=True, blank=True) manager = models.ForeignKey( "self", null=True, blank=True, on_delete=models.SET_NULL, related_name="sub_users", ) country = CountryField(blank_label="(select country)", blank=True) contact_info = JSONField("ContactInfo", default=contact_default) My serializer: class UserSerializer(serializers.ModelSerializer): def create(self, validated_data): user = super().create(validated_data) user.set_password(validated_data['password']) user.save() return user class Meta: model = User fields = … -
Django webpack_loader: `Regex` Undefined?
I've updated a Django app to Python 3.9 and Django 4.0, and I'm getting an error on launch: TypeError: expected string or bytes-like object I tracked it down to this function in python3.9/site-packages/webpack_loader/loader.py: def filter_chunks(self, chunks): filtered_chunks = [] for chunk in chunks: ignore = any(regex.match(chunk) for regex in self.config['ignores']) if not ignore: filtered_chunks.append(chunk) return filtered_chunks On the line ignore = any(regex.match(chunk)..., regex is undefined. I ran brew upgrade python, but Homebrew said: Warning: python 3.9.13_1 already installed What am I missing?