Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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}] -
Django code work on local machine but dose not work on heroku
my Django code works on my computer but when I pushed it onto Heroku, it shows and error, but whene I run the program on my machine, it works fine. can anyone help me please. The error : 2022-02-11T17:26:36.187430+00:00 app[web.1]: <QueryDict: {'csrfmiddlewaretoken': ['bB8ABomINOKodDyyfQbC8ykkl9Rmormxv9D3X7kVJpyeHeJDKaFeqSPFhZJiThzC'], 'colors': [''], 'size': ['270'], 'colors_ca': [''], 'blurriness': ['4'], 'edges': ['with edges'], 'points': ['5000'], 'back_color': ['#191919'], 'letters': ['$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\\|()1{}[]?-_+~<>i!lI;:,"^`\'. '], 'blur': ['71'], 'style': ['cartooning']}> 2022-02-11T17:26:36.191835+00:00 app[web.1]: user>>> admin 2022-02-11T17:26:36.194190+00:00 app[web.1]: media\img\20\866E71D6-7AA1-4429-AB3F-99823DDF29B0.jpeg 2022-02-11T17:26:36.194192+00:00 app[web.1]: path is up 2022-02-11T17:26:36.226445+00:00 app[web.1]: Internal Server Error: /home_f/cartoonify_f/ 2022-02-11T17:26:36.226446+00:00 app[web.1]: Traceback (most recent call last): 2022-02-11T17:26:36.226447+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner 2022-02-11T17:26:36.226447+00:00 app[web.1]: response = get_response(request) 2022-02-11T17:26:36.226455+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response 2022-02-11T17:26:36.226456+00:00 app[web.1]: response = wrapped_callback(request, *callback_args, **callback_kwargs) 2022-02-11T17:26:36.226456+00:00 app[web.1]: File "/app/app/views/views.py", line 273, in cartoonify 2022-02-11T17:26:36.226457+00:00 app[web.1]: cartoon, total_color = cartooning(path, request) 2022-02-11T17:26:36.226457+00:00 app[web.1]: File "/app/app/views/views_filters_func.py", line 606, in cartooning 2022-02-11T17:26:36.226457+00:00 app[web.1]: print('befor resizing -- origainal 50px small image: ', img.shape) 2022-02-11T17:26:36.226458+00:00 app[web.1]: AttributeError: 'NoneType' object has no attribute 'shape' 2022-02-11T17:26:36.227187+00:00 app[web.1]: 10.1.13.21 - - [11/Feb/2022:17:26:36 +0000] "POST /home_f/cartoonify_f/ HTTP/1.1" 500 64458 "https://pixelifier.herokuapp.com/home_f/" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.2 Safari/605.1.15" 2022-02-11T17:26:36.227822+00:00 heroku[router]: at=info method=POST path="/home_f/cartoonify_f/" host=pixelifier.herokuapp.com request_id=9121505b-0838-4c88-bc0f-67cbf633667d fwd="37.239.124.11" dyno=web.1 connect=0ms service=10399ms status=500 bytes=64759 … -
How can I migrate a Wordpress website to Django
I currently have a fully functional Wordpress website that is mostly static. It is a marketing website that mainly displays static webpages. My client would however want to add new features such as accounts functionality and others using the Django web framework. I am well versed in Django, but I would like to know what the best approach is to migrate the Wordpress site into a Django project. Or if there is a better way. Thank you. -
DRF: Updating a model in another models serializer or view
so I have a User and schools model which are related as an Owens(ManyToMany), student, and staff, if an owner registers and creates a school, I would like to perform a partial update to the Owens field of the request.user from having a null/blank or previously created schools to adding the newly created school serializers.py class SchoolSerializerBase(serializers.ModelSerializer): ... class Meta: model = School fields = ... def validate(self, attrs): ... return attrs def create(self, validated_data): instance = School.objects.create( ... ) instance.save() return instance and i have a simple view for it class CreateSchoolView(generics.CreateAPIView): queryset = School.objects.all() permission_classes = [IsSchoolOwner, ] serializer_class = SchoolSerializerBase My question: how do I update the request.user.ownes field and add the school instance to it?? -
django.db.utils.IntegrityError: The row in table 'main_page_projects' with primary key '1' has an invalid foreign key
Created first project model and populated it with some data, then tried to add profile model to it (no data there) through foreign key and while trying to do a migration for linking profile model with projects model getting an error: django.db.utils.IntegrityError: The row in table 'main_page_projects' with primary key '1' has an invalid foreign key: main_page_projects.profile_id contains a value '1' that does not have a corresponding value in main_page_profile.id. Value nr 1 was picked during the makemigration: It is impossible to add a non-nullable field 'profile' to projects without specifying a default. This is because the database needs something to populate existing rows. Please select a fix: 1) Provide a one-off default now (will be set on all existing rows with a null value for this column) 2) Quit and manually define a default value in models.py. I googled around and looked also stackoverflow, probably if I delete migration files and sqlite3 database then migrations should work, but I would like to know how to make it to work without deleting migration files and database. If populate profile then migration also works, but why it won't create a link with default values? What should I do differently or where … -
Django Image not showing up in django when using template tags
When i try calling an image like this {{ profile.image.url }} it works in the profile page, but in the home page when i do {{ post.user.profile.image.url }} nothing shows up and that is not what i expect. i have also tried checking if the image url work and yes it's working. NOTE: It working fine as expected in the profile page but in index.html it seems like nothing is showing up. index.html {% for post in post_items %} <a href="{{post.user.profile.image.url}}" class="post__avatar"> <img src="{{post.user.profile.image.url}}" alt="User Picture"> </a> <a href=""{{ post.user.username }}</a> models.py class Profile(models.Model): user = models.ForeignKey(User, related_name='profile', on_delete=models.CASCADE) image = models.ImageField(upload_to="profile_pciture", null=True) def save(self, *args, **kwargs): super().save(*args, **kwargs) def __str__(self): return f'{self.user.username} - Profile' def save(self, *args, **kwargs): super().save(*args, **kwargs) -
Django (dj-rest-auth) Custom user registration with a ForeignKey
I have created a custome user in my App, and points to a timezone record, in the TimeRegion Model. model.py class TimeRegion(models.Model): id=models.UUIDField(primary_key=True,default=uuid.uuid4,editable=False,) tz_key=models.CharField(max_length=200,) class CustomUser(AbstractUser): id=models.UUIDField(primary_key=True,default=uuid.uuid4,editable=False,) user_timezone=models.ForeignKey(TimeRegion,verbose_name="Time Zone",on_delete=models.DO_NOTHING, blank=True, null=True) Extended the API call to include the custom field. serializers.py class CustomRegisterSerializer(RegisterSerializer): first_name = serializers.CharField() last_name = serializers.CharField() statement_agreement = serializers.BooleanField() user_timezone = serializers.UUIDField() #Tried CharField() and PrimaryKeyField() def get_cleaned_data(self): super(CustomRegisterSerializer, self).get_cleaned_data() return { 'username': self.validated_data.get('username', ''), 'password1': self.validated_data.get('password1', ''), 'password2': self.validated_data.get('password2', ''), 'email': self.validated_data.get('email', ''), 'first_name': self.validated_data.get('first_name', ''), 'last_name': self.validated_data.get('last_name', ''), 'user_timezone': self.validated_data.get('user_timezone', ''), } def save(self, request): adapter = get_adapter() user = adapter.new_user(request) self.cleaned_data = self.get_cleaned_data() adapter.save_user(request, user, self) setup_user_email(request, user, []) user.user_timezone = self.cleaned_data.get('user_timezone') user.save() return user setting.py REST_AUTH_REGISTER_SERIALIZERS = { 'REGISTER_SERIALIZER': 'api.serializers.CustomRegisterSerializer' } However whenever I run an API test to check that I am able to register a new user, get the following error message: test code # Get the timezone record url_timezone = 'http://127.0.0.1:8000/api/v1/timezonelist/' response_timezone = self.client.get(url_timezone, content_type='application/json') #Register the user to the first timezone: url_signup = 'http://127.0.0.1:8000/api/v1/dj-rest-auth/registration/' params_signup={ 'first_name': 'John', 'last_name': 'Tester', 'email':'testuser@email.com', 'password1':'pwdktudchJsuec123', 'password2':'pwdktudchJsuec123', 'user_timezone': response_timezone.data[0]['id'], } response_signup = self.client.post(url_signup, data=json.dumps(params_signup), content_type='application/json') responce: Traceback (most recent call last): File "/code/api/tests.py", line 45, in test_from_start response_signup = self.client.post(url_signup, data=json.dumps(params_signup), content_type='application/json') File "/usr/local/lib/python3.9/site-packages/rest_framework/test.py", … -
How To Decrypt Content In The Backend Then Pass It To The Frontend With Other Attributes
I'm building a Django social media, that focuses on privacy and anonymity, and I'm trying to build E2EE functionality, but I can't add any JavaScript in the project, so the decryption of the messages, notes is done locally and is stored in a temporary method like a dictionary or a list, then passed to the frontend, my problem is how to pass other attributes to the frontend? like messages are made like this: class Message(models.Model): id = models.UUIDField(primary_key = True, default = uuid.uuid4, editable = False) msg = models.BinaryField(null=False, blank=False) date = models.DateTimeField(default=timezone.now) to = models.ForeignKey(User, related_name='received', on_delete=models.CASCADE, blank=False, null=False) res = models.CharField(max_length=5, blank=False, null=False) author = models.ForeignKey(User, blank=False, null=False, related_name='sent', on_delete=models.CASCADE) so the msg that is the content of every message is the encrypted field, and when the messages view is loaded the messages are decrypted with the users private key class messages(LoginRequiredMixin, View): def get(self, request, touser, *args, **kwargs): if User.objects.filter(username=touser).exists(): user = User.objects.get(username=touser) msgs = Message.objects.filter(Q(to=request.user)|Q(author=request.user)) try: key = request.COOKIES['key'] except: return redirect('set-key') private_key = serialization.load_pem_private_key(request.user.profile.privatekey, password=key.encode('utf-8'),) messagescontent = [] for mess in msgs: plaintext = private_key.decrypt(mess.msg, padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None)) messagescontent.append(plaintext.decode()) context = {'msgs': messagescontent,} else: messages.warning(request, 'User Doesn\'t Exist') return redirect('messages-list') return render(request, 'posts/messages.html', context) so … -
Django ModuleNotFoundError: No module named 'core'
I was working on a blog. The static files are in a bucket on aws and the website is being hosted on heroku. Each time i try to edit a blog post ie(http://127.0.0.1:8000/admin/blog/post/1/change/) I keep getting this error: File "C:\Users\Hp\AppData\Local\Programs\Python\Python310\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 992, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1004, in _find_and_load_unlocked ModuleNotFoundError: No module named 'core' Here is my settings.py: """ Django settings for proton project. Generated by 'django-admin startproject' using Django 4.0.2. For more information on this file, see https://docs.djangoproject.com/en/4.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.0/ref/settings/ """ from pathlib import Path import os import django_heroku import dj_database_url # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'secret key' # SECURITY WARNING: don't run with debug turned on in production! … -
django error using if statement with or condtion
I am if using if statement with or condition if batch == (None or 0): raise error and also if batch is not None and farm ==(None or 0): raise error