Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Issue extending django.contrib.auth User model. Django + legacy MySQL
I'm unclear which Django-generated default-model I should keep after extending the AuthUser model with a custom "NewUser" model I'll first explain the status and at the bottom, I'll ask the question. My installed apps are: 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', After syncing the MySQL database to the Django project, Django added the default user, permission, sessions, etc. tables to the database. Then I ran "inspectdb > models.py" to get the models pasted into my model.py. Here only show the Django generated ones: class AuthGroup(models.Model): name = models.CharField(unique=True, max_length=150) class Meta: managed = True db_table = 'auth_group' class AuthGroupPermissions(models.Model): id = models.BigAutoField(primary_key=True) group = models.ForeignKey('AuthGroup', models.DO_NOTHING) permission = models.ForeignKey('AuthPermission', models.DO_NOTHING) class Meta: managed = True db_table = 'auth_group_permissions' unique_together = (('group', 'permission'),) class AuthPermission(models.Model): name = models.CharField(max_length=255) content_type = models.ForeignKey('DjangoContentType', models.DO_NOTHING) codename = models.CharField(max_length=100) class Meta: managed = True db_table = 'auth_permission' unique_together = (('content_type', 'codename'),) class AuthUser(models.Model): password = models.CharField(max_length=128) last_login = models.DateTimeField(blank=True, null=True) is_superuser = models.IntegerField() username = models.CharField(unique=True, max_length=150) first_name = models.CharField(max_length=150) last_name = models.CharField(max_length=150) email = models.CharField(max_length=254) is_staff = models.IntegerField() is_active = models.IntegerField() date_joined = models.DateTimeField() class Meta: managed = True db_table = 'auth_user' class AuthUserGroups(models.Model): id = models.BigAutoField(primary_key=True) user = models.ForeignKey('AuthUser', models.DO_NOTHING) group = … -
Got an error creating the test database: could not read file "base/1/1249": I/O error
When i try sudo docker-compose run python python manage.py test I've got this Eror: Starting bstr_sa_backend_sa_db_1 ... done Creating test database for alias 'default'... Got an error creating the test database: could not read file "base/1/1249": I/O error -
Django 4 with drf_spectacular Swagger does not execute POST
I have the following classes using the django-restframework and drf-spectacular. I can execute POST when I am logged in and through the drf default routes, but not using the swagger-ui routes. I can go to this url: http:/example.com/api/schema/swagger-ui/#/organism/organism_create But when I click the Execute button, nothing really happens. I expect the CURL command to be shown etc. Also, I don't see a response at the server backend. Contrary to the GET method. Here, the server prints: 11/Feb/2022 22:34:02] "GET /api/organism/ HTTP/1.1" 200 275 I did go to login, and provided my username and password first. What is wrong with this setup? models.py class Organism(models.Model): short_label = models.CharField(max_length=100) long_label = models.CharField(max_length=100) genus = models.CharField(max_length=100) def __str__(self): return self.long_label serializers.py class OrganismSerializer(serializers.ModelSerializer): class Meta: model = models.Organism fields = ('__all__') views.py class ReadOnly(BasePermission): def has_permission(self, request, view): return request.method in SAFE_METHODS class OrganismViewset(viewsets.ModelViewSet): queryset = models.Organism.objects.all() serializer_class = serializers.OrganismSerializer parser_classes = [parsers.MultiPartParser, parsers.FormParser] http_method_names = ['get', 'post', 'patch', 'delete'] # Permissions permission_classes = [IsAuthenticated|ReadOnly] def get(self, request, format=None): content = { 'status': 'request was permitted' } return Response(content) urls.py router = SimpleRouter() router.register('organism', views.OrganismViewset) settings.py I tried different settings. Using the BasicAuth.., I get a prompt asking for username and password, but … -
"ValueError: source code string cannot contain null bytes" when trying to run a Django server
I cloned a project from github that works on another computer. When I run the server with the command "python3 manage.py runserver" I get the following error: File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 846, in exec_module File "<frozen importlib._bootstrap_external>", line 983, in get_code File "<frozen importlib._bootstrap_external>", line 913, in source_to_code File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed ValueError: source code string cannot contain null bytes I tried to delete bootstrap4 but the problem persists... Thanks in advance. -
Django API IntegrityError insert or update on table
This is my error , i am using postgresql , what is problem ? insert or update on table "Auth_user_org_user_id" violates foreign key constraint "Auth_user_org_user_id_user_id_17f17996_fk_auth_user_id" DETAIL: Key (user_id)=(1) is not present in table "auth_user". This is models class User(models.Model): FirstName = models.CharField(blank=True,null=True,max_length=100) LastName = models.CharField(blank=True,null=True,max_length=100) mail = models.CharField(blank=True,null=True,max_length=100) def __str__(self): return str(self.FirstName) class Organization(models.Model): id = models.AutoField(primary_key=True,blank=True) name = models.CharField(max_length=100) type = models.CharField(max_length=20) def __str__(self): return str(self.id) class User_org(models.Model): id = models.AutoField(primary_key=True,blank=True) user_id = models.ManyToManyField(User,related_name='UserInfo') organization_id = models.ForeignKey(Organization,related_name='orginfo',on_delete=models.CASCADE) and this is views.py class UserSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserForSerializer class OrgSet(viewsets.ModelViewSet): queryset = Organization.objects.all() serializer_class = OrganizationSerializer #test class User_and_Org_Set(viewsets.ModelViewSet): queryset = User_org.objects.all() serializer_class = User_and_org_Serializer what is problem and how to slove this ? i can insert models fields , firstname ,lastname and mail , also can insert organization fileds name and type , but when i try to insert User_org fields which is foreignkey there is error. -
Trouble with using datepicker in edit form
I have trouble with edit data in django project. Everything is almost ok :) , but if I'm trying edit data my form get all data from database exept date field. I found solution as below and I see datapicker on my edit form but I have to fill in data to this field. Every data in edit form are filled in exept this one. Datapicker for adding records works good. I'm using the same form to add and edit. My forms.py is listed below: from django import forms from .models import Expens, Category class DateInput(forms.DateInput): input_type = 'date' class ExpensForm(forms.ModelForm): class Meta: model = Expens fields = ('name', 'date', 'category', 'value', 'add_description', 'scan') labels = { 'name': 'Nawa wydatku:', 'date': 'Data wydatku:', 'category': 'Kategoria wydatku:', 'value': 'Kwota wydatku:', 'add_description': 'Dodatkowy opis:', 'scan': 'Skan paragonu:', } widgets ={ 'name': forms.TextInput(attrs={'class': 'form-control'}), 'date': DateInput(attrs={'class': 'form-control'}), 'category': forms.Select(attrs={'class': 'form-control'}), 'value': forms.NumberInput(attrs={'class': 'form-control'}), 'add_description': forms.TextInput(attrs={'class': 'form-control'}), 'scan':(), } My html template to this forms is listed below: {% extends 'expenses/index.html' %} {% block tytul %} DATABASE FORMS {% endblock %} {% load bootstrap5 %} {{ form.media }} {% block strona %} {% if new %} <h5>Add record</h5> {% else %} <h5>Edit record</h5> {% … -
Django How to use Postgresql's INSERT INTO ... WHERE conditional insert functionality?
Postgresql has a nice syntax for conditionally inserting: INSERT INTO child (name, parent_id) SELECT :name, :parent_id WHERE EXISTS ( SELECT 1 FROM parent WHERE id = :parent_id AND parent.user_id = :user_id ) In the above example, nothing would be inserted into the child unless the given :user_id was the owner of the parent row. Is it possible to simulate this kind of insert in Django? -
Django prevent users from spamming a view (add to cart)
I have a view (add to cart) that rely on sessions to add or update an item in the cart, And I am using the javascript fetch API so that the hole process is asynchronous, it works fine, but I've noticed that the user can spam the add to cart button/form so what's the best way the prevent that ?, this is my code: def API_View(request): article_slug = request.POST.get('article_slug') if article_slug: try: article = Article.objects.get(slug = article_slug) except Article.DoesNotExist: raise Http404('article does not exist ') my_cart = request.session.get('my_cart',None) if my_cart: if str(article.slug) in my_cart: item = my_cart[str(article.slug)] item['quantity'] += 1 item['status'] = 'updated' request.session.modified = True print(' quantity updated') print(my_cart) else : my_cart[str(article.slug)] ={ 'slug' :str(article.slug), 'quantity' :1, 'status' :'Added' } request.session.modified = True print('new item in cart ') print(my_cart) else: request.session['my_cart'] = { str(article.slug):{ 'slug' :str(article.slug), 'quantity' :1, 'status' :'Added' } } my_cart = request.session['my_cart'] print('first to cart') print(my_cart) return JsonResponse(my_cart,safe=False) -
Are there limits on the reasonable amount of HTML that browsers can handle before they start to slow down in regards to page rendering?
I am working to troubleshoot an issue with my Django formsets implementation. After working with a consultant for a couple hours today...we think it might be related to the amount of HTML that gets generated based on the number of records the formset is processing. Based on 18,000 lines of HTML...the page takes about 15 seconds to load. The same page with fewer records loads much more quickly. We've explored the query thing...and have exhaustively looked at performance metrics on the server side and can't seen anything glaringly sticking out that would be contributing to the perceived slow rendering of the page in the browser. Has anyone else come to this conclusion with their formsets? If so, what potential alternatives are there to resolving the slow page rendering issue? Formsets are great...but it would seem that the browsers have trouble rendering the records when they hit a certain amount? Thanks in advance for any thoughts. -
dict object has no attribute
In frontend I use vue js , using axios I sent data to backend.But after clicking submit button I got this error: dict object has no attribute 'invoice_products'. From frontend using axios: this.$http.post('http://127.0.0.1:8000/api/createTest', { invoice_products: this.invoice_products }) This is my json input data {"invoice_products":[{"name":"fgf","price":"56"}]} views.py: @api_view(['POST']) def createTest(request): serializer = TestSerializer(data=request.data.invoice_products) if serializer.is_valid(): serializer.save() return Response(serializer.data) Error: dict object has no attribute 'invoice_products' -
Django project deployment on an offline pc, locally, we don't want to go online
I have a Django project. we cannot go online, is there any way to deploy the project in a client computer just for the client to use there on his pc? no need to go online! user needs to type an address in browser to get the starting page of some other easy path! is it possible? or is there any other way to solve this problem? -
NoReverseMatch at reset_password_complete: Django PasswordResetConfirmView
I am using Django's default password reset views and forms to send an email to the user for them to reset their password via a link in the email. I have most of the development complete but am stuck on one issue. When I receive the email from the local host, I click the link, enter my new password 2 times, hit 'submit' and get this error: Error Message. Below is my code. urls.py """defines URL patterns for users""" from django.urls import path, include, reverse_lazy from django.contrib.auth import views as auth_views from . import views app_name = 'users' urlpatterns = [ # include all default auth urls path('', include('django.contrib.auth.urls')), path('register/', views.register, name='register'), path( 'reset_password/', auth_views.PasswordResetView.as_view( template_name='registration/password_reset.html', success_url=reverse_lazy('users:password_reset_done') ) , name='reset_password' ), path( 'reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view( template_name='registration/password_reset_form.html', success_url=reverse_lazy('users:password_reset_complete') ), name='password_reset_confirm' ), path( 'password_reset_done/', auth_views.PasswordResetDoneView.as_view( template_name="registration/password_reset_sent.html"), name='password_reset_done' ), path( 'password_reset_complete/', auth_views.PasswordResetCompleteView.as_view( template_name='registration/password_reset_done.html'), name='password_reset_complete' ), path('forgot_username/', views.forgot_username, name="forgot_username"), path('username_retrieval/', views.username_retrieval, name="username_retrieval"), ] As you can see, I am using the namespace 'users' in the success_url variable, however, it seems to work on the reset_password path, but it does not seem to work on the reset/<uidb64>/<token> path. One thing to be aware of is that I have a custom user model in my application. Would … -
(Html,css, JavaScript, python,django) What should I learn to be a full stack developer 2022? Should I follow my current roadmap? [closed]
Currently I m confused which roadmap should I follow to be a full stack web developer. Should I learn mern stack or html,css, JavaScript python Django? Which roadmap is better and high demand for future? Or should I learn php for back end development? -
Django add multiple Users to lobby model
I want to add Users to my players field in the lobby but i dont know how. Every user should be in just one lobby. User Model class GeoUser(AbstractUser): user_score = models.IntegerField(default=0) email = models.EmailField(unique=True) Lobby Model class Lobby(models.Model): lobby_code = models.CharField( max_length=18, unique=True) players = # here i want to add multiple users that should be in the lobby Thanks in advance -
Django regex string validation for emails including international characters
To only allow for international characters in the local part, I am trying to extend the EmailValidator class like this: class EmailValidator(_EmailValidator): """ This is meant to mirror the Django version but override the user_regex to allow for more unicode chars """ user_regex = _lazy_re_compile( r"^\w[a-zA-Z0-9èéàáâãäçêìíîñòóôöäüÖÄÜ\.\-_]", # too vague re.IGNORECASE) Obviously there are some holes in my regex string. Ideally this would adhere to RFC 5322 standards. I have some test emails that I need this to pass: piny@tineapples.com - valid tinä@turner.com - valid pinéapplé@lol.com - valid pinéa@pplé@lol.com - invalid kînda.prétty.ãmazonian1539@pastasauce.co - valid -
how to break the paragraph lines on a live production using django template tag filters?
I have searched for it but couldn't find an example for live server so that's why posting. I am working on a template in django in which I need to break the paragraph lines according to the formate that I have applied in django admin panel. let say I have written the same way as it is here : a paragraph a paragraph example a paragraph a paragraph example a paragraph a paragraph example a paragraph a paragraph example a paragraph a paragraph example so I have applied linebreaks template filter on it and it is working on the development server. When I push the source code on live production, the whole paragraph appears as a single line instead of being displayed with tags. Example on live server: a paragraph a paragraph example<br>a paragraph a paragraph example a paragraph a paragraph example<br>a paragraph a paragraph example a paragraph a paragraph example So I would love to get help from you guys. thanks in advance. -
how to make an Api to create unique URL's for a Form View (Like Googles Forms uniques URLS)
I'm new in Django Rest Framework and Django. I'm trying to make a service Api. The bussiness rule is "If post a field Email, this service return me a unique URL to go to a survey view". But, I'm only can make services with username and Password with AuthToken and only views with static url. Can you Help me?. Thanks in advance! -
How to make some fields optional in Django ORM
I've coded a function that signs up a user. In my sterilizer the name field is optional but whenever I try to create a user without giving a name, I just face KeyError: 'name'. what should I do to make this code work? def post(self, request): if request.user.is_anonymous: data = RegisterationSerializer(data=request.data) if data.is_valid(): User.objects.create_user(email=data.validated_data['email'], username=data.validated_data['username'], password=data.validated_data['password'], name=data.validated_data['name']) return Response({ "message": f'{data.validated_data["email"]} account was created successfully' }, status=status.HTTP_201_CREATED) else: return Response(data.errors, status=status.HTTP_400_BAD_REQUEST) else: return Response({ "message": "You already authorized" }, status=status.HTTP_400_BAD_REQUEST) -
django-cascading-dropdown-widget - doesn't give me an error but both my dropdown are filled and nothing is cascaded based on parent selection
I don't want to explicitly write an AJAX code to implement cascading dropdown for my django app. While researching alternate methods I came across this django-cascading-dropdown-widget package. I tried following the documentation but the cascade does not work. It doesn't give me an error but both my dropdown are filled and nothing is cascaded based on parent selection. Has anyone tried this packing and how? https://pypi.org/project/django-cascading-dropdown-widget/ -
Clear field in M2M relationship
I have a model which has a field with reference to the same model: class Department(models.Model): title = models.CharField(max_length=30) description = models.CharField(max_length=100, blank=True, verbose_name='Description') subsidiary = models.ManyToManyField('self',null=True,blank=True, symmetrical=False, related_name='subsidiary_name') superior = models.ForeignKey('self',null=True,blank=True, related_name='superior_name', on_delete = models.SET_NULL) status = models.BooleanField(default=True) I have also save method overriding: def save(self, *args, **kwargs): if self.status: # do smth else: self.subsidiary.clear() # save the instance super().save(*args, **kwargs) I just want to clear my field subsidiary , but my solution doesn't work. Could you help me? -
Page not found at /about/. The current path, about/, did not match any of these. Why can't django follow my URL path?
I'm sure this question has been asked many times before but I'm sure I'm doing everything exactly as the tutorial says and it's still not working. I can access the home page just fine but not the about page. Here is screenshot of the error: https://i.stack.imgur.com/oFNAJ.png I have the URL path in my .urls file (file below) from django.urls import path from . import views urlpatterns = [ path('', views.homepage, name='main-home'), path('about/', views.about, name='main-about'), ] And in the .urls file I have referenced the .views file (below) from django.shortcuts import render from django.http import HttpResponse def homepage(request): return HttpResponse('<h1>Home</h1>') def about(request): return HttpResponse('<h1>About</h1>') I could be missing something blatantly obvious but I've been staring at this for hours now and still can't figure out why it can't find the page. -
check if object exist before saving django rest framework
When i post new data i want to check create new man object and dok object related to man objects but if man object alredy exist i want to append related dok to it any idea how to start i'm totally new to rest_framework class Man(ListCreateAPIView): queryset = Man.objects.all() serializer_class = ManSerial model.py class Man(models.Model): name = models.CharField(max_length=50,unique=True) age = models.IntegerField() def __str__(self): return self.name class Dok(models.Model): man = models.ForeignKey(Man,on_delete=models.CASCADE,related_name="dok_man") cool = models.CharField(max_length=400) def __str__(self) : return str(self.man) serializer.py class Dokserial(serializers.ModelSerializer): class Meta: model = Dok fields ='__all__' class ManSerial(serializers.ModelSerializer): data = Dokserial(source="dok_man",many=True) class Meta: model = Man fields = '__all__' -
Django:How i can call the values of the fields of a form that i want to display properly when i want to generate a pdf printout
Hi stackoverflow team; Am newbie on django ,I Hope i can find solution or someone can help me because am really stuck on , I have spent the whole day searching without reaching my goal; I want to generate a printout after fill out a form , this form contain the fields "longeur", "largeur", "element", the user will fill out this form then he will click on a button to display the "moment" and the "area" that would be calculated automatically and be displayed under the form. but on the printout I would for now just display the values typed by the user in the field "longuer" and "largeur" Here is the story of my code; I have a the model class in models.py of the form(formulaire): class Forms(models.Model): element = models.CharField(verbose_name=" Component ", max_length=60, default="e1") hauteur = models.FloatField(verbose_name=" Height ") longuer = models.FloatField(verbose_name=" Length between posts ") in the views.py: I have defined the function "forms_render_pdf_view" for generating the pdf where I have passed the fields of the form("longeur" and "largeur" to the dictionary "context") that i want their values to be displayed on my pdf printout. def forms_render_pdf_view(request, *args, **kwargs): template_path = 'pages/generate_pdf.html' context = {'longuer':request.GET.get('longuer'), 'largeur':request.GET.get('largeur')} response … -
Add sound to push notifications
I'm using django-push-notifications to send push to our ios users (using APNS). from push_notifications.models import APNSDevice, APNSDeviceQuerySet from apps.notifications.db.models import Notification from apps.users.db.models import User class APNSService: def __init__(self, user: User, title: str, body: str, data: dict): self.user = user self.title = title self.body = body self.data = data def get_devices(self) -> APNSDeviceQuerySet: return APNSDevice.objects.filter(user=self.user) def send_message(self): return self.get_devices().send_message( message=dict( title=self.title, body=self.body ), badge=Notification.objects.filter(recipient=self.user, unread=True).count(), extra=self.data ) The problem is, that notifications comes without a sound. According to the docs, there should be extra field to execute the sound when notification is received. How to do this? -
Get respectives values from Django annotate method
I have the following query: result = data.values('collaborator').annotate(amount=Count('cc')) top = result.order_by('-amount')[:3] This one, get the collaborator field from data, data is a Django Queryset, i am trying to make like a GROUP BY query, and it's functional, but when i call the .values() method on the top variable, it's returning all the models instances as dicts into a queryset, i need the annotate method result as a list of dicts: The following is the top variable content on shell: <QuerySet [{'collaborator': '1092788966', 'amount': 20}, {'collaborator': '1083692812', 'amount': 20}, {'collaborator': '1083572767', 'amount': 20}]> But when i make list(top.values()) i get the following result: [{'name': 'Alyse Caffin', 'cc': '1043346592', 'location': 'Wu’an', 'gender': 'MASCULINO', 'voting_place': 'Corporación Educativa American School Barranquilla', 'table_number': '6', 'status': 'ESPERADO', 'amount': 1}, {'name': 'Barthel Hanlin', 'cc': '1043238706', 'location': 'General Santos', 'gender': 'MASCULINO', 'voting_place': 'Colegio San José – Compañía de Jesús Barranquilla', 'table_number': '10', 'status': 'PENDIENTE', 'amount': 1}, {'name': 'Harv Gertz', 'cc': '1043550513', 'location': 'Makueni', 'gender': 'FEMENINO', 'voting_place': 'Corporación Educativa American School Barranquilla', 'table_number': '7', 'status': 'ESPERADO', 'amount': 1}] I just want the result to be like: [{'collaborator': '1092788966', 'amount': 20}, {'collaborator': '1083692812', 'amount': 20}, {'collaborator': '1083572767', 'amount': 20}]