Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: cannot get data sent by axios in views
I am trying to send post request using axios like usual axios({ method: 'post', url: '/handle_login_info/', headers: { 'X-CSRFToken': csrftoken, }, data: { a: 'a', b: 'b' } }).then(res => console.log(res)).catch(err => console.error(err)) The view function corresponds to /handle_login_info/ is called, but there is nothing in request.POST. If I modify the code above a little like below data: JSON.stringify({ a: 'a', b: 'b' }) then request.POST's value is <QueryDict: {'{"a":"a","b":"b"}': ['']}>. Why does this happen? How do I send and receive axios data normally? -
Heroku hosting uses 5 times more RAM than Google Cloud Run
For my Django application, there are many lists, sets, and dictionaries, that I load from pickle files into RAM, for fast access at any moment. I am getting Error R14 (Memory quota exceeded) on Heroku. I have done lots of debugging and memory usage analysis of Python. I know how to optimize code, and I have optimized everything that can be optimized. Now this is the weird thing: the same application, literally the same deployment, on Google cloud takes 5 times less RAM memory than on Heroku. I deploy both of them from the same Git repo. 1 GB of RAM on google is enough, lets assume it takes around 900 MB RAM there, well on Heroku the same thing takes 4.5 GB RAM, for which I need to "rent" 8 GB RAM, which makes the costs insanely high. Why is this happening? So it's not about optimizing my own code. How can the same app on Heroku occupy around 5 times more RAM than on Google? How I got that measurement of 5 times, is actually, I have an ecommerce website, with products, and they have attributes and values, and also keywords. I store all these values and keywords … -
Filtering a Model with a Foreignkey with a list of other models?
I want to filter the org collectors by their foreign key org_data by a list of org_data with the Github type. OrgCollector.objects.filter( org_data=OrgData.objects.filter( data_type=DataTypeEnum.GITHUB )) I currently have this but it does not work. What do I do instead? Running through the list with a for loop works, but I expect that there is a better way. I also tried org_data__in but that did not seem to work either. -
django 4 recent issue
Django has recently released a new version and I'm trying to work with it. But the problem that I have is that one I say pip install Django no matter in the cmd or visual studio's cmd, it installs Django 4.0, but once I put the file in the code editor (it is vs code), it changes to Django 3.0 and I was shocked once I saw that even in pip freeze` it is changed! I would be so glad if you can help me with this problem -
Django: handle multi stock (related table) in Product Based List View
I need to manage Products shared by multiple Warehouses. I tried to get through with annotate, prefetch_related, select_related but in my case, those solutions are upside-down for my need. I need first to get product and then, the related stock in each warehouse and display it in template and the foreignKey is in my Sststock, not in Product I have : Product models.py class Product(models.Model): famille = models.ForeignKey(Famille, on_delete=SET_NULL, null=True) sku = models.CharField(max_length=100, unique=True) nom = models.CharField(max_length=250) fournisseur = models.ForeignKey( Supplier, on_delete=models.SET_NULL, default=12, null=True) qty = models.IntegerField() mini = models.IntegerField() maxi = models.IntegerField() [...] Warehouse models.py class Warehouse(models.Model): nom = models.CharField(max_length=100) code = models.CharField(max_length=10, null=True) adresse = models.CharField(max_length=255) cp = models.IntegerField() ville = models.CharField(max_length=50) tel = models.CharField(max_length=10) email = models.EmailField(default='sav@iturbo.fr', null=False, blank=False) allow_store = models.BooleanField(default=False) def __str__(self): return self.nom.upper() Sststock models.py class SstStock(models.Model): sst = models.ForeignKey(Warehouse, on_delete=models.CASCADE) mageid = models.ForeignKey(Product, on_delete=models.CASCADE, null=True) qty = models.IntegerField() last_update = models.DateTimeField(default=timezone.now) For the time, I only have 3 warehouses but there could have more in the future. First I had "hard-coded" my 3 warehouses in Product's model but this solution was not easily scalable. What would be the best way to achieve my goal ? I've seen solution with Mysql Stored Procedures in … -
Password saved as plain text in database Django AbstractUser
Actually, I am working on a project and I have to modify the authentication system so that I am able to log in using email instead of a username. Also, I have to remove the username field as it's not relevant for the use case scenario. The problem i am getting is after user registers the password is saved as a plain text in database. Below is my implementation My views.py def signup(request): if request.method == 'POST': password = request.POST['cr-pwd'] email = request.POST['cr-eml'] phone_number = request.POST['cr-phone'] print(password, email, phone_number) user = User.objects.create_user(email, password) # user.username = username user.password = password user.email = email user.phone_number = phone_number user.save() messages.success(request, 'Your account has been created successfully') return render(request, 'index.html') return render(request, 'index.html') My models.py from django.contrib.auth.models import AbstractUser, BaseUserManager from django.db import models from django.utils.translation import gettext_lazy as _ class UserManager(BaseUserManager): """Define a model manager for User model with no username field.""" use_in_migrations = True def _create_user(self, email, password, **extra_fields): """Create and save a User with the given email and password.""" if not email: raise ValueError('The given email must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **extra_fields): """Create and save a regular … -
Django - Create custom PrimaryKey with selected ForeignKey object
Problem: I want to create a custom-PrimaryKey in ItemCode Model contain with selected-ForeignKey object. So, It's gonna change the custom-PrimaryKey every time submit a new ForeignKey field. Here's my Model: class ItemCategory(models.Model): idItemCat = models.CharField(primary_key=True max_length=5) nameCategory = models.CharField(max_length=150) class ItemCode(models.Model): idItemCode = models.CharField(primary_key=True, editable=False, max_length=20) idItemCat = models.ForeignKey(ItemCategory, on_delete=models.DO_NOTHING) To illustrate, here's the example of custom-PrimaryKey I wanna create: MN.202203.001 MN means Monitor from selected-ForeignKey object Then, it change every time I submit new ForeignKey field, like this: CM.202203.002 CM means Printer from new selected-ForeignKey object What I've tried: I've tried to using request method but I don't know how to implemented it in my Model. def CustomPK(request): if request.method == 'POST': category = ItemCategory.objects.get(pk=request.POST.get('idItemCat')) return category Question: Is there anyway to get or fetch the object from selected-ForeignKey field to make a custom-PrimaryKey with request method? or is there any better way to do it? If my question isn't clear enough, please let me know... -
django - get values from formset
I've tried to get value from formset do some calculations and pass the output. My code is: def form_valid(self, form, formset): rndid2 = RndIds() form.instance.doc_added_by = self.request.user form.instance.doc_guid = rndid2.random_doc_guid() instances = formset.save(commit=False) for instance in instances: cd = instance.cleaned_data() at_id=cd.get('att_guid') instance.att_added_by = str(self.request.user) instance.att_ctrl_sum = rndid2.random_doc_application_id(at_id) instance.save() return HttpResponseRedirect(self.get_success_url()) But got an error 'Att' object has no attribute 'cleaned_data' Att is my model How can I get the formset values? -
DoesNotExist at /admin/auth/user/. User matching query does not exist
I am trying to delete a user from admin, but can't do it. I tried to delete function by changing sender to User and user= instance but 'maximum recursion depth' error occurs. 1.users/signals.py from django.db.models.signals import post_save, post_delete from django.dispatch import receiver from .models import Profile from django.contrib.auth.models import User @receiver(post_save, sender=Profile) @receiver(post_save, sender=User) def createProfile(sender, instance, created, **kwargs): if created: print('Profile created') user = instance user.save() profile = Profile.objects.create( user=user, username = user.username, email=user.email, ) # @receiver(post_delete, sender=Profile) def deleteUser(sender, instance, **kwargs): user = instance.user // error showing to this line user.delete() # post_save.connect(createProfile, sender=User) post_delete.connect(deleteUser, sender=Profile) **2.Users/models.py from django.db import models import uuid from django.contrib.auth.models import User # Create your models here. class Profile(models.Model): user = models. OneToOneField(User,on_delete=models.CASCADE, null=True,blank=True) name = models.CharField(max_length=200, null=True, blank=True) username = models.CharField(max_length=200, null=True, blank=True) short_intro = models.TextField(max_length=1000,null=True,blank=True) short_bio = models.TextField(max_length=1000,null=True,blank=True) user_image = models.ImageField(null=True,blank=True,upload_to='profiles/',default='profiles/mehdi.png') email = models.CharField(max_length=200, null=True, blank=True) social_github = models.CharField(max_length=200, null=True, blank=True) social_linkedin = models.CharField(max_length=200, null=True, blank=True) social_website = models.CharField(max_length=200, null=True, blank=True) social_twitter = models.CharField(max_length=200, null=True, blank=True) social_stackoverflow = models.CharField(max_length=200, null=True, blank=True) def __str__(self): return self.username -
Django differentiate between incorrect login information and inactive user on login
Currently I added in my site a method for email confirmation when registering. What I saw though, is that when the user is registered, but didn't click in the confirmation link yet and tries to login, I can't differentiate between wrong user/password and not confirmed user. This is my login function: def loginUser(request): if request.user.is_authenticated: return redirect("decks:index") if request.method == "POST": form = AuthenticationForm(request, data=request.POST) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(username=username, password=password) if user is not None and user.is_active: login(request, user) return redirect("myApp:portal") elif user is not None: messages.error(request, "Email is not confirmed.") else: messages.error(request, "Invalid username or password.") else: messages.error(request, "Invalid username or password.") form = AuthenticationForm() return render(request, "myApp/login.html", context = {'login_form': form}) The problem is that when running form.is_valid() the authenticate function from /home/nowork/.local/lib/python3.8/site-packages/django/contrib/auth ModelBackend is executed: def authenticate(self, request, username=None, password=None, **kwargs): if username is None: username = kwargs.get(UserModel.USERNAME_FIELD) if username is None or password is None: return try: user = UserModel._default_manager.get_by_natural_key(username) except UserModel.DoesNotExist: # Run the default password hasher once to reduce the timing # difference between an existing and a nonexistent user (#20760). UserModel().set_password(password) else: if user.check_password(password) and self.user_can_authenticate(user): return user So the form.is_valid() will never be true when … -
Django/Python - remove row in sqlite3 database with form button
I want to have a delete button to delete a row in my sqlite3 database. I'm almost there but I'm not sure what I should add to send the ID from my html of the row to my views.py. This is what I have: mailindex.html <form action="" method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="form-group"> <a href="{% url 'core:mail' mail.id %}" class="btn btn-secondary btn-sm">Manage</a> <button type="submit" name="deletemail" value="deletemail" class="btn btn-secondary btn-sm">Delete</button> </div> </form> views.py class MailboxView(generic.ListView): extra_context = {"mailbox_page": "active"} model = MailMessage context_object_name = 'mails' template_name = 'core/mailbox/mailindex.html' def post(self, request): # if 'deletemail' in self.request.POST: if request.POST.get('deletemail'): mail = MailMessage.objects.get(pk=13) mail.delete() return HttpResponseRedirect(self.request.path_info) It works, in a sense that when I push the delete button it deletes email with ID = 13. Which is logical as I put no. 13 there. I would like to replace '13' with the mail.id, but I'm not sure how to do this. I hope it is possible: I would prefer it to be as simple as possible, so to not create an extra url, but again don't know if this is possible... -
Covert String into Hexbytes
I have this signature b'V\xae\xc1\x0bU:\xcaV0\xcbBO@\xe6\xf7\x9c\xb3\xe4R\xa0\xb4\x10\xcf\x1e\x9b\xc3\x03\t\x84\xf9\x92!\xd2p\x12\x16*\x8biJ\xfeNq\x11\xfa5\x05\n\x19*9\xdak\x989j\xd8:\x7f\xdd\x03\xa2\xd7\x1c' but it is in string format. I am using w3.eth.account.recover_message(encode_defunct( text=account_address.challenge), signature=signature) to get address back, but as it only accepts <class 'hexbytes.main.HexBytes'> format. So can please anyone help me convert this value into Hexbytes but as you can see value of string should not change. I am using django here. -
Daily scheduler on django
I am trying to build a sort of daily scheduler with Django. My goal is to have something like the screenshot below: I'd like to have this kind of daily calendar where I can manage the bookings in different times of the day. I don't know if this is possible with django (I suppose it is, even though I have no clue about the logic around it) or if I need to build it in other languages. Last, but not least, I'd like to understand if there's already something like that somewhere in the internet pre built. I tried to google it but so far I didn't find anything. Thank you all very much -
How to capture user information during related model's update using inlineformset factory
I am trying to save user ID in the model's relevant field on create as well as update of a pair of related models. Following are the objects, albeit truncated for better readability: models.py class Plant(BaseTimeStampModel): # .... class Calendar(BaseTimeStampModel): calendar_id = models.CharField(primary_key=True, max_length=4) short_text = models.CharField(max_length=55, ... # ... class AssignedPlants(BaseTimeStampModel): assginment_id = models.CharField(primary_key=True, max_length=4, ... plant = models.ForeignKey(primary_key=True... calendar = models.ForeignKey(Calendar, related_name= ... short_text = models.CharField(max_length=55, ... # ... forms.py class CreateCalendarForm(forms.ModelForm): class Meta: model = Calendar fields = (... class CreatePlantAssgnForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(CreatePlantAssgnForm, self).__init__(*args, **kwargs) self.auto_id = True class Meta: model = AssignedPlants fields = ... exclude = () CreateCalendarFormset = inlineformset_factory( Calendar, AssignedPlants, form = CreatePlantAssgnForm, extra=0, can_delete=True, min_num=1, validate_min=True, max_num=50, validate_max=True, ) views.py class CalendarCreateView(CreateView): template_name = ... model = Calendar form_class = CreateCalendarForm success_url = ... def get_context_data(self, **kwargs): data = super(CalendarCreateView, self).get_context_data(**kwargs) if self.request.POST: data['calendar'] = CreateCalendarFormset(self.request.POST, self.request.FILES) else: data['calendar'] = CreateCalendarFormset() return data def form_valid(self, form): form.instance.created_by = self.request.user context = self.get_context_data() calendar = context['calendar'] with transaction.atomic(): if calendar.is_valid(): self.object = form.save() calendar.instance = self.object for frmst_form in calendar.forms: f = frmst_form.save(commit=False) f.created_by = self.request.user calendar.save() f.save() return redirect(... else: context.update({'calendar': calendar}) return self.render_to_response(context) return super(CalendarCreateView, self).form_valid(form) With this … -
How to fix cors error while using fetch api in django?
Objective: Fetch url from Google drive without CORS policy error A django app with django-cors-headers enabled in settings, allowing all hosts continues to give an error stating the request has been blocked due to CORS policy. ALLOWED_HOSTS = ['*'] INSTALLED_APPS = [ ..., 'corsheaders', ] MIDDLEWARE = [ ..., 'corsheaders.middleware.CorsMiddleware', ] CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = False CORS_ALLOW_METHODS = [ "DELETE", "GET", "OPTIONS", "PATCH", "POST", "PUT", ] CORS_ALLOW_HEADERS = [ "accept", "accept-encoding", "authorization", "content-type", "dnt", "origin", "user-agent", "x-csrftoken", "x-requested-with", ] A url fetch function written in javascript successfully fetches url from couple of websites, but fails to fetch url from Google drive. fetch(url) .then(response => { if (!response.ok) { throw new Error('HTTP error ' + response.status); } # do something .catch(e => { console.error('error', e); }); }) Can someone help? -
Select a valid choice. That choice is not one of the available choices --Django forms
I am new to Django. I am trying to make a drop down select form (category) in django. The form renders well on the webpage but when I try to submit I get the error Select a valid choice. That choice is not one of the available choices. I have done everything possible within my capability to resolve this. if you have any idea on how to go about this please help. model.py from django.db import models from django.contrib.auth.models import User from django.urls import reverse # Create your models here. class Category(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name def get_absolute_url(self): return reverse('detail', args=[str(self.id)]) # return reverse('home') class Post(models.Model): title = models.CharField(max_length=100) text = models.TextField() author = models.ForeignKey(User, on_delete=models.CASCADE) edited = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) category = models.CharField(max_length=100, default='coding') def __str__(self): return f'{self.title} by {self.author} {self.pk}' def get_absolute_url(self): return reverse('detail', args=[str(self.id)]) # return reverse('home') form.py from django import forms from .models import Post, Category choices = Category.objects.all().values_list('name','name') choices_list = [] for item in choices: choices_list.append(item) class PostForm(forms.ModelForm): class Meta: model = Post fields = ('title', 'category', 'author','text') widgets={ 'title': forms.TextInput(attrs={'class':'form-control'}), 'category': forms.Select(choices=choices_list, attrs={'class':'form-control'}), 'author': forms.TextInput(attrs={'class':'form-control', 'id':'author'}), # 'author': forms.Select(attrs={'class':'form-control'}), 'text': forms.Textarea(attrs={'class':'form-control','placeholder':choices_list}), } class EditForm(forms.ModelForm): class Meta: model = Post fields … -
parsing queryset from html file in django project
I would like to be able to click on the link, and then add item=123 to the url. How can I do this? my urls.py urlpatterns = [ url(r'^filter/$', views.filter, name='filter22' ), url(r'^page/$', views.page, name='page') ] my views.py def page(request): return render(request, 'page.html') def filter(request): query = request.GET.get('item') article = Information.objects.get(title=query) return render(request, 'showing_articles/show_article.html', {'article': article}) my page.html {% extends 'base.html' %} {% block content%} <h1>Hoi</h1> <a href="{% url 'filter22' %}? " >Hoi </a> {% endblock %}} so in the html i want to pass the item=123 value so that it can be used in the function filter -
Django: split one model instance into two
I have a Django model Adventure with two datetime fields: from django.db import models class Adventure(models.Model): start_time = models.DateTimeField() end_time = models.DateTimeField() (...) There's an instance of Adventure, let's say: Adventure(start_time=TIME_1, end_time=TIME_2, ...) Assuming there is some TIME_X between TIME_1 and TIME_2 (TIME_1 < TIME_X < TIME_2), how can I split one Adventure object into two separate objects, so after splitting I would have: #first instance Adventure(start_time=TIME_1, end_time=TIME_X, ...) #second instance Adventure(start_time=TIME_X, end_time=TIME_2, ...) Adventure has more fields, which should be the same for both instances (except for PK, of course). -
django- how to render template for formset properly
I would like to create template with inline_formset. My parent element is customer and children elements are attachments which was sent by them. So I have to models: Customer, Attachment and inline_formset_factory For the time being I've got template as follows: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Adding new doc</title> </head> <body> <form action="" method="post"> {% csrf_token %} {{ form.as_table }} <br/><br/><br/> {{ formset }} <button type="submit">Submit</button> </form> </body> </html> And it looks like sh... I'm new in django and would like to give users better output. How can I render form and formset with table where labels and fields will be in separarte rows? -
Best method to write a model that adds a new entry and can correlate with the same primary key
Title probably won't make much sense, but here is what I am trying to achieve. I have a model called NewHandoff and 3 user groups that will be adding 'Observations'. These observations are captured in fields I have added to my NewHandoff model. For context, each day, the Shift 1 engineer creates a blank handoff. This will create the entry in the database. I then want engineers to be able to add notes in the handoff as their day progresses which will save as an individual record in the NewHandoff model - but I need those records to only be associated with that particular days handoff. My thought here is to add fields to the NewHandoff model like this: #Shift 1 Observations shift1_observation_title = models.CharField(max_length=1000) shift1_observation_detail = models.TextField #Shift 2 Observations shift2_observation_title = models.CharField(max_length=1000) shift2_observation_detail = models.TextField #Shift 3 Observations shift3_observation_title = models.CharField(max_length=1000) shift3_observation_detail = models.TextField My plan is to then create views for each shift based on the user group they are in so shifts could never possibly add Shift 2 Observations, if they happen to be on Shift 3 for example. My question here to the community is, am I doing this the best way I possibly can? … -
how to access request data sent as form-data to Django rest framework
I'm sending a POST request with a body as FormData from my flutter application to my Django backend.. the body has both MultiPart Files and String but when I try to access data in my backend some of them are not accessible .. here is my code : flutter form-data body FormData form = FormData({ "mobile_number": supplierMobileController.text, "password": supplierPasswordController.text, "firebase_token": "123456789", "main_user": { "username": supplierMobileController.text, "password": "123456789" }, "client_object": null, "supplier_object": { "personal_name": supplierPersonalNameController.text, "company_name": supplierCompanyNameController.text, "email": supplierEmailController.text, "established": supplierMonthController.text.length == 2 ? "${supplierYearController.text}-${supplierMonthController.text}-01" : "${supplierYearController.text}-0${supplierMonthController.text}-01", "number_of_projects": supplierNumberOfProjectsController.text, "tax_id": MultipartFile(File(imageOne.value), filename: "${supplierCompanyNameController.text}_tax_image.png"), "company_logo": MultipartFile(File(imageTwo.value), filename: "${supplierCompanyNameController.text}_logo_image.png"), "business_register": MultipartFile(File(imageThree.value), filename: "${supplierCompanyNameController.text}_business_image.png"), "company_text": "" }, }); and this is how am trying to access this data in the backend : Django Backend function @permission_classes(["AllowAny"]) @parser_classes(["JSONParser"]) @api_view(['POST']) def create_new_supplier(request): ''' Handles API call to create a new supplier ''' data = {} if request.method == 'POST': main_user_serializer = MainUserSerializer(data=request.data['main_user']) # causes an error main_user_serializer.is_valid(True) main_user_data = main_user_serializer.data app_user_serializer = AppUserSerializer(data=request.data) app_user_serializer.is_valid(True) validated_data = app_user_serializer.data supplier_serializer = models.Supplier(data=request.data['supplier_object']) supplier_serializer.is_valid(True) supplier_object_data = supplier_serializer.data main_user_object = User.objects.create_user(**main_user_data) app_user = models.AppUser.objects.create(**validated_data) token_object = Token.objects.create(user=main_user_object) supplier_object = models.Supplier.objects.create(**supplier_object_data) app_user.token = token_object app_user.client_object = None app_user.supplier_object = supplier_object app_user.main_user = main_user_object app_user.is_active = False app_user.save() data = { "success" … -
Error when trying to install Satchmo in Python
Im trying to install Satchmo to my Python project using pip install Satchmo and I encountred this error : Can anyone tell me what should I do ? -
how to use model.related_set.filter in django template tags
I have tried using model.related_set.get.id == Id but it only gets the first set in the related_set. I have tried using for loops so: {% for model in model.related_set %} {% if model.author_id == user %} <p>Success<p> {% else %} <p>Fail<p> {% endif %} {% endfor %} The above code works but the fail gets printed between the sucess how can i stop that Also i want another else for the forloop is it possible ? -
Django Serializer and Optional Recaptcha
I have the following serializer that i used for users signing up to the site. It takes in a recaptcha token and validates its not a spammer, returns error if issues. How can i used the same serializer without the recaptcha if I want to add a user internally, i.e. Our admin adds in back end and therefore Recapthca is not required. I get an error for not providing currently. class UserCreateSerializer(UserCreateSerializer): recaptcha = ReCaptchaV3Field(action="signup", required_score=0.6) class Meta(UserCreateSerializer.Meta): model = model = get_user_model() fields = ( "id", "first_name", "last_name", "email", "phone", "password", "recaptcha", ) def validate(self, attrs): if attrs.get("recaptcha"): attrs.pop("recaptcha") return attrs Its a custom user mode using Djoser to handle creation. -
How to autofill another input when the Foreign Key has been chosen?
I want to know how to use the foreign key as a dropdown list and autofill the another input when I choose the foreign key. The picture below show the solution that I want to slove The unsloved solution the code is below: class customer_detail(models.Model): Customer = models.CharField(max_length=10) Customer_Name = models.CharField(max_length=100) class Quotation(models.Model): Quatation_No = models.CharField(max_length=100) customer = models.ForeignKey(customer_detail, on_delete = models.CASCADE) customer_name = models.CharField(max_length=100, null=True, blank=True)