Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how can i delete my comment in with a delete function or class in Django?
how can I create a delete function or class to delete a comment with this detail? this is part of my comment model in the comment app class Comment(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='comments') content = models.TextField() parent = models.ForeignKey('self', null=True, blank=True, related_name='replies', on_delete=models.CASCADE) this is part of my view in product app def product_detail(request, *args, **kwargs): selected_product_id = kwargs['productId'] product = Product.objects.get_by_id(selected_product_id) if product is None or not product.active: raise ("not valid") comments =product.comments.filter(active=True, parent__isnull=True) new_comment=None if request.method == 'POST': comment_form = CommentForm(data=request.POST) if comment_form.is_valid(): parent_obj = None try: parent_id = int(request.POST.get('parent_id')) except: parent_id = None if parent_id: parent_obj = Comment.objects.get(id=parent_id) if parent_obj: replay_comment = comment_form.save(commit=False) replay_comment.parent = parent_obj new_comment = comment_form.save(commit=False) new_comment.product = product new_comment.save() else: comment_form = CommentForm() -
Unable to use runserver_plus for django
I am using the command to run my python-django project on https "python3 manage.py runserver_plus 0.0.0.0:9999 --cert-file /path/to/cert/app" but I get the error File "/Users/xyz/django_dev_portal/django-api-1/app/manage.py", line 16 ) from exc ^ SyntaxError: invalid syntax I have django-extensions installed. Im unable to figure out whats going wrong as Im very new to Django and Python. Any help is greatly appreciated. Cheers, Sheetal -
attribute error in django. django.db.models has no attribute
I am trying to write the code so that a user in the system can view complaint registered by others on this page but not their own complaints. This is the code, but I don't understand what's wrong: views.py: class OtherPeoplesComplaints(TemplateView): model = Complaint form_class = ComplaintForm template_name = 'userComplaints.html' def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) context["complaints"] = models.Complaint.objects.exclude( profile__user = self.request.user ) models.py: class Complaint(models.Model): user = models.ForeignKey(User, on_delete= models.CASCADE, null = True, blank=True) id = models.AutoField(blank=False, primary_key=True) reportnumber = models.CharField(max_length=500 ,null = True, blank= False) eventdate = models.DateField(null=True, blank=False) event_type = models.CharField(max_length=300, null=True, blank=True) device_problem = models.CharField(max_length=300, null=True, blank=True) manufacturer = models.CharField(max_length=300, null=True, blank=True) product_code = models.CharField(max_length=300, null=True, blank=True) brand_name = models.CharField(max_length = 300, null=True, blank=True) exemption = models.CharField(max_length=300, null=True, blank=True) patient_problem = models.CharField(max_length=500, null=True, blank=True) event_text = models.TextField(null=True, blank= True) document = models.FileField(upload_to='static/documents', blank=True, null=True) def __str__(self): return self.reportnumber forms.py: class DateInput(forms.DateInput): input_type = 'date' class ComplaintForm(ModelForm): class Meta: model = Complaint fields = '__all__' widgets = { 'reportnumber': forms.TextInput(attrs={'placeholder': 'Report number'}), 'event_type': forms.TextInput(attrs={'placeholder': 'Event type'}), 'eventdate': DateInput(), 'device_problem': forms.TextInput(attrs={'placeholder': 'Device Problem'}), 'event_text': forms.Textarea(attrs={'style': 'height: 130px;width:760px'}), 'manufacturer': forms.TextInput(attrs={'placeholder': 'Enter Manufacturer Name'}), 'product_code': forms.TextInput(attrs={'placeholder': 'Enter Product Code'}), 'brand_name': forms.TextInput(attrs={'placeholder': 'Enter Brand Name'}), 'exemption': forms.TextInput(attrs={'placeholder': 'Enter Exemption'}), … -
I am encountering an Apache error while deploying a Django site
Faced Apache error while deploying Django site with MySQL db. Without Apache, the site works perfectly, but when you enable it, this error is thrown. I can't figure it out for several days. This is what the logs give out: [Wed Jul 21 12:49:59.142758 2021\] \[wsgi:error\] \[pid 24588:tid 140415838369536\] \[remote 95.56.215.234:56573\] mod_wsgi (pid=24588): Target WSGI script '/bigchina/django/bigchina/bigchina/wsgi.py' cannot be loaded as Python module. \[Wed Jul 21 12:49:59.142923 2021\] \[wsgi:error\] \[pid 24588:tid 140415838369536\] \[remote 95.56.215.234:56573\] mod_wsgi (pid=24588): Exception occurred processing WSGI script '/bigchina/django/bigchina/bigchina/wsgi.py'. \[Wed Jul 21 12:49:59.144156 2021\] \[wsgi:error\] \[pid 24588:tid 140415838369536\] \[remote 95.56.215.234:56573\] Traceback (most recent call last): \[Wed Jul 21 12:49:59.144210 2021\] \[wsgi:error\] \[pid 24588:tid 140415838369536\] \[remote 95.56.215.234:56573\] File "/bigchina/django/bigchina/bigchina/wsgi.py", line 18, in <module> \[Wed Jul 21 12:49:59.144217 2021\] \[wsgi:error\] \[pid 24588:tid 140415838369536\] \[remote 95.56.215.234:56573\] application = get_wsgi_application() \[Wed Jul 21 12:49:59.144257 2021\] \[wsgi:error\] \[pid 24588:tid 140415838369536\] \[remote 95.56.215.234:56573\] File "/bigchina/venv/lib/python3.6/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application \[Wed Jul 21 12:49:59.144263 2021\] \[wsgi:error\] \[pid 24588:tid 140415838369536\] \[remote 95.56.215.234:56573\] django.setup(set_prefix=False) \[Wed Jul 21 12:49:59.144269 2021\] \[wsgi:error\] \[pid 24588:tid 140415838369536\] \[remote 95.56.215.234:56573\] File "/bigchina/venv/lib/python3.6/site-packages/django/__init__.py", line 24, in setup \[Wed Jul 21 12:49:59.144274 2021\] \[wsgi:error\] \[pid 24588:tid 140415838369536\] \[remote 95.56.215.234:56573\] apps.populate(settings.INSTALLED_APPS) \[Wed Jul 21 12:49:59.144280 2021\] \[wsgi:error\] \[pid 24588:tid 140415838369536\] \[remote 95.56.215.234:56573\] File "/bigchina/venv/lib/python3.6/site-packages/django/apps/registry.py", … -
Django not collecting all my static files
This my settings.py code, I have made a folder staticdie and copied all my static files in it. STATIC_URL = '/static/' STATICFLIES_DIRS = [ os.path.join(BASE_DIR, 'staticdie') ] STATIC_ROOT = os.path.join(BASE_DIR, 'assets') When I put python manage.py collectstatic it creates a folder 'assets' and only displays admin files in it. Its not collecting all my static files from staticdie folder. I'm using travello template from colorlib. link(https://www.dropbox.com/sh/gf8x8xjwidq20cz/AABPlOsXmijnz0-yjxYj9ebsa?dl=0) What am I missing? -
How to redirect unauthenticated users to login page?
Im developing a web application using React and Django Sessions with Django Rest Framework for authentication. I have already configured sessions to be given to users on login. I am trying to find a way to redirect unauthenticated users to login page from any page in the web application. I have tried to obtain the value of the sessionid cookie seen here so that I can redirect users if the .length value == 0. if (getCookieValue('sessionid').length === 0) { return <Redirect to="/login" /> } However, since the sessionid cookie is an HTTP cookie, JavaScript is unable to obtain the value. Thus, it is always 0. How can I obtain the value of the HTTP cookie? Or, is there any other way to achieve my desired effect? -
assertEqual getting failed while values are same
I have below test case assert code self.assertEqual( response.data['results'], [ ('id', self.bookmark.id), ('title', self.bookmark.title), ('color', self.bookmark.color), ('user', self.bookmark.user.id), ('project', self.bookmark.project.id), ] ) response.data['result'] is : [OrderedDict([('id', 7), ('title', 'bookmark'), ('color', 'yellow'), ('user', 2), ('project', 1)])] compare list value is : [('id', 7), ('title', 'bookmark'), ('color', 'yellow'), ('user', 2), ('project', 1)] failure msg : AssertionError: [OrderedDict([('id', 7), ('title', 'bookma[52 chars]1)])] != [('id', 7), ('title', 'bookmark'), ('color[37 chars], 1)] can anyone please help? -
How pass multiple attributes to View on Button Click?
I am using Django as my web Framework. On my website there is a view that shows all "projects" of a user. Here the user has the possibility to leave the project or to add a user to the project. When a user presses a button, I want the respective action to be executed. To check if the share or leave button has been pressed i have added a button in my button: <form method="POST"> <button name="leave_project" type="submit" ...>...</button> </form> and can then check in the views: if 'leave_project' in request.POST: However, now I still need the ID of the project that was clicked on. How can I also pass the ID? I know that I could solve the problem by adding a new view with the ID in the url. But then the page would have to be reloaded which I would like to avoid. -
best article/resource for DJANGO + REACT stack
I've been learning Django and React separately for a long time. I want to use them together as a stack now. I know, there are so many articles/tutorials about this already. But everyone has their own method. Can someone plz tell me the BEST way to do so? Any article/video/or previously asked StackOverflow question will do me good. Thanks -
No Reverse error on updating an object in Django
Model: class HourCodes(models.Model): nummer = models.IntegerField() omschrijving = models.CharField(max_length=100) def get_absolute_url(self): return reverse("to_HourCodes") View: class UpdateHourCodes(UpdateView): template_name = 'hourcode_update.html' form_class = Update_hourcode_form queryset = HourCodes.objects.all() def get_object(self): id_ = self.kwargs.get("pk") return get_object_or_404(HourCodes, id=id_) Url.py path('toHourcodes/', views.toHourcodes, name='to_hourcodes'), path('UpdateHourCodes/<int:pk>/', views.UpdateHourCodes.as_view(), name="update_hourcode"), iam getting the error NoReverseMatch at /UpdateHourCodes/44/ So the link seems to be right, in this case to HourCode nr 44. Anybody has a clue ? -
Django Cast DateTimeField to DateField splits over multiple days
I have a DateTimeField that I'm casting into a DateField so I can group by the date then perform some annotations. For some reason it's splitting a single timestamp for a specific date into two dates - I can't figure out why it's happening. For example in the following I should only get one grouping as I'm specifically filtering for May 5th but it's being split into two separate dates. orders = ( Order.objects .filter(paid_at__date='2021-05-01') .annotate(paid_at_date=Cast('paid_at', DateField())) .order_by('paid_at_date') .values('paid_at_date') .annotate(total=Sum('total')) ) <OrderQuerySet [{'paid_at_date': datetime.date(2021, 5, 1), 'total': Decimal('17852.30')}, {'paid_at_date': datetime.date(2021, 5, 2), 'total': Decimal('6895.30')}]> -
how i could filter items by their sex category
template <form name="selectForm" action="{% url 'shop' %}" method="get"> <label for="orderby"></label> <select name="orderby" id="orderby" onchange="selectForm.submit();"> <option value="">default</option> <option value="price">price: $ - $$</option> <option value="-price">price: $$ - $</option> <option value="collection">collection</option> <option value="-collection">collection2</option> </select> <input type="submit" class="d-none" value="submit"> </form> view class Shop(ListView): template_name = 'essense/shop.html' context_object_name = 'items' paginate_by = 9 allow_empty = False model = Item def get_context_data(self, *, object_list=None, **kwargs): context = super().get_context_data(**kwargs) ***context*** return context def get_ordering(self): return self.request.GET.get('orderby', ) how can i pass gender to template, if i just pass the value== collection it will be sort by collection names(women first then men and children) am i need a template tag for this? -
deleting model when foreignkey is deleted in django
So, I have a model something like this class Blog(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) posted_by = models.ForeignKey(User, on_delete=models.CASCADE, null=True) def delete(self, *args, **kwargs): # to do before delete super().delete(*args, **kwargs) I want to delete all Blog objects related to User when the User is deleted. It is working but its deleting object without calling overridden delete function. I want to delete the model through the overridden delete function coz i have something to do before actually deleting the object. If it is not possible, do suggest any other way to do it. -
Django choices field in form
I have two tables: class Career(models.Model): title = models.CharField(max_length=300) job_type = models.CharField(max_length=20, blank=False, default=None) location = models.CharField(max_length=200, blank=False, default=None) description = RichTextUploadingField(max_length=227, blank=False, default=None) class ApplyJob(models.Model): first_name = models.CharField(verbose_name=_('First Name'), max_length=100) last_name = models.CharField(verbose_name=_('Last Name'), max_length=100) email = models.EmailField(verbose_name=_('Email'), max_length=200) position = models.CharField(verbose_name=_('Position'), max_length=40) apply = models.ManyToManyField(Career, default=None, blank=True) And a ModelForm: class Meta: model = ApplyJob fields = ('first_name', 'last_name', 'email','position', 'message') widgets = { 'position': forms.Select(choices=CHOICES, attrs={'class': 'form-control'})} I want to add choices selection in position with values from Career table, so itried to query Career table to get all values. So i tried CHOICES = Career.objects.values_list('title', flat=True).distinct() but i got an Exception Error: too many values to unpack (expected 2) Any ideas on what the problem is about? Thank you! -
Django User Type Definition
In Django : From a Python OO perspective if I want different types of users shouldn't I have a "Teacher" Object Type AND "Student" Object" type extended from AbstractUser? Looks like all the solutions mention to just extend with all the fields required for both users and only use the fields required for a Teacher or Student at Form time. Just trying to stay with the OO method which makes sense to me from a newbie perspective. Having different object types would allow me to test the object for the type instead of looking at an attribute and have only the needed fields for each type defined in the object. Is there a correct way to do this so I have users of different object types? Could I just embed an object of type Teacher or Student as a field in the User Model? Just a guess? Let me know what you can and thanks for your expert polite response and patience. Is this a good solution? https://github.com/mishbahr/django-users2 This is the recurring theme I see on the internets... django best approach for creating multiple type users -
syntax error when importing django-sphinxsearch
I am trying to run the standard django migration commands, ex., python3 manage.py makemigrations, and continuously get a syntax error on module import with sphinxsearch. I know it's deprecated, but unfortunately I am working on small additions to the site and cannot move to elasticsearch yet. Python version : 3.5.3 System : Debian (AWS server) Sphinx version: 3.5.4 sphinxsearch version: 0.1 Error message: Traceback (most recent call last): File "manage.py", line 13, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.5/dist-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.5/dist-packages/django/core/management/__init__.py", line 347, in execute django.setup() File "/usr/local/lib/python3.5/dist-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python3.5/dist-packages/django/apps/registry.py", line 89, in populate app_config = AppConfig.create(entry) File "/usr/local/lib/python3.5/dist-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/usr/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 673, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 669, in exec_module File "<frozen importlib._bootstrap_external>", line 775, in get_code File "<frozen importlib._bootstrap_external>", line 735, in source_to_code File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed File "/usr/local/lib/python3.5/dist-packages/sphinxsearch/__init__.py", line 75 SPH_ATTR_MULTI = 0X40000000L ^ SyntaxError: invalid syntax I've tried updating the system and have changed sphinx … -
Django: Redirecting to same page after updating profile is not updating the user profile in database
I have this update view which updates the user's profile like first_name, last_name and DOB. @login_required def profile_view(request): user_obj = get_object_or_404(User, id=request.user.id) profile_obj = get_object_or_404(Profile, user=user_obj) print(user_obj.first_name) if request.method == "POST": user_edit_form = UserEditForm(data=request.POST, instance=user_obj) profile_edit_form = ProfileEditForm(data=request.POST, instance=profile_obj) if user_edit_form.is_valid() and profile_edit_form.is_valid(): user_edit_form.save() profile_edit_form.save() return HttpResponseRedirect(request.path_info) else: user_edit_form = UserEditForm(instance=user_obj) profile_edit_form = ProfileEditForm(instance=profile_obj) return render( request, "account/profile.html", {"user_edit_form": user_edit_form, "profile_edit_form": profile_edit_form}, ) The problem is when I redirect to the same page using HttpResponseRedirect(request.path_info) the values are not getting updated in the database. But if I redirect to some other page of my site say return redirect('account:home') instead of HttpResponseRedirect(request.path_info) the values are updating. This is my profile form {% extends "base.html" %} {% load static %} {% block content %} <h1> {{ request.user | capfirst }} Profile details</h1> <form method="post"> {% csrf_token %} <table class="table .table-striped"> {{ user_edit_form.as_table }} {{ profile_edit_form.as_table }} </table> <button class="btn btn-danger" type="submit"> <a style="text-decoration: none; color: black;" href="#">Update</a> </button> <button class="btn btn-danger"> <a style="text-decoration: none; color: black;" href="{% url 'account:log_out' %}">Log Out</a> </button> </form> {% endblock %} -
Django ValueError: "" must be a "" instance
I am trying to save some data into the database with a form but am getting the exception ValueError: Cannot assign "<ShoppingCartOrderItem: 1 of The Crucifixion>": "Review.product" must be a "Product" instance. I think I understand the issue I am just unsure on how to solve it. Basically I have products which are displayed if the user has ordered the item, they then can choose to leave a review. In my form in the select options I am returning a query set so that they only have the orders that they have ordered displayed. Models: class ShoppingCartOrderItem(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) ordered = models.BooleanField(default=False) item = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) class Review(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True) rating = models.DecimalField(max_digits=2, decimal_places=1, validators=[MinValueValidator(Decimal('0.1'))]) comment = models.TextField(validators=[MinLengthValidator(10)]) date = models.DateField(auto_now=True) Views: class MyOrdersView(LoginRequiredMixin, View): def get(self, request, *args, **kwargs): try: order = ShoppingCartOrder.objects.filter(user=self.request.user, ordered=True) form = ReviewForm(user=self.request.user) context = { 'object': order, 'form': form } return render(request, 'my_site/my_orders.html', context) except ObjectDoesNotExist: messages.warning(request, 'You do not have any orders') return redirect('all_products') def post (self, request, *args, **kwargs): form = ReviewForm(request.POST, user=self.request.user) if form.is_valid(): form = ReviewForm( product = form.cleaned_data['product'], rating = form.cleaned_data['rating'], comment = form.cleaned_data['comment'] ) form.save() return … -
How Do I order a Django model by name?
I have got a list of products from different retailers. I am trying to sort the list to try and group all products that are the same but have different retailers together. I am trying to sort the model by 'product', so that it is presented in order in the Django admin panel, and so that I can carry out commands on a product group at once. How should I go about doing this? Model: class RetailerProduct(models.Model): url = models.CharField(max_length=300,null=True,blank=True) price = models.DecimalField(default=0.00,max_digits=8,decimal_places=2,null=True,blank=True) difference = models.DecimalField(default=0.00,max_digits=8,decimal_places=2,null=True,blank=True) retailer = models.ForeignKey(Retailer, on_delete=models.CASCADE) available = models.BooleanField(default=False) _id = models.AutoField(primary_key=True, editable=False) product = models.ForeignKey(Product, on_delete=models.CASCADE,related_name='sources') def __str__(self): return self.retailer.name + " - " + self.product.name I have tried using: class Meta: ordering = ('product',) But it does not work. -
Django - modify a field value in filter()
I want to modify some_date_field value while filtering. Like using models.Lookup or models.Transform but I dont want to make a raw sql expression. Just modify model's field value Smth like this: class SomeModel(models.Model): some_date_field = models.DateField() def replace_year(value): return value.replace(year=2021) SomeModel.objects.filter( # replace_year(some_date_field)__gte= ... ) Is it possible? -
Custom authentication with djoser using django 3.1
Im having problems making my backend (takes either phone number or email address for login) work with djoser for login. It seems to be only loging in the superuser account hen i want it to take either the phone number or email address. ps: the backend is not from django rest framework but i created a custom authentication from vanilla django.(i created the full project before the api just in case this might be problem) Im new to APIs and Django i hope this is a relevant question. heres my code, let me know if you need more thanks My settings: DJOSER = { 'USER_CREATE_PASSWORD_RETYPE':True, 'USERNAME_CHANGED_EMAIL_CONFIRMATION':True, 'PASSWORD_CHANGED_EMAIL_CONFIRMATION':True, 'SEND_CONFIRMATION_EMAIL':True, 'SET_USERNAME_RETYPE':True, 'SET_PASSWORD_RETYPE':True, 'PASSWORD_RESET_CONFIRM_URL':'password/reset/confirm/{uid}/{token}', 'USERNAME_RESET_CONFIRM_URL':'password/reset/confirm/{uid}/{token}', 'ACTIVATION_URL':'activate/{uid}/{token}', 'SEND_ACTIVATION_EMAIL':True, 'SERIALIZERS': { 'user_create': 'rafiki.serializers.UserCreateSerializer', 'user': 'rafiki.serializers.UserCreateSerializer', 'user_delete': 'djoser.serializers.UserDeleteSerializer', } } my auth model: class CustomUserManager(BaseUserManager): """ Custom user model manager where Email_Address is the unique identifiers for authentication instead of usernames. """ def create_user(self, Email_Address, password, **extra_fields): """ Create and save a User with the given Email_Address and password. """ if not Email_Address: raise ValueError(_('The Email_Address must be set')) Email_Address = self.normalize_email(Email_Address) user = self.model(Email_Address=Email_Address, **extra_fields) user.set_password(password) user.save() return user def create_superuser(self, Email_Address, password, **extra_fields): """ Create and save a SuperUser with the given Email_Address and … -
How to filter related objects of related objects in Django?
Imagine a data model where: class Album(models): name = models.CharField class Song(models): albums = models.ManyToManyField(related_name="albums") class Word(models): songs= models.ManyToManyField(related_name="songs") category = model.Charfield() # can be "friendly", "expletive", etc. I.e. an album has many songs and a song can be on several albums. Then a song consists of many words and the same word can be in multiple songs. I'd like to construct a queryset consisting of all words where the category is "friendly", and which belong to all songs of an album. -
Django / Postgres - Sum aggregate function duplicates results when grouping by other annotations
The Django Sum() aggregation method produces buggy results when combined with multiple annotations that usually results in duplicated data when a row of data can fit into multiple categories Take the following for example: class Item(models.Model): id = models.BigAutoField(primary_key=True) name = models.TextField(blank=True, null=True) class ItemLink(models.Model): id = models.BigAutoField(primary_key=True) parent_item = models.ForeignKey(Item, blank=False, related_name='parent_item_links') child_item = models.ForeignKey(Item, blank=False, related_name='child_item_links') class Aggregate(models.Model): id = models.BigAutoField(primary_key=True) item_id = models.ForeignKey(Item, blank=False) data = models.FloatField(blank=True, null=True) These 3 tables describe an item, the relationship items have to other items, and some aggregate table that has data associated to a particular item. If I were to sum the aggregate data for an item and group by any parent relationships it has, I would receive duplicate results. For example: [{ name: parent_1, id: 1 }, { name: parent_2, id: 2 }, { name: child_1, data: 1.0, (via aggregate) id: 3 }] if I were to query against this data set I would expect to get data: 1 for both the parent objects, but when I group by the items name, I get 2. Aggregate.objects.annotate('item_name': F('item__parent_item_links__parent_item__name')).annotate(agg_value=Sum('data')).filter('item_id__is': 3).values_list('item_name', 'agg_value') would give you [{ item_name: parent_1, agg_value: 2.0, }, { item_name: parent_2, agg_value: 2.0, }] where I'd expect it to … -
Modeling complex relationship between Django models based on another model's value
I am trying to model a Recipe that contains a series of Ingredients. In these ingredients, the price field is dependent on the value of another model (Supplier's location). For example, my Recipe could contain: Water, Beef and Salt. Each ingredient has a price, which depends on the user's location. I.e. if my user is from Texas, the price of the beef and water may change and therefore the total price of the recipe will change. Right now I'm using the following approach: class Product(models.Model): name = models.CharField(_('Name'), max_length=255, help_text=_('Product name')) price = models.FloatField(_('Sale price'), default=0) supplier = models.ForeignKey(Supplier, blank=True, null=True, related_name='supplier_products', on_delete=models.CASCADE) class IngredientRecipe(models.Model): product_name = models.CharField(_('Name'), max_length=255, help_text=_('Product name'), blank=True) recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE, related_name='ingredients') quantity = models.FloatField(_('Quantity')) class Recipe(models.Model): user = models.ForeignKey(User, null=True, on_delete=models.CASCADE, related_name='user_recipes') title = models.CharField(_('Recipe title'), max_length=255, help_text=_('Recipe. Example: american chicken salad'), blank=True) I'm using this models along with a serializer to show the price corresponding to the selected location: class VerySimpleRecipeSerializer(serializers.ModelSerializer): cost = serializers.SerializerMethodField(read_only=True) class Meta: model = Recipe fields = ['id', 'title', 'cost',] def get_cost(self, obj): ingredients_names = obj.ingredients.values('product_name', 'quantity') total_price = 0 try: location_id = self.context['request'].query_params.get('location', None) products = Product.objects.annotate(min_price=Min('price')).filter( Q(supplier__location_id=location_id) & Q(name__in=[x.get('product_name', None) for x in ingredients_names]), is_active=True, min_price__lte=F('price')).order_by() except … -
Django Object filter expected id (int) but get str
I make Django blog project and I've implemented a function to filter posts by their tag. There is a possibility to select a certain tag and to see all posts with this specific one. But I have trouble when I want to filter all posts by this tag. I get an error that Django expects int number but not str. How to solve this problem? This is my code models.py class Tag(models.Model): name = models.CharField(max_length=200, null=True) slug = models.SlugField(max_length=250, unique=True, editable=False) class ProjectPost(models.Model): tag = models.ForeignKey(Tag, on_delete=models.PROTECT) url.py urlpatterns = [ ... path("projects/", views.projects, name='projects'), path('projects/<slug:tag>/',views.projects, name='projects_tag'), ] views.py def projects(request, tag=None): if tag is not None: ProjectPost.objects.filter(tag=tag) else: posts = ProjectPost.objects.all() tags = Tag.objects.all() context = {'posts':posts, 'tags':tags} return render(request, 'website/projects.html', context) THis is error ValueError at /projects/romania/ Field 'id' expected a number but got 'romania'. Request Method: GET Request URL: http://127.0.0.1:8000/projects/romania/ Django Version: 3.2.5 Exception Type: ValueError Exception Value: Field 'id' expected a number but got 'romania'. Exception Location: /home/cristian/Desktop/GreatEcology my project/ecosite/venvecosite/lib/python3.8/site-packages/django/db/models/fields/__init__.py, line 1825, in get_prep_value Python Executable: /home/cristian/Desktop/GreatEcology my project/ecosite/venvecosite/bin/python Python Version: 3.8.5 Python Path: ['/home/cristian/Desktop/GreatEcology my project/ecosite/ecowebsite', '/home/cristian/Anaconda3/lib/python38.zip', '/home/cristian/Anaconda3/lib/python3.8', '/home/cristian/Anaconda3/lib/python3.8/lib-dynload', '/home/cristian/Desktop/GreatEcology my ' 'project/ecosite/venvecosite/lib/python3.8/site-packages'] Server time: Wed, 21 Jul 2021 14:36:51 +0000