Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
The serializer field might be named incorrectly and not match any attribute or key on the `dict` instance.\nOriginal exception text was: 'ilan_no'
Whenever I use values() method in queryset I get the error on title. If I use a simpler query in views.py, like Ilan.objects.all() It works fine. So, It seems that the error is due to the value() method. How can I fix it? BTW, ilan_no is a identifier number for each row. I have used ModelSerializers but nothing has changed. Django==2.1 djangorestframework==3.11.0 models.py: class Ilan(models.Model): ilan_no = models.IntegerField(unique=True, blank=True, null=True) url = models.CharField(unique=True, max_length=255, blank=True, null=True) add_date= models.DateField() origin = models.CharField(max_length=100, blank=True, null=True) city = models.CharField(max_length=20, blank=True, null=True) district = models.CharField(max_length=30, blank=True, null=True) price = models.IntegerField(blank=True, null=True) serializers.py class IlanSerializer(serializers.Serializer): ilan_no = serializers.IntegerField() url = serializers.CharField() ilan_tarihi = serializers.DateField() origin = serializers.CharField() city = serializers.CharField() district = serializers.CharField() price = serializers.IntegerField() views.py class IlcePriceAndSizeDistributionListView(ListAPIView): queryset = Ilan.objects.annotate(year=ExtractYear('ilan_tarihi')).annotate(month=ExtractMonth('ilan_tarihi')).values( 'district', 'year', 'month').annotate(average_m2=Avg('m2_net')).annotate(average=Avg('price')).annotate(count=Count('ilan_no')).order_by('year', 'month') serializer_class = IlanSerializer Whole error: Got KeyError when attempting to get a value for field `ilan_no` on serializer `IlanSerializer`.\nThe serializer field might be named incorrectly and not match any attribute or key on the `dict` instance.\nOriginal exception text was: 'ilan_no'. Whole trace_back: Environment: Request Method: GET Request URL: http://127.0.0.1:8000/charts/api/v1/ilce_price_size Django Version: 2.1 Python Version: 3.7.4 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'charts.apps.ChartsConfig', 'predictions.apps.PredictionsConfig'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', … -
form.is_valid is false and form.error doesn't
i want to submit a login this my login views def login(request): context = {} print("ok ok ok ok ok") user = request.user if user.is_authenticated: print("ok ici") return render(request, "login.html") form = LoginForm(request.POST or None) if request.POST: print("ok ici1") if form.is_valid(): email = form.POST['email'] password = form.POST['password'] user = authenticate(request, email=email, password=password) print(email) if user: login(request, user) if user.user_type == '1': return render(request, "administrateur.html") elif user.user_type == '2': return render(request, "entrepreneur.html") elif form.errors: print("errors") print(form.errors) form = AuthenticationForm() context['login_form'] = form return render(request, "login.html", context) and my form class for customuser in form.py class LoginForm(forms.ModelForm): class Meta: model=CustomUser fields ={'email','password'} my html is like this <form method="POST" action="{% url 'businessplan:login' %}"> {% csrf_token %} <h2> Vous ètes un Admin ?</h2> <div class="container" action > <input type="hidden" name="user_type" value="1"> <label for ="id_email"><b>Votre Email</b></label> <input id="id_email" type="text" placeholder="Entrer Votre Email" name="email" required> <label for ="id_password" ><b>Mot de Passe</b></label> <input id="id_password" type="password" placeholder="Entrer Votre Mot de passe" name="password" required> <button type="submit" >Login</button> <label> <input type="checkbox" checked="checked" name="remember"> souviens de moi </label> </div> <div class="container" style="background-color:#f1f1f1"> <button type="button" class="cancelbtn">annuler</button> <span class="psw">oublier <a href="#">mot de passe?</a></span> </div> </form> when i submit my form.is_valid return false and the form.errors print (emailUser with this Email already exists.) … -
Neither `fab` (fabric2) nor `django-admin` are recognized commands in anaconda3 environment's Windows 10 cmd line
Upon returning to working on my Django project, I realize that neither django-admin nor fab are recognized commands anymore. I use anaconda3 distribution of Python and run everything i nthe (Anaconda3) shell. Both django and fabric2 were installed with pip and used to work normally a couple of months ago, when I last used them. The packages are present, the modules are imported uneventfully, e.g. the following works ok: import fabric2 from django.shortcuts import render I do not preclude that I inadvertently caused this myself, but all my attemtpts to find what caused it were futile. I did find django-admin and fab commands as .py files in anaconda3\Lib\site-packages folder, and site-packages is not in my %path% variable, but I can't find a clue on how to point to site-packages. Quick fixes as well as references to conceptual resources are very much appreciated. -
Is there a way to add dynamic text fields to django admin?
In the models i have i need to add a dynamic quantity of textfields, is there a way to achieve this? i also need to have them in order something like this: -
Where to find Cpanel python app console logs?
i'm trying to deploy Django app in cpanel after configuring settings and installing requirements i have this error i want the location of log file to check the error -
How to Change Input Forms for ManyToMany Field Django
Picture of Admin interface in Student Model Hello I am trying to change the input form for my admin interface for my ManyToMany Relationship for Students to their Held Licenses and Enrolled Courses. I wanna do checkboxes instead of cmd+clicking each element. Does anyone know how to change the input on the admin interfaces for models? class Student(models.Model): user = models.OneToOneField( settings.AUTH_USER_MODEL, on_delete=models.CASCADE ) date_of_birth = models.DateField( blank=True, null=True ) photo = models.ImageField( upload_to='users/%Y/%m/%d/', blank=True ) licenses_held = models.ManyToManyField( License, related_name="students" ) enrolled_courses = models.ManyToManyField( Syllabus, ) instructor = models.ForeignKey( to=Instructor, null=True, on_delete=models.SET_NULL, related_name="students" ) def __str__(self): return f'Username for user {self.user.username}' -
Local Database replication to solve simultanous writing and analytical tasks
I have a Django application that writes on the database on very short intervals. I have also a very complicated dashboard that fetches most of the data from the database every 10 seconds or so. When the dashboard refreshes however it blocks the database and I won't be able to write to the database at the same time. Any idea how to solve that? I was looking for local database replication. so I could have primary/secondary identical databases. I would use the first one to insert data and the second one for the dashboard. First of all, would that solve my problem since both of them are local databases? second, I need a way to start implementing this solution since in all the tutorials I have seen so far, the two databases would be on separate servers! But it seems obvious that there should be a non hacky solution for this. Django works of course with all database engines so I don't mind if the solution would be for sqlite, mysql, postgres or whatever. -
Display Objects Related Objects Reference In Django Admin
I have two classes with a one-to-many relationship: class Teacher(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) teacher = models.ForeignKey(Teacher, on_delete=models.CASCADE, related_name='students', default=None, null=True) In Django Teacher's Admin page (THIS-> /admin/users/teacher/ , NOT THIS -> /admin/users/teacher/1/change/) I'd like to either: List all a Teacher's students or Display the total number students a Teacher has I would usually add fields to this page using something like: class StudentAdmin(admin.ModelAdmin): list_display = ('user', 'teacher',) But as this is a one-to-many relationship and im accessing the 'many', im lost. Thank you. -
django on heroku: celery worker gets 403 forbidden when accessing s3 media to read and process media files
I'm really stuck on this one because I'm not sure where to start: My Django project allows users to upload a spreadsheet and the app then processes and aggregates the uploaded data. The file is uploaded to the MEDIA_URL using a standard form and Django model with a FileField. Once it's uploaded a celery worker accesses the file and processes it, writing the output to another model. This works fine locally, but is not working in production. I'm deploying to heroku, and using the cookiecutter-django project template. I've set up an s3 bucket and am using the django-storages library. The files upload without a problem - I can access and delete them in the Django admin, and also in the s3 bucket. However when the celery worker tries to read the file, I get an HTTP Error 403: Forbidden. I'm not sure how to approach this problem, because I am not sure which part of the stack contains my mistake. Could it be my tasks.py module, heroku:redis addon, or settings.py module? -
users can submit form only one time in django
I have made a simple Django Polling App where the user logs in and creates his/her Poll. Now I want that user shares that poll to his friends and ask them for vote and polling form should be submitted only one time by his anonymous friend. How can I do that? Should I filter users by their IP addresses? if yes then how can I do that? -
How to create new model with foreignkey in django
class Schedule(models.Model): name = models.CharField(max_length=50) class ScheduleDefinition(models.Model): schedule = models.ForeignKey(Schedule, on_delete=models.DO_NOTHING) config = JSONField(default=dict, blank=True) These are my models. I am trying to create a new ScheduleDefinition(The Schedule already exists and I know the ID I want to use for my foreign_key). I have a predefined Schedule id that I want to use, but it is not working.. Posting this body: { "schedule_id": 1, "config": { "CCC": "ccc" } } Error I get: null value in column "schedule_id" violates not-null constraint What am I doing wrong? When I create new ScheduleDefinition models, the Schedule model will already be created previously. I am never going to be creating new Schedule's when I create new ScheduleDefinition's. Serializer: class ScheduleSerializer(serializers.ModelSerializer): class Meta: model = Schedule fields = ['id', 'name'] class ScheduleDefinitionSerializer(serializers.ModelSerializer): schedule = ScheduleSerializer(read_only=True, many=False) class Meta: model = ScheduleDefinition fields = ['schedule', 'config'] View: from rest_framework import generics from .models import Schedule, ScheduleDefinition from .serializers import ScheduleSerializer, ScheduleDefinitionSerializer class ScheduleList(generics.ListAPIView): queryset = Schedule.objects.all() serializer_class = ScheduleSerializer class ScheduleDefinitionList(generics.ListCreateAPIView): queryset = ScheduleDefinition.objects.all() serializer_class = ScheduleDefinitionSerializer class ScheduleDefinitionDetail(generics.RetrieveUpdateDestroyAPIView): queryset = ScheduleDefinition.objects.all() serializer_class = ScheduleDefinitionSerializer -
Send Django signup information to MailChimp
I would like to add each user that signs up on my django project to one of my mailchimp lists with a specific tag for that user. I want the user email to be sent to mailchimp specifically when a user signups. This is what I have in my views: class UserManager(BaseUserManager): def _create_user(self, email, password, is_staff, is_superuser, **extra_fields): if not email: raise ValueError('Users must have an email address') now = timezone.now() email = self.normalize_email(email) user = self.model( email=email, is_staff=is_staff, is_active=True, is_superuser=is_superuser, last_login=now, date_joined=now, **extra_fields ) user.set_password(password) user.save(using=self._db) API_KEY = '***' api = mailchimp.Mailchimp(API_KEY) api.lists.subscribe('email': email) return user def create_user(self, email, password, **extra_fields): return self._create_user(email, password, False, False, **extra_fields) def create_superuser(self, email, password, **extra_fields): user=self._create_user(email, password, True, True, **extra_fields) user.save(using=self._db) return user The current code does not send the email of the person signing up to mailchimp -
Django: null value in column "id" violates not-null constraint after migrate database
I just make migration from my sqlite3 database to postgres using pgloader: pgloader sqlite://db.sqlite3 postgresql://... At first all looks like success, but now i have a problem with updating or creating models. When i trying to update something or create new objects with admin panel i getting an error: null value in column "id" violates not-null constraint DETAIL: Failing row contains (null, фывфывфыв, фывфывфыв, 2020-06-16, 2020-06-18, фывфыв, http://asdasd.ru/fsdfsdfsdf). For some reason now django not sending object id, and sending null istead. How can i fix it, and why did it happen? Some info about this table from pgadmin: CREATE TABLE public.pages_exhibitions ( id bigint NOT NULL, city text, name text, start_date date, end_date date, adress text, url text, CONSTRAINT idx_25075_pages_exhibitions_pkey PRIMARY KEY (id) ) WITH ( OIDS=FALSE ); ALTER TABLE public.pages_exhibitions OWNER TO polonika; model in django of this table: class Exhibitions(models.Model): city = models.CharField(max_length=200, blank=False, verbose_name='Город выставки') name = models.CharField(max_length=200, blank=False, verbose_name='Название выставки') start_date = models.DateField(blank=False, verbose_name='Дата начала выставки') end_date = models.DateField(blank=False, verbose_name='Дата окончания выставки') adress = models.CharField(max_length=500, blank=False, verbose_name='Адрес') url = models.URLField(max_length=500, blank=False, verbose_name='Ссылка', null=True) No varchar limits, no timestamps or anything. Did my migration on postgres was with errors? Or its ok? -
Django Google App Engine Upload files greater than 32mb
I have a Django Rest Framework Project that I've integrated with Django-Storages to upload files to GCS. Everything works locally. However, Google App Engine imposes a hard limit of 32mb on the size of each request, I cannot upload any files greater than this described limit. I looked into many posts here on StackOverflow and on the internet. Some of the solutions out listed the use of Blobstore API. However, I cannot find a way to integrate this into Django. Another solution describes the use of django-filetransfers but that plugin is obsolete. I would appreciate it if someone can point me towards an approach I can take to fixing this problem. -
MultiValueDictKeyError at /addtocart/ 'ordered_name'
I'm trying to run an add to cart functionality, but i get this error when i click; MultiValueDictKeyError at /addtocart/ 'ordered_name' this is my code def addtocart(request): ordered_name = request.POST['ordered_name'] price = request.POST['price'] image = request.POST['image'] put_item = OrderedItem(ordered_name=ordered_name, price=price, image=image) put_item.save() return redirect('cart') class OrderedItem(models.Model): ordered_name = models.CharField(max_length=50) price = models.FloatField() image = models.ImageField(upload_to='pics') -
JWT authentication using Django if user email and password is stored in cassandra remote database
I am working on sign-up and sign-in services for my application. The user data (firstName, email, password and phone) is stored in remote cassandra database (not in django default SQLite DB). Now I want to use JWT to secure my services and for that I saw online help for various JWT django-rest-framework packages but for all of that it requires that user data (email and password) should be on local django server. I tried to create custom user class using AbstractBaseUser but it is not working. Any suggestions on how I can authenticate django application using data stored in remote DB. -
Django : Select Multiple products from a Model
I'm new in Django, i'm working on an Inventory management project, I have a model called Products which contains some products, and i want to make a 'Return list' of products to a specific Supplier (i have this model also containing suppliers infos) , i need a form that i can type a product's name, it appears, then add it with specific quantity and so on,and finally save it to database as pdf file or csv , please help Thanks -
How to only let user transfer funds from wallet which belongs to his account in django?
models.py from django.db import models from django.contrib.auth.models import User from djmoney.models.fields import MoneyField # Create your models here. class Account(models.Model): # ACCOUNT_TYPES = ( # ('PERSONAL', 'PERSONAL'), # ('BUSINESS', 'BUSINESS') # ) account_owner = models.OneToOneField(User, on_delete=models.CASCADE, null=True) account_number = models.CharField(max_length=15, unique=True) # account_type = models.CharField(max_length=17, choices=ACCOUNT_TYPES) balance = models.DecimalField(max_digits=5, decimal_places=3) date_created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.account_number class Transaction(models.Model): account_owner = models.OneToOneField(User, on_delete=models.CharField, null=True) from_account = models.CharField(max_length=15) to_account = models.CharField(max_length=15) amount = models.DecimalField(max_digits=5, decimal_places=3) timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.amount) views.py @login_required def transfer(request): if request.method == "POST": form = forms.TransactionForm(request.POST) if form.is_valid(): sender = models.Account.objects.get(account_number=request.POST.get('from_account')) if sender.balance > decimal.Decimal(request.POST.get('amount')): trans = form.save() trans.account_owner = request.user # debit the sender account sender.balance -= decimal.Decimal(request.POST.get('amount')) sender.save() # credit receiver account receiver = models.Account.objects.get(account_number=request.POST.get('to_account')) receiver.balance += decimal.Decimal(request.POST.get('amount')) receiver.save() return render(request, "wallet.html") else: form = forms.TransactionForm() return render(request, "wallet.html", {'form': form}) Hi, I am having trouble with this, transferring funds from one account to another is working great but I only want the user's account number to be able to transfer who is logged in...not this that I can input anyone's account number and transfer from one account to another...I just want to make sure the account number belongs to the user … -
If condition in django templates not working
I have tried the if condition based on the value defined in the django template {% if randomgen == 2 %} {% randomgen %}1 {% else %} {% randomgen %} 2 {% endif %} the randomgen is defined to pick in random between 1 and 2 and the value is being displayed correctly in tag but irrespective of the value it always going to else condition -
How does two function or two class call each other in python
I need to use a class attribute value (myClass.name) in a function (myFunction) and inside the class the function is also invoked which is defined earlier or next to the class. I placed the class first and the function last and vice versa. (test.py is the file name) I'm trying to use a function inside django model filed. I'm surprised Why I can't find solution like such a common thing (at least i think, it should be common). kindly help me to solve this Problem. Here First function than class: def myFunction(): myName = myClass.name return myName class myClass: name = 'rafi sarker' hello = 'Welcome'+ myFunction() myFunction() Erro in this case: Traceback (most recent call last): File "test.py", line 5, in <module> class myClass: File "test.py", line 7, in myClass hello = 'Welcome'+ myFunction() File "test.py", line 2, in myFunction myName = myClass.name NameError: name 'myClass' is not defined Here Class first, function last: class myClass: name = 'rafi sarker' hello = 'Welcome'+ myFunction() def myFunction(): myName = myClass.name return myName myFunction() Error in this case: Traceback (most recent call last): File "test.py", line 2, in <module> class myClass: File "test.py", line 4, in myClass hello = 'Welcome'+ myFunction() … -
How can I resolve Django class serializer assertion Error
Trying to work with Django Rest Framework when I run the code I get an error on Error message: Class MovieSerializer missing "Meta.model" attribute Here are my Serializers below class MovieSerializer(serializers.ModelSerializer): class Meta: models = Movie fields = ('id', 'title', 'description') class RatingSerializer(serializers.ModelSerializer): class Meta: models = Rating fields = ('id', 'movie', 'stars', 'user') I legit do not know where the error could be -
How do I build a Django model that retrieves some fields from an API?
Question How can I build a Model that that stores one field in the database, and then retrieves other fields from an API behind-the-scenes when necessary? Details: I'm trying to build a Model called Interviewer that stores an ID in the database, and then retrieves name from an external API. I want to avoid storing a copy of name in my app's database. My first attempt was to create a custom Model Manager called InterviewManager that overrides get_queryset() in order to set name on the results like so: class InterviewerManager(models.Manager): def get_queryset(self): query_set = super().get_queryset() for result in query_set: result.name = 'Mary' return query_set class Interviewer(models.Model): # ID provided by API, stored in database id = models.IntegerField(primary_key=True, null=False) # Fields provided by API, not in database name = 'UNSET' # Custom model manager interviewers = InterviewerManager() However, it seems like the hardcoded value of Mary is only present if the QuerySet is not chained with subsequent calls. I'm not sure why. For example, in the django shell: >>> list(Interviewer.interviewers.all())[0].name 'Mary' # Good :) >>> Interviewer.interviewers.all().filter(id=1).first().name 'UNSET' # Bad :( My current workaround is to build a cache layer inside of InterviewManager that the model accesses like so: class InterviewerManager(models.Manager): def … -
how display formset error validation massege
i'm trying to display error massege in my inlineformset , i have contact and phone number in my parent and in my child (formset) i have several fields , each one has its own error massege , but the problem is that they only appear if i have a massege error in either contact or phone number in my parent's field even if in my parent's field has no error and in my child fields have several error still nothing appear and the form will be save this is my CreateView def get_context_data(self,*args,**kwargs): data = super().get_context_data(*args,**kwargs) if self.request.POST: data['formset'] = MyInlineFormSet(self.request.POST) else: data['formset'] = MyInlineFormSet() return data def form_valid(self,form): context = self.get_context_data() formset = context['formset'] with transaction.atomic(): form.instance.author = self.request.user self.object = form.save() if formset.is_valid() and form.is_valid() and formset.cleaned_data!={}: formset.instance = self.object formset.save() return super().form_valid(form) my template <form method="POST">{% csrf_token %} {{formset.management_form}} <p> {{form.name| add_class:'col-12 text-center d-inline text-center'}} {% if form.name.errors %} <div class="error mx-auto"> {{form.name.errors}} </div> {% endif %} <div class="col-12 p-0 border-top border-light "> <table class="customeTable col-12 table-responsive-sm info text-center table1 mx-auto mb-2 "> <tbody class="tbody tb1 "> {% for content in formset.forms %} <tr class="p-0 col-12"> <td class=""> {{content.title| add_class:'col-12 text-center'}} {% if content.title.errors %} <div class="error … -
Django 3 Pass Get The Selected Value Dropdown select option
Django dropdown option selected. Get data in template and select option. My code is. views.py def home(request): compType = Type.objects.all() comptype = request.GET.get('comp_type') context = { 'compType': compType } return render(request, 'compapp/dashboard.html', context) search.html <div class="form-group"> <label>Type</label> <select class="form-control select2" name="comp_type" style="width: 100%;"> <!-- <option disabled="true" selected >Company Type</option> --> {% for i in compType %} <option value="{{ i }}" {% if request.GET.items == i %}selected{% endif %}>{{ i }}</option> {% endfor %} </select> -
Generating foreign based query sets
I currently have three models which is Service, Customers and Orders as shown below class Customer(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) name = models.CharField(max_length=200, null=True) def __str__(self): return self.user.email class Services(models.Model): name = models.CharField(max_length=200, null=True) price = models.FloatField(null=True) class Order(models.Model): customer = models.ForeignKey(Customer, null=True, on_delete = models.SET_NULL) service = models.ForeignKey(Service, null=True, on_delete = models.SET_NULL) As shown, the Order model has foreign keys from the Customer and Service models. When I construct a query set from Service and Customer. Service.objects.all() Or Customer.objects.all() How can I receive the same results from accessing the query sets based on the orders model? Currently I am creating query set as shown below Order.objects.all().values('service') And Order.objects.all().values('customer') However I am not quite receiving the same results if I were to do as Service.objects.all() Or Customer.objects.all() How can I have a query set based on the order model to receive the results from query set from the Service and Customer as shown above?