Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
In my Django project I have two similar url
I have a question with my sites urls. When someone want to go mysite.com I redirect them to mysite.com/register. url(r'^$', RedirectView.as_view(url='register/', permanent=False), name='index'), url(r'^register/',views.guaform2,name='custform2'), Also I have another url that allows to write somethings after the part of register. For example when someone goes to this website mysite.com/register/kh-54-m2-fc it allows to go that: url(r'^register/(?P<pk>[-\w]+)',views.guaform,name='custform'), But when I use these urls together my guaform view doesn't work. And it goes to customer_form2.html. When someone goes this site: mysite.com/register/ anything I want them go to customer_form.html. How can I seperate these urls? urls.py from django.conf.urls import url from django.contrib import admin from olvapp import views from django.views.generic import RedirectView urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', RedirectView.as_view(url='register/', permanent=False), name='index'), url(r'^register/',views.guaform2,name='custform2'), url(r'^register/(?P<pk>[-\w]+)',views.guaform,name='custform'), ] views.py from django.shortcuts import render,HttpResponse from olvapp.models import Customer from olvapp.forms import CustomerForm,CustomerForm2 from django.conf import settings from django.http import HttpResponseRedirect from django.urls import reverse from olvapp import forms def guaform(request,pk): theurl = request.get_full_path() orderid = theurl[10:] form = CustomerForm(initial={'order_id':orderid}) if request.method == "POST": form = CustomerForm(request.POST) if form.is_valid(): form.save(commit=True) return HttpResponseRedirect(reverse('thank')) else: HttpResponse("Error from invalid") return render(request,'customer_form.html',{'form':form}) def guaform2(request): form = CustomerForm2() if request.method == "POST": form = CustomerForm2(request.POST) if form.is_valid(): form.save(commit=True) return HttpResponseRedirect(reverse('thank')) else: HttpResponse("Error from invalid") return render(request,'customer_form2.html',{'form':form}) -
Django DecimalRangeField form validation will only accept whole numbers
All of my DecimalRangeField fields work as expected when changing values in admin but my form won't accept non-whole numbers: Interestingly, if I set the lower default value as a non-whole number, the validation tries to force any whole number added to the lowest default. For example, if I define a field like this in models.py: my_field= DecimalRangeField( blank=True, default=(0.05, 5), validators=[RangeMinValueValidator(0.05), RangeMaxValueValidator(5)], ) I get the following warning: Maybe I am missing something in the field definition or there is something I don't understand about how Django converts the input into a decimal but I've not been able to find anything online about this. Any help would be greatly appreciated :) -
pytest + django giving me a database error when fixture scope is 'module'
I have the following inside conftest.py @pytest.mark.django_db @pytest.fixture(scope='module') def thing(): print('sleeping') # represents a very expensive function that i want to only ever once once per module Thing.objects.create(thing='hello') Thing.objects.create(thing='hello') Thing.objects.create(thing='hello') Inside tests.py @pytest.mark.django_db def test_thing(thing): assert models.Thing.objects.count() > 1 @pytest.mark.django_db def test_thing2(thing): assert models.Thing.objects.count() > 1 @pytest.mark.django_db @pytest.mark.usefixtures('thing') def test_thing3(): assert models.Thing.objects.count() > 1 All three tests throw the same error: RuntimeError: Database access not allowed, use the "django_db" mark, or the "db" or "transactional_db" fixtures to enable it. I've tried using scope='session' / scope='class' / scope='package' / scope='module' -- the only one that works is `scope='function' which defeats the purpose of what I'm trying to accomplish. I want to be able to create all these items ONCE per module, not once per test. Note: I ran into this issue with a large code base and created a new django project with a single app to test and see if the problem was the existing test code, and it failed on a standalone test also. Not that it matters, but the models.py class Thing(models.Model): thing = models.CharField(max_length=100) -
Reverse for 'profile_info_update' with arguments '(None,)' not found. 1 pattern(s) tried: ['profile_info_update/(?P<pk>[0-9]+)$']
It is basically an e-Commerce website. Everything working perfectly but When I log out then occurs the below error. What will be the relevant solution? NoReverseMatch at / Reverse for 'profile_info_update' with arguments '(None,)' not found. 1 pattern(s) tried: ['profile_info_update/(?P<pk>[0-9]+)$'] Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 3.2.3 Exception Type: NoReverseMatch Exception Value: Reverse for 'profile_info_update' with arguments '(None,)' not found. 1 pattern(s) tried: ['profile_info_update/(?P<pk>[0-9]+)$'] Exception Location: C:\Users\DCL\AppData\Local\Programs\Python\Python39\lib\site-packages\django\urls\resolvers.py, line 694, in _reverse_with_prefix Python Executable: C:\Users\DCL\AppData\Local\Programs\Python\Python39\python.exe Python Version: 3.9.5 Python Path: ['D:\\1_WebDevelopment\\Business_Website', 'C:\\Users\\DCL\\AppData\\Local\\Programs\\Python\\Python39\\python39.zip', 'C:\\Users\\DCL\\AppData\\Local\\Programs\\Python\\Python39\\DLLs', 'C:\\Users\\DCL\\AppData\\Local\\Programs\\Python\\Python39\\lib', 'C:\\Users\\DCL\\AppData\\Local\\Programs\\Python\\Python39', 'C:\\Users\\DCL\\AppData\\Roaming\\Python\\Python39\\site-packages', 'C:\\Users\\DCL\\AppData\\Roaming\\Python\\Python39\\site-packages\\win32', 'C:\\Users\\DCL\\AppData\\Roaming\\Python\\Python39\\site-packages\\win32\\lib', 'C:\\Users\\DCL\\AppData\\Roaming\\Python\\Python39\\site-packages\\Pythonwin', 'C:\\Users\\DCL\\AppData\\Local\\Programs\\Python\\Python39\\lib\\site-packages'] Server time: Mon, 16 May 2022 15:31:17 +0000 template: <a href="{% url 'profile_info_update' user.pk %}" class="edit_btn btn"> edit </a> urls.py: path('profile_info_update/<int:pk>', views.profile_info_update.as_view(), name="profile_info_update") views: class profile_info_update(UpdateView): model = User from_class = change_profile_info fields = 'first_name','last_name','email' template_name = '33_change_profile_info.html' success_url =("/") forms.py: class change_profile_info(forms.ModelForm): first_name = forms.CharField(widget=forms.FileInput(attrs={'class':"form-control"})) last_name = forms.CharField(widget=forms.FileInput(attrs={'class':"form-control"})) email = forms.EmailField(widget=forms.FileInput(attrs={'class':"form-control"})) class Meta: model = User fields = ('first_name','last_name','email',) -
Django update_or_create()
I'm trying to use Django update_or_create() but I could not pass the pk (obj_key) to defaults. The idea is filter by user_id and wallet_id and update if exist or create if not. class ModelSelectedWallet(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) wallet = models.name = models.ForeignKey(ModelWallet, default=1, on_delete=models.CASCADE) created = models.DateField(verbose_name='Created', auto_now_add=True) modified = models.DateField(verbose_name='Modified', auto_now=True) created_by = models.ForeignKey('auth.User', related_name='selected_wallet_created_by', blank=True, null=True, default=None, on_delete=models.SET_DEFAULT) modified_by = models.ForeignKey('auth.User', related_name='selected_wallet_modified_by', blank=True, null=True, default=None, on_delete=models.SET_DEFAULT) def select_wallet(request): if request.method == "POST": wallet_id = request.POST['wallet_id'] user = get_current_user() user_id = user.id db = ModelSelectedWallet obj_key = db.objects.filter(user_id__exact=user_id, wallet_id__exact=wallet_id).values('id')[0]['id'] defaults = {'id': obj_key} try: obj = db.objects.get(user_id=user_id, wallet_id=wallet_id) for key, value in defaults.items(): setattr(obj, key, value) obj.save() except db.DoesNotExist: new_values = { 'created': datetime.datetime.now().strftime ("%Y-%m-%d"), 'created_by_id': user_id, 'modified_by_id': user_id, 'wallet_id': wallet_id, 'user_id': user_id } new_values.update(defaults) obj = db(**new_values) obj.save() -
Django view. Upload/modify one CSV/Download modified csv
i'm trying to create and API for some validation: I want to have a option to upload one CSV. I want to pass that CSV through some validations, to modify the original CSV (to add 2 new columns) I want to have a posibility to download the modified CSV (with my 2 new columns) I implemented the first part, i created the validation, but after i download, i've got the same output (file wasn't modified) Could anyone help me with this part pls? This is my code for my view: def upload(request): context = {} if request.method == 'POST': promo2 = request.FILES['document'] if request.method == 'GET': promo2 = promo2[~promo2['COMP_ARTICLE_PROMO_TYPE'].isna()] for index, row in promo2.iterrows(): promo2 = pd.read_csv(promo2, sep=';') if (row['COMP_ARTICLE_PROMO_NAME'] == '-20%') or (row['COMP_ARTICLE_PROMO_NAME'] == '20.0% korting'): if 0.95 < round(row['COMP_ART_PRICE'] * 0.80, 2) / row['COMP_ARTICLE_PROMO_PRICE_PER_UNIT'] < 1.05: promo2.loc[index, 'VALIDATE_ARTICLE_PROMO_PRICE_PER_UNIT'] = 'GOOD' else: promo2.loc[index, 'VALIDATE_ARTICLE_PROMO_PRICE_PER_UNIT'] = 'WRONG' if (row['COMP_ARTICLE_PROMO_NAME'] == '-20%') or (row['COMP_ARTICLE_PROMO_NAME'] == '20.0% korting'): if row['COMP_ARTICLE_PROMO_PERCENT'] == 20: promo2.loc[index, 'VALIDATE_ARTICLE_PROMO_PERCENT'] = 'GOOD' else: promo2.loc[index, 'VALIDATE_ARTICLE_PROMO_PERCENT'] = 'WRONG' #fs = FileSystemStorage() #name = fs.save(promo2.name, promo2) #context['url'] = fs.url(name) #promo2.to_excel(response, engine='xlsxwriter', index=False) fs = FileSystemStorage() name = fs.save(promo2.name, promo2) context['url'] = fs.url(name) return render(request, 'upload.html', context) Here is my front … -
Django-rest-framework - fetching data from another server's DB
I made with Django REST Framework an API that i use for my project which is a Flutter app. *BUT, i want to add some data from another Server's database, can i do it in Django REST Framework, and then include those in my API ? -
How to differentiate access to data at the database server level?
In DB i have three roles: guest, client and admin. In my django project, there are three connections under these roles DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'test', 'USER': 'guest', 'PASSWORD': 'guest', 'HOST': 'localhost', 'PORT': 5432, }, 'admin': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'test', 'USER': 'admin', 'PASSWORD': 'admin', 'HOST': 'localhost', 'PORT': 5432, }, 'customer': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'test', 'USER': 'customer', 'PASSWORD': 'customer', 'HOST': 'localhost', 'PORT': 5432, } } How and where can I change the connection to the database depending on whether the user is authenticated or not? -
DJANGO FORM - how to change save location file uploaded
i don't use models form but only form. How to change location file when i uploaded? i want the file just go to /mp3 folder. And now i got error : UnboundLocalError at / local variable 'form' referenced before assignment and this my code : def homepage(request): if request.method == "POST": form = Audio_store(request.POST, request.FILES) # form = AudioForm(request.POST, request.FILES) if form.is_valid(): handle_uploaded_file(request.FILES['record']) return HttpResponseRedirect('mp3/') return render(request, "homepage.html", {'form': form}) forms.py : from django import forms class Audio_store(forms.Form): record=forms.FileField() and my error msg : my folder: -
How to get the data associated with a checkbox in Django views
I have a database that I'm trying to access via a template in Django. I'd like to be able to select some checkboxes and have it return the items associated with those checkboxes in my views.py so I can perform some logic on that data. template.py <input type="checkbox" checked autocomplete="off" name="tag" value={{ recipe.id }} />{{ recipe }} views.py def create_list(request): check_values = request.POST.getlist('tag') context = {'check_values': check_values) return render(request, 'grocery_lists/create_list.html', context) The create_list.html page simply displays {{ check_values }}. This was my attempt at a troubleshooting step so I could see what was stored in the variable check_values, However, check_values ends up being an empty list. I'm having trouble finding a solution that fits my use case. Thank you in advance. -
Django DRF - Updating many-to-one model in serializer
My models structure is pretty straightforward: a many to one relationship where a set of Conditions references one Item by the foreign key. And here we have the corresponding serializers.py: class ConditionSerializer(serializers.ModelSerializer): class Meta: model = Condition fields = ('condition_id','name', 'left', 'operator', 'right') class ItemSerializer(serializers.ModelSerializer): conditions = ConditionSerializer(many=True, read_only=True) def create(self, validated_data): conditions_data = validated_data.pop("conditions") item = Item.objects.create(**validated_data) for condition_data in conditions_data: Condition.objects.create(item=item, **condition_data) return item def update(self, instance, validated_data): instance.name = validated_data.get('name', instance.name) conditions_data = validated_data.get('conditions', instance.conditions) for c in conditions_data.all(): print(c.name) # it correctly prints out the value instance.conditions.set(conditions_data.all()) # Doesn't update the instance instance.save() return instance class Meta: model = Item fields = ('item_id', 'name', 'conditions') The problem is in the update function: instance.name is correctly updated; instance.conditions.set(conditions_data.all()) is not. No error is displayed, since the response is 200OK. I also put the for loop printing of field of the Condition object (name) and it successfully is displayed, showing that the data is correctly read. I've tried to address the issue removing the read_only=True from the ConditionSerializer, but the situation got worse since I receive the error: AttributeError: 'list' object has no attribute 'all' Maybe the issue is related to the foreign key management. Is there a … -
The view shopping_mall.views.add_comment didn't return an HttpResponse object. It returned None instead
How can i fix it? ERROR MESSAGE The view shopping_mall.views.add_comment didn't return an HttpResponse object. It returned None instead. My Views.py def add_comment(request, pk): post = ProductList.objects.get(pk=pk) if request.method == "POST": form = CommentFrom(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.author = request.user comment.product = post comment.save() return redirect('index', pk=post.pk) else: form = CommentFrom() return render(request, 'shopping_mall/add_comment.html', {'form':form}) My urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('top_cloth/', views.top_cloth), path('top_cloth/<int:pk>/', views.cloth_detail, name='top_cloth_pk'), path('top_cloth/<int:pk>/comment/', views.add_comment, name='add_comment'), path('top_cloth/<int:pk>/remove/', views.comment_remove, name='comment_remove'), path('top_cloth/<int:pk>/modify/', views.comment_modify, name='comment_modify'), ] -
Django's `date_hierarchy` not showing the correct date in filters
I have date_hierarchy on a date field in my ModelAdmin. The day filters at the top don't match the actual dates in the list. For example, when I click "May 16", it doesn't show any results (the dates only go up to May 15). Is this the expected behavior? My guess is there's something going on with UTC time vs timezone, but I'm not sure why. -
Django Application verify user can only see items relevant to them
My issue is that I can list all the clients in the database and these occur on all account managers detail pages. What I want to achieve is to list only those clients that appear for a specific account manager but to date everything I have tried does not work. This is the Client Model: class Client(models.Model): client_name = models.CharField(max_length=255) account_manager = models.ForeignKey( AccountManager, on_delete=models.CASCADE, related_name="clients", ) My views.py currently looks like this: class AccountManagerDetailView(LoginRequiredMixin, DetailView): model = AccountManager template_name = "accountmanagers/dashboard.html" context_object_name = "ams" def get_object(self, *args, **kwargs): return self.request.user def get_context_data(self, **kwargs): # Call the base implementation first to get a context context = super().get_context_data(**kwargs) context["clients"] = Client.objects.all() return context And my urls.py urlpatterns = [ path("detail", views.AccountManagerDetailView.as_view(), name="detail"), ] -
access form from another funcion
Question is.. I have static page profil.py: def profil(request, pk): context = {} person = User.objects.get(id=pk) try: person.profesor except Profesor.DoesNotExist: context['ucenik'] = Ucenik.objects.get(id=person.ucenik.id) else: context['profesor'] = Profesor.objects.get(id=person.profesor.id) return render(request, "profil.html", context) and this: def profesor(request): profesor = request.user.profesor forma = ProfesorFormaSlika(instance=profesor) context = {'forma':forma} return render(request, 'pocetna_profesor.html', context) question is, how can i access {{ forma }} in HTML page from def profesor in def profil? -
What does reset password token protect against?
This is more of a concept question than a specific code one. I am building a web app in Django which almost entirely handles the password reset process. And it had me thinking what does the token do, I'm aware that it checks whether the same email that requested the reset is the one changing the password. But why is this needed If someone tried to send a reset email to someone elses email they would need that emails password to actually change it. Is the token just another layer of protection? Is it necessary? I also do not understand the way django handles it: path('password-reset-confirm/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view( template_name='users/password_reset_confirm.html' ), How does passing the token in here, which is the page you access when the reset email is sent to YOU, make it secure. The latter question isnt as important. -
How to fill 'initial value' in Django forms with current user data?
I went ahead and created a Form to update the user database entry. class UserUpdateForm(forms.ModelForm): class Meta: model = User fields = ("username", "first_name", "last_name", "email") But when I render the form all input fields are empty. How do I populate them with the user's data like current username and email? I use Bootstrap 5 to style it, but that should matter: <div class="mb-3"> <label for="{{ form.first_name.id_for_label }}" class="form-label">{{ form.first_name.label }}</label> {{ form.first_name|addcss:"form-control"}} </div> Problem is, I render the input field with the Django template engine and don't specifiy it myself. My idea was to chain template filters: <div class="mb-3"> <label for="{{ form.username.id_for_label }}" class="form-label">{{ form.username.label }}</label> {{ form.username|addcss:"form-control"|addplaceholder:user.username}} </div> But that didn't work because the first filter converts it to a widget: @register.filter(name="addcss") def addcss(field, css): return field.as_widget(attrs={"class": css}) Maybe you can recommend me a way on how to modify that filter or tell me a complety different approach. -
How can i change a field based on another m2m field?
So, what i'm tryna do here is set the status of an object based on the length of m2m field. Here's how it looks from django.db import models class Dependency(models.Model): dependency = models.SlugField('Шаблон') class Seo(models.Model): statuses = ( (1, 'Дефолтный'), (2, 'Дополнительный') ) dependencies = models.ManyToManyField( Dependency, verbose_name='Зависимости', blank=True, help_text='Оставьте пустым, если это дефолтный шаблон' ) h1 = models.CharField('Заголовок(h1)', max_length=200) title = models.CharField('Заголовок(title)', max_length=200) description = models.CharField('Описание', max_length=200) keywords = models.TextField('Ключевые слова') status = models.IntegerField('Статус', choices=statuses, blank=True, editable=False) def save(self, *args, **kwargs): if len(self.dependencies) == 0: self.status = 1 else: self.status = 2 # self.status = 1 # # print(len(self.dependencies)) super().save(*args, **kwargs) class Page(models.Model): pass But it throws me an error that goes like ValueError: "<Seo: Seo object (None)>" needs to have a value for field "id" before this many-to-many relationship can be used. And what it want to achieve is whenever the dependency field is empty then status should be 1 and otherwise it should be 2. But i couldn't find a way to do it. -
How to query the existence of related objects that are successive in time?
My Blog model has a has two types of comments, blue ones and red ones. I would like to find all blogs that have posts that are blue directly followed by posts that are red. Here, "followed by" is meant in terms of a timestamp field "created_at". How can I filter my blogs by this property? class Comment(Model): color = Charfield(max_length=100) created_at = DateTimeField() blog = ForeignKey(Blog, related_name="comments") class Blog(Model): ... My attempt is: blue_comments = Comment.objects.filter(blog=OuterRef("pk"), color="blue") red_comments = Comment.objects.filter(blog=OuterRef("pk"), color="red") blogs = Blog.objects.filter(Exists(blue_comments), Exists(red_comments)).all() I don't know how to filter for the condition that the "created_at" fields must be successive. -
Add properties to a model from a different app in django? (extend model from different app)
I've got an app (named essence) that I use in multiple projects (it's a shared app with just a User model and a Location model that get used in multiple projects I have) The Location model looks something like this: class Location(models.Model): name = models.CharField(max_length=50) alternate_location_id = models.IntegerField() class Meta(object): ordering = ["name"] def __str__(self): return self.name Currently I have a function that takes a queryset of locations, iterates across it and creates a dictionary for each location with the needed data. But that is causing a lot of extra queries I'd like to avoid. So I'm trying to see if I can dynamically add properties to the Location model from the positions app. The function returns a dictionary that looks like this: { "location_id": location.id, "location_name": location.name, "alternate_location_id": location.alternate_location_id, "location_current_position_count": position_count, "location_current_position_average": position_average, "location_change": location_position_change, } The three variables listed in that dictionary (position_count, position_average and location_position_change) are figured out using various queries of other related models in the function (which are not using aggregate/annotate, but could/should be - hence my refactoring now) I would like to get rid of that function and just make those other variables attributes/properties on the Location model itself so I'm not having to … -
SQL - How to get rows within a date period that are within another date period?
I have the following table in the DDBB: On the other side, i have an interface with an start and end filter parameters. So i want to understand how to query the table to only get the data from the table which period are within the values introduces by the user. i.e If the users only defines start = 03/01/2021, then the expected output should be rows with id 3,5 and 6. if the users only defines end = 03/01/2021, then the expected output shoud be rows with id 1 and 2. if the users defines start =03/01/2021 and end=05/01/2021 then the expected output should be rows with id 3 and 5. Hope that makes sense. Thanks -
Use different models for user and superuser in django
I have a Student model and I will also be creating another model called Teacher. But I want a single model called Admin to be the superuser for both of these models in their respective managers. How do I achieve this? Here's the code I have so far: class StudentManager(BaseUserManager): def create_user(self, usn, email, first_name, last_name, initials, branch, **extra_fields): if not email: raise ValueError('Email for user must be set.') email = self.normalize_email(email) user = self.model( usn=usn, email=email, first_name=first_name, last_name=last_name, initials=initials, branch=branch, **extra_fields) user.set_password('password') user.save() return user def create_superuser(self, name, email, **extra_fields): if not email: raise ValueError('Email for user must be set.') email = self.normalize_email(email) admin = self.model( # but self.model refers to Student, not Admin email=email, name=name, **extra_fields) admin.set_password('password') admin.save() return admin class Student(AbstractBaseUser, PermissionsMixin): usn = models.CharField(max_length=10, primary_key=True, unique=True, editable=False) email = models.EmailField(max_length=254, unique=True) first_name = models.CharField(max_length=50, null=False) last_name = models.CharField(max_length=50, null=False) initials = models.CharField(max_length=10, null=True) branch = models.CharField(max_length=5, null=False, editable=False) objects = StudentManager() USERNAME_FIELD = 'usn' EMAIL_FIELD = 'email' REQUIRED_FIELDS = ['email', 'first_name', 'last_name', 'branch'] class Admin(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=254, unique=True) name = models.CharField(max_length=100, null=False) # objects = StudentManager() USERNAME_FIELD = 'name' EMAIL_FIELD = 'email' REQUIRED_FIELDS = ['email', 'name'] And here's the error I get: api.Admin.groups: (fields.E304) … -
Sorting and filtering django model objects by foreign key values
so i was given a test for an interview and trying to figure out the best way to implement this: Lets say we have a django project. With models: Rental name Reservation rental_id checkin(date) checkout(date) Add the view with the table of Reservations with "previous reservation ID". Previous reservation is a reservation that is before the current one into same rental. so i tried implementing something that actually works, but i just feel i have ignored alot of good practices just to get the work done, I will appreciate some insights/tips on how i can improve my code, thanks guys. Ps: i really need the job :( Here is a sample of my code: ##### models from django.db import models # Create your models here. class Rental(models.Model): name = models.CharField(max_length=100) def __str__(self) -> str: return self.name class Reservations(models.Model): rental_id = models.ForeignKey(Rental, related_name="rental_id", on_delete=models.CASCADE) checkin = models.DateField() checkout = models.DateField() def __str__(self) -> str: return f"{self.rental_id.name}, {self.id}" #### The views implementation from django.shortcuts import render from .models import Rental, Reservations def All_Reservation(request): reservations = Reservations.objects.all() rental_names = Rental.objects.values_list('name') ValueSet = [] for i in sort_by_rental_name(rental_names): ValueSet += i mapped = zip(ValueSet,reservations) print(dict(mapped)) context = { 'reservations': reservations, 'values': ValueSet } return … -
Number of occurrences in django
How to calculate and save in database the number of occurrences per day of the number of participants lower than the maximum number of participants in a space of radius R=50km. # models.py class Even(models.Model): name = models.CharField(max_length=200, null=True, blank=True) date = models.DateField(null=True, blank=True) time = models.TimeField(null=True, blank=True) participant = models.PositiveIntegerField(null=True, blank=True) longitude = models.FloatField(null=True, blank=True) latitude = models.FloatField(null=True, blank=True) geom = models.PointField(srid=4326, null=True, blank=True,) @property def longitude(self): return self.geom.x @property def latitude(self): return self.geom.y def __str__(self): return self.name # views.py def even_nb_jour(request): labels = [] data = [] today = date.today() even_max_today = Even.objects.filter(date=today).aggregate(Max('particpant')) pnt = Even.objects.filter(date=today).filter(geom_magnitude=even_max_today) queryset = Even.objects.filter(date=today).values('time').filter(geom__distance_lte=(pnt, Distance(km=50))).annotate(time_name=Count('name')).order_by('time') for rm in queryset: labels.append(rm['time']) data.append(rm['time_name']) return JsonResponse(data={ 'labels': labels, 'data': data, }) -
How to nest Some of the UserModel fields into another Serializer
I have a model name Comment as follows. class Comment(models.Model): message = models.CharField(max_length=1000) time = models.DateTimeField(auto_now_add=True) sender = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='usercomment') def __str__(self): return self.sender.name For this model, I have a serializer class CommentSerializer(serializers.Serializer): id = serializers.IntegerField(read_only=True) time = serializers.DateTimeField(read_only=True) message = serializers.CharField(read_only=True) sender = serializers.PrimaryKeyRelatedField(read_only=True, many=False) name = serializers.StringRelatedField( source='sender', read_only=True, many=False) I have another serializer for the sender information that is linked with Forignkey to AUTH_USER_MODEL, and for that Part, I have another serializer to nest some of the fields from the User model. class SenderInformation(serializers.Serializer): id = serializers.UUIDField(read_only=True) name = serializers.CharField(read_only=True) avatar = serializers.ImageField(read_only=True) And the main objective is to Nest this SenderInformation into CommentSerializer. How can I achieve this?