Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
TypeError: Cannot read properties of undefined (reading 'forEach') with ajax method
I have ajax funtion: <div class="quiz-box"></div> ... const url = window.location.href const quizBox = document.getElementById('quiz-box') let data $.ajax({ type: 'GET', url: `${url}data/`, success: function(response){ // console.log(response) data = response.data data.forEach(el => { for (const [question, answers] of Object.entries(el)){ quizBox.innerHTML = ` <b>${question}</b> ` } }); }, error: function(error){ console.log(error) }, }) Which gets data from django view. Now this results in an error in console: Uncaught TypeError: Cannot read properties of undefined (reading 'forEach') at Object.success at j at Object.fireWith [as resolveWith] at x at XMLHttpRequest.b Why is this error occuring and how can I prevent this? -
Page not found (404) No x matches the given query
I'm not sure of why I can't get the pk which I think it's the problem here. I am trying to do a like functionality to a product model, with a like the page would refresh and the result be shown but it does not save the like and the error Page not found (404) No Product matches the given query. My Model: class Product(models.Model): author = models.ForeignKey(User, default=None, on_delete=models.CASCADE) title = models.CharField(max_length=120, unique=True) likes = models.ManyToManyField(User, related_name='like') ... def number_of_likes(self): return self.likes.count() My views: class ProductDetailView(DetailView): model = Product template_name = 'services/product_detail.html' def get_context_data(self, **kwargs): data = super().get_context_data(**kwargs) likes_connected = get_object_or_404(Product, id=self.kwargs['pk']) liked = False if likes_connected.likes.filter(id=self.request.user.id).exists(): liked = True data['number_of_likes'] = likes_connected.number_of_likes() data['post_is_liked'] = liked return data def ProductLike(request, pk): post = get_object_or_404(Product, id=request.POST.get('product_id')) if post.likes.filter(id=request.user.id).exists(): post.likes.remove(request.user) else: post.likes.add(request.user) return HttpResponseRedirect(reverse('product-detail', args=[str(pk)])) My urls: path('product/<int:pk>/', ProductDetailView.as_view(), name='product-detail'), path('product-like/<int:pk>/', ProductLike, name="product_like"), My template: {% if user.is_authenticated %} <form action="{% url 'product_like' object.id %}" method="POST"> {% csrf_token %} {% if post_is_liked %} <button type="submit" name="blogpost_id" value="{{object.id}}" >Unlike</button> {% else %} <button type="submit" name="blogpost_id" value="{{object.id}}">Like</button> {% endif %} </form> {% else %} <a href="{% url 'login' %}?next={{request.path}}">Log in to like this article!</a><br> {% endif %} <strong>{{ number_of_likes }} Like{{ number_of_likes|pluralize }}</strong> -
Django not authenticating users made using shell
In my project I have an existing legacy database, so I use inspectdb to create models and for specific requirements I am using custom user model No when I create a user directly in the DB using SQL commands then the user gets authenticate and is able to login, but when I create user using SHELL commands (model_name.objects.create()), then the user is not authenticated and is not able to login. and the main point, ** when I create user using SQL command password is stored in RAW form (non-encrypted), but when I create user using SHELL commands the password is encrypted and it looks like "pbkdf2_sha256---------------------------------" managers.py #managers.py class UsermanagementCustomUserManager(BaseUserManager): def create_user(self,emailid,firstname, password=None): """ Creates and saves a User with the given email, date of birth and password. """ if not emailid: raise ValueError('Users must have an email address') user = self.model( emailid=self.normalize_email(emailid), password=password, ) user.set_password(password) user.save(using=self._db) return user backends.py #backends.py from django.contrib.auth.backends import BaseBackend from django.contrib.auth.hashers import make_password,check_password from django.contrib.auth import get_user_model Usermanagement = get_user_model() class EmailAuthBackend(BaseBackend): def authenticate(self,request,username=None,password=None): # print("Custom authenticate rqst: ",request) try: print("Trying the email backend!") user = Usermanagement.objects.get(emailid=username) print("Got the user") # print(password) # print(user.password) # print(check_password(password)) # print(user.check_password(password)) if user.password == password or user.check_password(password): … -
JWT Token authentication in github social authentication in Django(Note: Use django allauth)
In a django project i created a user login using github social authentication by using django allauth. i want to implement JWT token authentication in it. How can i do it? If any one have any idea please share. -
Best way to organize search results by location in a Django Rest Framework backend?
There are some naive ways to do this but I was wondering whether there is a more proficient way to achieve this functionality. I have a django rest framework backend and a react native front end. I have a table with objects that includes an Address object with the object's street address. What I would like to do is to return results sorted by distance from the user. Right now the database is small but soon we may have to paginate results. I have a couple of ideas but I'm wondering whether there is a cleaner way to accomplish this. For example the address field contains a lat/lng portion that is currently left blank, one idea is to populate this field on create/update operations using the google maps API geocoding functionality, then when the user makes a search request we order by l2 distance from their coordinates. One issue is that this could become very inefficient as the table grows larger. If we need O(N log N) operations every time the user is at a different location - even using tricks like caching. I know that some larger companies shard their database over regions to help with overhead in situations … -
ImportError: cannot import name 'Item' from partially initialized module 'core.models' (most likely due to a circular import)
Now, this is being a nuisance. It used to work before but now all of a sudden, it shows me this error. I know what circular imports mean but this used to work before. Now, the 'product' field gives me the problem. from django.db import models from appsystem.models import Outlet from core.models import Item, Supplier from location.models import Warehouse, Zone, Section, Level class MainPurchases(models.Model): METHOD_A = 'CASH' METHOD_B = 'CREDIT' PAYMENT_METHODS = [ (METHOD_A, 'CASH'), (METHOD_B, 'CREDIT'), ] product = models.ForeignKey(Item, on_delete=models.PROTECT) quantity = models.PositiveSmallIntegerField() purchase_price = models.DecimalField(max_digits=6, decimal_places=2) paid_amount = models.DecimalField(max_digits=6, decimal_places=2) date_created = models.DateTimeField(auto_now_add=True) supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE) outlet = models.ForeignKey(Outlet, on_delete=models.CASCADE, blank=True, null=True) payment_method = models.CharField(max_length=6, choices=PAYMENT_METHODS, default=METHOD_A) -
"POST / HTTP/1.1" 201 91 handleChange function is not updating the object's state
I am creating aa react js and django app for my school project.I am creating a form component that has an image field in it.The value entered from form is required to be posted on the django rest framework api that has been created.But the state is not being updated by handleChange function in the react component Null values from initial state are getting posted.I am a newbie.Please help! Image.js this.state = { floor_no:null, distance:null, area:null, no_of_rooms:null, price:null, images: null }; this.handleChange=this.handleChange.bind(this); this.handleImageChange=this.handleImageChange.bind(this); } handleChange = (e) => { this.setState({ [e.target.id]: e.target.value }) }; handleImageChange = (e) => { this.setState({ images:e.target.files[0] }) }; handleSubmit = (e) => { e.preventDefault(); console.log(this.state); let form_data = new FormData(); form_data.append('floor_no',this.state.floor_no); form_data.append('distance',this.state.distance); form_data.append('area',this.state.area); form_data.append('no_of_rooms',this.state.no_of_rooms); form_data.append('price',this.state.price); form_data.append('images',this.state.images,this.state.images.name); let url = 'http://localhost:8000/'; axios.post(url, form_data, { headers: { 'content-type': 'multipart/form-data' } }) .then(res => { console.log(res.data); }) .catch(err => console.log(err)) }; django rest framework all null values are being posted(from initial state) instead of the ones entered from the form. { "floor_no": null, "distance": null, "area": null, "no_of_rooms": null, "price": null, "images": null } -
Filter Django query by week of month?
In a Django query, how would you filter by a timestamp's week within a month? There's a built-in week accessor, but that refers to week-of-the-year, e.g. 1-52. As far as I can tell, there's no other built-in option. The only way I see to do this is to calculate the start and end date range for the week, and then filter on that using the conventional means. So I'm using a function like: def week_of_month_date(year, month, week): """ Returns the date of the first day in the week of the given date's month, where Monday is the first day of the week. e.g. week_of_month_date(year=2022, month=8, week=2) -> date(2022, 8, 7) """ assert 1 <= week <= 5 assert 1 <= month <= 12 for i in range(1, 32): dt = date(year, month, i) _week = week_of_month(dt) if _week == week: return dt and then to calculate for, say, the 3rd week of July, 2022, I'd do: start_date = week_of_month_date(2022, 7, 3) end_date = week_of_month_date(2022, 7, 3) + timedelta(days=7) qs = MyModel.objects.filter(created__gte=start_date, created__lte=end_date) Is there an easier or more efficient way to do this with the Django ORM or SQL? -
use db constraints to limit a foreign key to have only one boolean value false while others true
i am having a model below class MaintenancePersonnel(models.Model): performed_by=models.ForeignKey(User,on_delete=models.CASCADE) work_performed=models.ForeignKey(EquipmentMaintenanceSchedule,on_delete=models.CASCADE) comments=models.TextField(blank=True,null=True) is_performed=models.BooleanField(default=False) I want for a given work performed to have only one field that has is_performed False i have tried using condition but this seems to force only one model to have is_performed equal to false regardless of the work performed class Meta: constraints = [ models.UniqueConstraint(fields=['work_performed','is_performed'], condition=models.Q(is_performed=False), name='unique_is_performed_False') ] -
Use managers in Factory-Boy for models
Use Factory-boy for retrieve operation without use the DB for testing case. I have this simple model: class Student(models.Model): name = models.CharField(max_length=20) ` To get all: Student.objects.all() With Factory-boy: class StudentFactory(factory.django.DjangoModelFactory): class Meta: model = Student Is there a way to make StudentFactory.objects.all() ? When I call the method all() in my factory, I would like to return a list of QuerySet created by me. Example: [QuerySet_1, QuerySet_2] # Not Database. With that, I can change my data from DB to memory in my test. -
Django STL Viewer?
It is possible to use django build web 3D viewer? The idea is upload a stl and view on the bowser, and able to zoom pan rotate on the bowser. Please correct me Django is a backend we have develop this think on frontend correct? what should I use for that? -
Django: Efficiently updating many to many relation
Let's say we have a Django User with a lot of Groups. We want to update the groups with a new list of groups. A simple but not performant solution could be: def update_users_groups(new_groups: List[Group]): user.groups.clear() user.groups.set(new_groups) A little bit more performant solution is something similar to: def update_users_groups(new_groups: List[Group]): new_groups = set([x.id for x in new_groups]) old_groups = set([x.id for x in user.groups.all()]) groups_to_add = new_groups - old_groups if groups_to_add: user.groups.add(*groups_to_add) groups_to_remove = old_groups - new_groups if groups_to_remove: user.groups.remove(*groups_to_remove) I could not find any hints in the documentation for a built-in method. Is there some best practice or any way I could improve my example from above? Maybe even s.o. has an idea for a more performant solution. Thank you in advance! -
Django not installed vcvarsall.bat
Whenever i try installing django with pip it says Microsoft visual c++ required (unable to find vcvarsall. Bat) I added vs build tools in path but still nothing -
How to add captcha in django website in html form instead of forms.py
I have django application with authentication and I want to add captcha to it. I heard about django-simple-captcha and reCaptcha but both of them are added through forms.py. I want a solution in which I can add captcha without writing forms.py. Is there any way possible? -
How to validate fields with foreign keys in serializers context?
I'm working on some validations, and I want to check whether the requesterid entered is referencing to a userroleid value of "3" from userTable model. If it doesn't meet the criteria, it will raise a validation error. How can I access a field from a referenced table? What I have tried is something like request = self.context.get("requesterid__userroleid") but it doesn't validate correctly. Do you have any idea on how to do this? Here's my serializers: class RequestCreateSerializer(serializers.ModelSerializer): parts=PartSerializer(many=True) class Meta: model = requestTable fields = ['rid', 'requesterid', (...)] def create(self, validated_data): (...) def validate(self, data): request = self.context.get("requesterid__userroleid") #how to access userroleid? if request == 3: return data raise serializers.ValidationError("Sorry! Your role has no permission to create a request.") Here's my views: class RequestListCreateView(ListCreateAPIView): queryset = requestTable.objects.all() serializer_class = RequestCreateSerializer def create(self, request, *args, **kwargs): (...) def get_serializer(self, *args, **kwargs): serializer_class = self.get_serializer_class() kwargs['context'] = self.get_serializer_context() return serializer_class(*args, **kwargs) def get_serializer_context(self): return { 'request': self.request, 'format': self.format_kwarg, 'view': self } Here's my models: class requestTable(models.Model): rid = models.AutoField(primary_key=True) requesterid = models.ForeignKey(userTable, on_delete=models.CASCADE) (...) class userTable(models.Model): userid = models.UUIDField(primary_key=True, default = uuid.uuid4, editable=False) userroleid = models.ForeignKey(roleTable, on_delete=models.CASCADE) class roleTable(models.Model): roleid = models.IntegerField(null=False, primary_key=True) role = models.CharField(max_length=255, null=False) -
Django - show bootstrap modal after successful save data to db
I'm new to Django and at this point , i set up a very simple post article page, i hope that when i successfully save the article, it will show the message of the bootstrap modal style model.py from django.db import models from django.utils import timezone class Article(models.Model): title = models.CharField(max_length=100,blank=False,null=False) slug = models.SlugField() content = models.TextField() cuser = models.CharField(max_length=100) cdate = models.DateField(auto_now_add=True) mdate = models.DateField(auto_now=True) forms.py from .models import Article from django.forms import ModelForm class ArticleModelForm(ModelForm): class Meta: model = Article fields = [ 'title', 'content', ] views.py from django.shortcuts import render from .forms import ArticleModelForm from django.contrib.auth.decorators import login_required from .models import Article @login_required def create_view(request): form = ArticleModelForm(request.POST or None) context={ 'form':form } if form.is_valid(): article_obj = Article(cuser=request.user) form = ArticleModelForm(request.POST,instance=article_obj) form.save() context['saved']=True context['form']=ArticleModelForm() return render(request,'article/create.html',context= context) my template > article/create.html {% extends 'base.html' %} {% block content %} <form method="POST"> {% csrf_token %} {{form.as_p}} <div><button data-bs-toggle="modal" data-bs-target="#saveModal" type="submit">create</button></div> </form> {% if saved %} <div class="modal fade" id="saveModal"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h3>save successfully!</h3> <button type="button" class="btn-close" data-bs-dismiss="modal"> </button> </div> </div> </div> </div> {% endif %} {% endblock content %} I use the saved variable in views.py to determine whether the content of the article … -
Is there a Python function I can use for a condition like "If condition is still true after (3) seconds then dosomething"(
I am running a opencv through django and trying to save the data in sqlite. I tried to use the sleep() in library time, but it only prevents my web app from running. color = (0, 0, 255) time.sleep(3) if color == (0, 0, 255): save time -
Django - get original object values in form_valid for UpdateView?
Using Django's UpdateView, I'm looking to update a version number if certain fields in the form.instance are actually updated. This requires comparing the values of these fields to the original value before the user set the updated value. In form_valid, is it possible to access the original object's values before the updating occurred? -
Django: usage of prefetch_related
I have some models with this relation: EmailReport --many-to-many--> PaymentReport --foreign-key--> Shop --many-to-many--> users Now I want to reach the users from EmailReport. I tried this query but failed: query = models.EmailReport.objects.prefetch_related('payment_report').prefetch_related('shop__users').filter(pk__in=ids) Anyone knows the correct query? -
JSONDecodeError when using json.loads
I am getting Expecting value: line 1 column 1 (char 0) when trying to use json.loads Went through similar questions but couldn't find a solution for my code. It gives the error for line: body = json.loads(body_unicode) network.js: //When user clicks the save button save_button.addEventListener("click", event => { new_content = document.getElementByID(`new_content_${postID}`); //Make fetch request to update the page fetch(`/edit/${postID}`,{ method: "POST", body: JSON.stringify({ content: new_content.value, }) }) .then(response => { if(response.ok || response.status == 400) { return response.json() } else { return.Promise.reject("Error:" + response.status) } }) .then(result => { new_content.innerHTML = result.content; cancelEdit(postID); }) .catch(error => { console.error(error); }) }) views.py: def edit(request, id): if request.method == "POST": body_unicode = request.body.decode('utf-8') body = json.loads(body_unicode) new_content = body['content'] AllPost.objects.filter(id = id).update(content = new_content) return JsonResponse({"message": "Post updated successfully.", "content": new_content}, status=200) return JsonResponse({"error": "Bad Request"}, status = 400) index.html: {% for post in page_obj %} {{ post.full_name|upper }}<br> <div class="frame"> <h4><a href="{% url 'profile' post.user.username %}" style="color: black;">{{post.user.username}}</a></h4> {% if post.user == user %} <button class="btn btn-sm btn-outline-primary" data-id="{{post.id}}" id="edit_button_{{post.id}}">Edit</button> {% endif %} <div id="content_{{post.id}}">{{post.content}}</div> <form action="{% url 'edit' post.id %}" method="post" id="edit_form_{{post.id}}" style="display: none;"> {% csrf_token %} <div class="form-group"><textarea id="new_content_{{post.id}}" name="new_content" cols="30"></textarea></div> <input class="btn btn-sm btn-success" id="save_{{post.id}}" type="submit" value="Save"> <input … -
How to access foreignkey table fields in template using django
` models.py class Locations(models.Model): region = models.ForeignKey(Regions, on_delete=models.CASCADE,blank=True,null=True) name = models.CharField(max_length=255) class Regions(models.Model): region_name = models.CharField(max_length=255) serializer.py class LocationsSerializer(serializers.ModelSerializer): region = RegionSerializer() class Meta: model = Locations fields = "__all__" views.py def loc_reg(request): locations = Locations.objects.select_related('region').values('name','region__region_name') data = LocationSerializer(locations,many=True) return response.Response(data,status.HTTP_200_OK) template: <script> methods:{ fetchList(){ this.$axios.$post('/projects/loc_reg',config).then(response => { if(response){ this.locations =response.data; for(let i=0;i <this.locations.length; i++){ this.x=this.locations[i].name this.y=this.locations[i].region_name this.z=this.y + "-" +this.x this.result.push(this.z) } </script> After serialization I am getting null value in region_name. I am getting null in my template while try to get region_name.why so?`` -
how to resize an image and save it to storage using save function
how can i modify my save function to solve this problem ? i have a storage and when i wanted to upload an image i encountered this error . -
Django how to get days count of month in specific year [duplicate]
class MainYear(models.Model): year = models.CharField(max_length=4,blank=True,null=True,default=get_current_year()) def __str__(self): return str(self.year) @property def get_all_month(self): return self.MainMonth.all() def get_absolute_url(self): return reverse("agenda:ajax_month", kwargs={"pk": self.id}) class MainMonth(models.Model): main_year = models.ForeignKey(MainYear,on_delete=models.CASCADE,blank=True,null=True,related_name="MainYear") month = models.PositiveSmallIntegerField (validators=[MaxValueValidator(12)],default=1,blank=True,null=True) day_count = models.PositiveSmallIntegerField (validators=[MaxValueValidator(31)],blank=True,null=True) def __str__(self): return str(self.month) @property def get_day_count(self): # year = self.__main_year.year() year = self.objects.all().filter(main_year__MainYear_year='MainYear_year') for y in year: yea_to_days = self.year # You already have it days_count = monthrange(int(yea_to_days),int(self.month))[1] self.day_count = days_count return self.day_count My problem is i want if i select year like 2024 it should be in February 29 days how to make it i will be save it auto by using save method django python year month days -
how to implement autocomplete Search bar for a table in django
if i have a table of 4 team(python, java, php, ruby) and each team have 4 project then i searched py for python team in search bar and each bar show team name and then i select python then it filter the table and shows python team projects this is api `def searchteam_name(request): if request.method == 'GET': filterData2 = request.GET.get("query") try: u = TeamAndManager.objects.filter(name__istartswith = filterData2)#.filter(team__name = url[0]) print('<<<<<99999999999999999999>>>',u) except: print('<<<<<<<88888888>>>>>') pass if len(u) > 0: d = {} count = 0 for i in u: team_addon = {f'{count}' : f'{i.name}'} count = count +1 d.update(team_addon) else: d = { '0' : 'No Team Found' } return JsonResponse(d)` model.py `class TeamAndManager(models.Model): name = models.CharField(max_length=20,blank=False, null=False) manager = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return '{} : {}'.format(self.name, self.manager)` -
how to hide some field based on the forms.select django
i want to hide some fiel when the user will select an option, but when i'm trying to do so, it does not work, i don't know if i forget something in my code or if i make a mistake but i've tried many things and it does not work in my model i have a choices with "IN" and "Out" so what i want is when OUT is selected some field of my forms to be hidden, else to show the whole form. here is my model.py CHOICES = ( ("1", "IN"), ("2", "OUT") ) class addReport(models.Model): heure = models.TimeField(auto_now_add=True) mouve = models.CharField(max_length=12, choices = CHOICES) nom_Visiteur = models.CharField(max_length=26) fonction = models.CharField(max_length=26) service = models.CharField(max_length=26) motif = models.CharField(max_length=26) phoneNumber = models.CharField(max_length=12, unique= True) here is my forms.py from django import forms from .models import addReport from django.forms import ModelForm class PostForms(forms.ModelForm): class Meta: model = addReport fields = ('mouve','nom_Visiteur','fonction','service','motif','phoneNumber') widgets = { 'mouve': forms.Select(attrs={'class': 'form-control'}), 'nom_Visiteur': forms.TextInput(attrs={'class': 'form-control'}), 'fonction': forms.TextInput(attrs={'class': 'form-control'}), 'service': forms.TextInput(attrs={'class': 'form-control'}), 'motif': forms.Textarea(attrs={'class': 'form-control'}), 'phoneNumber': forms.TextInput(attrs={'class': 'form-control'}), } def __init__(self, data=None, *args, **kwargs): super().__init__(data, *args, **kwargs) # If 'later' is chosen, mark send_dt as required. if data and data.get('mouve', None) == self.OUT: self.fields['fonction'] = forms.HiddenInput(), self.fields['service'] …