Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
TypeError: 'User' object is not iterable
I am working with a payment system in my django E commerce Project. But it shows me that user is not iterable . Here's the code @login_required def payment(request): saved_address = BillingAddress.objects.get_or_create(user=request.user)[0] if not saved_address.is_fully_filled(): messages.info(request,f'Please complete shipping address!') return redirect('checkout') if not request.user.profile.is_fully_filled(): messages.info(request,f'Please complete profile details!') return redirect('profile') store_id = '$$$$$$$$$$$$$$$' API_key= '$$$$$$$$$$$$$$$@ssl' mypayment = SSLCSession(sslc_is_sandbox=True, sslc_store_id=store_id, sslc_store_pass=API_key) status_url= request.build_absolute_uri(reverse('complete')) mypayment.set_urls(success_url=status_url, fail_url=status_url, cancel_url=status_url, ipn_url=status_url) order_qs=Order.objects.filter(user=request.user,ordered=False) order_items=order_qs[0].orderitems.all() order_item_count=order_qs[0].orderitems.count() order_total=order_qs[0].get_totals() mypayment.set_product_integration(total_amount=Decimal(order_total), currency='BDT', product_category='Mixed', product_name=order_items, num_of_item=order_item_count, shipping_method='Courier', product_profile='None') current_user=request.user mypayment.set_customer_info(name=current_user.profile.full_name, email=current_user, address1=current_user.profile.address_1, address2=current_user.profile.address_1, city=current_user.profile.city, postcode=current_user.profile.zipcode, country=current_user.profile.country, phone=current_user.profile.phone) mypayment.set_shipping_info(shipping_to=current_user.profile.full_name, address=saved_address.address, city=saved_address.city, postcode=saved_address.zipcode, country=saved_address.country) response_data = mypayment.init_payment() return render(request,'payment/payment.html',context={}) it work untill i wrote the last line response_data = mypayment.init_payment() the server shows this TypeError at /payment/pay/ 'User' object is not iterable Request Method: GET Request URL: http://localhost:8000/payment/pay/ Django Version: 3.2.8 Exception Type: TypeError Exception Value: 'User' object is not iterable Help me with this. Thanks in advance -
django modeltranslation doesn't work with such queryset
I'm new to programming. In my blog I want to show a list of categories. If I create a queryset like this: Category.objects.all() my django-modeltranslation works perfectly. But I want to get categories of only published posts. Then my queryset is: Post.objects.values('category__name').filter(is_published=True) However, django-modeltranslation doesn't work. I get values from 'name' field instead 'name_en' or 'name_ru' fields. What is wrong? Here's my models.py : class Category(models.Model): name = models.TextField(max_length=100) url = models.SlugField(max_length=160, unique=True) class Post(models.Model): title = models.TextField('title', max_length=150) category = models.ManyToManyField(Category, related_name='posts', blank=True) -
The model appears but the profile edit form don't appear on it, any idea why?
On my social app that I'm working on, there's still one issue. On my ProfileDetailView, to click on "Edit Profile" the model form appear but there's no form. It was working before but when I fixed the close button and I don't know what happened.. I copied the model html from bootstrap so i probably deleted/changed something and forgot to re-do it.. Form: from django import forms from .models import Profile, Post, Comment class ProfileModelForm(forms.ModelForm): class Meta: model = Profile fields = ('first_name', 'last_name', 'bio', 'avatar') Views: from django.contrib.auth import authenticate, login, logout from django.db import IntegrityError from django.http import HttpResponse, HttpResponseRedirect from django.http.response import JsonResponse from django.shortcuts import render, redirect, resolve_url, get_object_or_404 from django.urls import reverse, reverse_lazy from django.core import serializers from django.core.paginator import Paginator from django.contrib import messages from django.contrib.auth.models import User from django.db.models import Q from django.contrib.auth.decorators import login_required from django.contrib.auth.mixins import LoginRequiredMixin from itertools import chain from .models import Relationship, Post, Profile, Like from django.views.generic import TemplateView, View, UpdateView, DeleteView, ListView, DetailView from .forms import ProfileModelForm, PostModelForm, CommentModelForm def search_view(request): if request.method == "POST": searched = request.POST['searched'] profiles = Profile.objects.filter(slug__contains=searched) return render(request, 'network/search.html', {'searched':searched, 'profiles':profiles}) else: return render(request, 'network/search.html', {}) class ProfileDetailView(LoginRequiredMixin, DetailView): model = Profile … -
Current parameters in url set in the next url in django
I have a url like this http://127.0.0.1:8000/orders/?from=&to=&status=1 I have an button in that page to export all orders but if i have a status I need to send this as an parameter in that url to filter before export <a href="{% url 'orders:export' %}">Export</a> How can I send parameters to that export function -
Django + Google Storage (GCP) multiple bucket
For now i use django 1.11 and using google cloud platform (google storage) to store pdf. my bucket is not open for public and everything was fine, but now i need to store public file (people with link can access uploaded pdf file) I was thinking is it possible for me to have options(choose the bucket target) when upload to google storage? Maybe something like this codes from django.db import models from storages.backends.s3boto import S3BotoStorage class MyModel(models.Model): file_1 = models.FileField() # Uses default storage file_2 = models.FileField(storage=S3BotoStorage(bucket='other-bucket')) I want to do the same as this, but using GCP instead of AWS django-storages with multiple S3 Buckets I'm sorry if this question is too basic, but I've never found the answer until now Thanks for your attention, and hope you can help me and the others who faced the same problem. -
How to get the sum of values in Django template for loop or how i can implement the same in Django view
this is my template <div class="row m-5 p-3 border bg-white"> <table class="table "> <tr> <th>Project Name</th> <th>Total Partnership</th> </tr> {% for pages in page %} <tr> <td>{{pages.name}}</td> <td> {% for i in pages.partnership_set.all %} {{i.partnership}}% {% endfor%} </td> </tr> {% endfor %} </table> </div> my output is: |project Name | Total Partnership | |-------------|-------------------| |project 1. | 100%. | |project 2. | 20% 30% 40%. | |project 3. | 45% 30%. | i just wanted this total partnerships to be added and displayed.how can i do it either in template or else in view? -
How to config media in Django using xampp apache mod_wsgi?
I have a project in Django. It runs completely normally on Local. But when I use XAMPP Apache MOD_WSGI to grow up the web, it can't be run, because it has many folders in the media folder. How can I solve this problem? Thank you very much -
djangosaml2idp problems with launch: saml2.sigver.MissingKey: http://localhost:8000/saml2/metadata/
I'v been trying to launch project(example_setup folder): https://github.com/OTA-Insight/djangosaml2idp/tree/master/example_setup ican anybody answer to men according with documentation. But it does not working. First problem, as I undesrtand is in date of methadata in SP(idp_metadata.xml)- validUntil="2020-12-27T12:41:18Z"> . It does not valid at the moment, and was changed to future date, as example(validUntil="2030-12-27T12:41:18Z"). But nex I got another problem when trying to sign in to SP(localhost:8000) in my browser, I have more problem: Error during SAML2 authentication IncorrectlySigned In attempts to find problem, I found the place where it is occured. In original it iis in tryexcept block, and can't be found easy. Traceback (most recent call last): File "/home/dmitriy/projects/djangosaml2idp/example_setup/idp/djangosaml2idp/views.py", line 251, in get req_info = idp_server.parse_authn_request(request.session['SAMLRequest'], binding) File "/home/dmitriy/projects/djangosaml2idp/example_setup/idp/venv/lib/python3.8/site-packages/saml2/server.py", line 238, in parse_authn_request return self._parse_request(enc_request, AuthnRequest, File "/home/dmitriy/projects/djangosaml2idp/example_setup/idp/venv/lib/python3.8/site-packages/saml2/entity.py", line 1036, in _parse_request _request = _request.loads(xmlstr, binding, origdoc=enc_request, File "/home/dmitriy/projects/djangosaml2idp/example_setup/idp/venv/lib/python3.8/site-packages/saml2/request.py", line 110, in loads return self._loads(xmldata, binding, origdoc, must, File "/home/dmitriy/projects/djangosaml2idp/example_setup/idp/venv/lib/python3.8/site-packages/saml2/request.py", line 51, in _loads print(self.signature_check(xmldata, origdoc=origdoc, File "/home/dmitriy/projects/djangosaml2idp/example_setup/idp/venv/lib/python3.8/site-packages/saml2/sigver.py", line 1662, in correctly_signed_authn_request return self.correctly_signed_message(decoded_xml, 'authn_request', must, origdoc, only_valid_cert=only_valid_cert) File "/home/dmitriy/projects/djangosaml2idp/example_setup/idp/venv/lib/python3.8/site-packages/saml2/sigver.py", line 1653, in correctly_signed_message return self._check_signature( File "/home/dmitriy/projects/djangosaml2idp/example_setup/idp/venv/lib/python3.8/site-packages/saml2/sigver.py", line 1503, in _check_signature raise MissingKey(_issuer) saml2.sigver.MissingKey: http://localhost:8000/saml2/metadata/ Internal Server Error: /idp/login/process/ Some key is missing: Error during SAML2 authentication MissingKey http://localhost:8000/saml2/metadata/ My idp_metada … -
How to loop through values in JSON and assign to another dictionary
I am developing a Python/Django web app. I am trying to parse JSON into a python dictionary, read the values in the dictionary, and assign the values to another dictionary if certain conditions are met. JSON is structured like this: {content: {cars: [0, 1, 2]}, other_stuff: []} Each car has multiple attributes: 0: {"make", "model", "power"...} Each attribute has three variables: make: {"value": "Toyota", "unit": "", "user_edited": "false"} I am trying to assign the values in the JSON to other dictionaries; car_0, car_1 and car_2. In this case the JSON response is otherwise identical considering each car, but the 'make' of the first car is changed to 'Nissan', and I'm trying to then change the make of the car_0 also to 'Nissan'. I'm parsing JSON in the following way: local_cars = [car_0, car_1, car_2] # Dictionaries which are already initialized. print(local_cars[0]['make']['value']) # Prints: Toyota (yes) print(local_cars[1]['make']['value']) # Prints: Toyota (yes) print(local_cars[2]['make']['value']) # Prints: Toyota (yes) counter = 0 if request.method == 'POST': payload = json.loads(request.body) if bool(payload): print(len(local_cars)) # Prints: 3 print(counter, payload['cars'][0]['make']['value']) # Prints: Nissan (yes) print(counter, payload['cars'][1]['make']['value']) # Prints: Toyota (yes) print(counter, payload['cars'][2]['make']['value']) # Prints: Toyota (yes) print(counter, local_cars[0]['make']['value']) # Prints: Toyota (yes) print(counter, local_cars[1]['make']['value']) # Prints: Toyota … -
Django unsupported operand type(s) for +=: 'int' and 'method'
I was trying to implement a simple logic in my e-commerce website where I will be calculating total cart price by looping through orders and getting their price with the help of get_final_price but suddenly this error occurred so please help me Function due to which error is occurring def get_total(self): total_sum = 0 for order_item in self.items.all(): total_sum += order_item.get_final_price() return total_sum Models.py file from django.db import models from django.conf import settings from django.db.models.deletion import CASCADE from django.db.models.fields import DateTimeField from django.urls import reverse # # Create your models here. CATEGORY_CHOICES = ( ('S', 'Shirts'), ('SW', 'Sports wear'), ('OW', 'Outwear') ) LABEL_CHOICES = ( ('P', 'primary'), ('S', 'secondary'), ('D', 'danger') ) class Item(models.Model): title = models.CharField(max_length=100) price = models.FloatField() discount_price = models.FloatField(blank=True,null=True) category = models.CharField( choices=CATEGORY_CHOICES, max_length=2) label = models.CharField( choices=LABEL_CHOICES, max_length=1) slug = models.SlugField() description = models.TextField() def __str__(self): return self.title def get_absolute_url(self): return reverse("product", kwargs={ 'slug' : self.slug }) def get_add_to_cart_url(self): return reverse("add_to_cart", kwargs={ 'slug' : self.slug }) def get_remove_from_cart_url(self): return reverse("remove_from_cart", kwargs={ 'slug' : self.slug }) class OrderItem(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) ordered = models.BooleanField(default=False) item = models.ForeignKey(Item, on_delete=models.CASCADE) quantity = models.IntegerField(default = 1) def __str__(self): return f"{self.quantity} of {self.item.title}" def get_total_item_price(self): return self.quantity*self.item.price def get_total_discount_item_price(self): … -
Why Django modelform is submitted with enter key
I'm using Django modelform and it's submitted by pressing the enter key. This is what I wanted, but I don't know why it works. I didn't add any JS codes related to keydown but other codes to practice Ajax. Also, I found out that when there's only one input inside the form, it's submitted with the enter key, but my form has two inputs. What I'm doing is to add a comment on a post like instagram. I used Ajax to create a comment instance. models.py class Comment(models.Model): parent_post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name="comments") author = models.CharField(max_length=10) content = models.CharField(max_length=100) forms.py class CommentForm(ModelForm): class Meta: model = Comment exclude = ["parent_post"] HTML {% for post in posts %} <form method="POST" data-id="{{post.id}}" class="d-flex align-items-center w-100 mt-2"> {% load widget_tweaks %} <!-- this is a django package for easy CSS --> {% csrf_token %} {{ form.non_field_errors }} <div class="fieldWrapper"> {{ form.author.errors }} {{ form.author|add_class:"form__author"|attr:"placeholder:name" }} </div> <div class="fieldWrapper w-100"> {{ form.content.errors }} {{ form.content|add_class:"form__content"|attr:"placeholder:content" }} </div> <button class="btn btn-sm btn-warning w-auto">Write</button> </form> {% endfor %} JS (Here I didn't put the codes after getting JSON response from views.py) const forms = document.querySelectorAll("form"); forms.forEach((value) => { const post_id = Number(value.getAttribute("data-id")); value.addEventListener("submit", (e) => { … -
Django memory leak after network disconnected?
The question is Django 2.2 DRF 3.8.2 When the connection is disconnected after a REST request, the RAM is not cleared. That is, data from the database is unloaded and remains in RAM, somewhere deep in Django. How can such a problem be overcome ? -
Migrating Django TextChoices to IntegerChoices
In Django (3.2.8), I have a set of TextChoices, which I would like to change to IntegerChoices. I will keep the keys the same, just the values in the database stored will just differ. I do this for consistency and I'm fixing some legacy code. Naturally, I changed the TextChoices to IntegerChoices, and the corresponding field to an IntegerField. As expected however, upon migrating, I get a django.db.utils.DataError: invalid input syntax for type integer: "option1". I feel like there should be a way that I can define a mapping for this migration to happen, but wasn't able to find any documentation on this. -
When is the space bar becoming + django model Textarea
When my comment is saved instead to showing spaces it replaces it with plus signs For example: My Comment: Hey Guys Please Help me The Comment shown: Hey+Guys%0D%0APlease+Help+me Is this in another format or something if so please tell me how to change it I use a Textarea model form Comment if code is needed Thanks a Lot -
Default storage delete method not working under windows [WinError 123]
I have the following issue. I wrote a unit test which works great under UNIX but breaks for Win10. I am uploading a file using Djangos default_storage: from django.core.files.storage import default_storage uploaded_file = SimpleUploadedFile(self.testfile_name, file.read(), content_type='multipart/form-data') response = self.client.post(url, {'file': uploaded_file}, *args, **kwargs)) testfile_new_path = response.data.get('file') ... default_storage.delete(testfile_new_path) When I want to remove the file after my test, I get an [WinError 123] error stating that the file doesn't exist. Actually this is true because testfile_new_path looks like this: C:\workspace\project\media\http:\testserver\media\path\to\my_file.txt Obviously, something is broken. I wonder how to do this properly. After all, I am using default Django methods. Thx! -
How do you fix favicon and manifest image issue while building Python Django Website?
I am fairly new to coding and I'm doing this course where they teach you to build your own portfolio website suing python django. So far, everything has been going great. Everything loads perfectly except for my images whenever I upload them to the admin. They do not show up on the main site. Stackoverflow does not allow me to upload images yet. They only let me do a link. I'll copy both the text and the image link. This is my settings file: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' MEDIA_URL = '/media/' MEDIA_ROOT = BASE_DIR This is my URLs file: from django.contrib import admin from django.urls import path from django.conf import settings from django.conf.urls.static import static import jobs.views urlpatterns = [ path('admin/', admin.site.urls), path('', jobs.views.homepage, name='home') ] urlpatterns += static(settings.STATIC_URL, document_ROOT = settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_ROOT = settings.MEDIA_ROOT) This is what I have in my HTML code right now. <div class="container"> <div class="row row-cols-1 row-cols-sm-2 row-cols-md-3 g-3"> {% for job in jobs.all %} <!-- Row 1 Box 1 ================== --> <div class="col"> <div class="card shadow-sm"> <img class="card-img-top" src="{{ job.image.url }}"> <div class="card-body"> <p class="card-text"> {{ job.summary }} </p> <div class="d-flex justify-content-between align-items-center"> <div class="btn-group"> … -
how to get average of two date fields
I want to subtract the time user's result object is created and the time user has registered. these are my models: class User(AbstractUser): id = models.AutoField(primary_key=True) created_at = models.DateTimeField(auto_now_add=True) username = models.CharField(unique=True, max_length=13) first_name = models.CharField(max_length=32, null=True, default=None) last_name = models.CharField(max_length=64, null=True, default=None) class Results(models.Model): quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) created = models.DateField(auto_now_add=True, blank=True, null=True) score = models.FloatField() in my views, I want something like this: (Sum of all Results.created dates - Sum of all User.created_at dates)/ len(all users). how can I achieve this? -
My search bar backend config is not properly responding to my condition statement
I am currently configuring(backend) my search-bar in my Django project to search the database. I've put an 'if or else' statement for when the user just clicks the search button without putting anything in the search-box. The 'if or else' statement seems not to be working properly because it ignores the 'if' part and goes straight to the else part. I've tried different ways to fix it but I seem to be failing. How do I rectify this. function openNav() { document.getElementById("mynavbar").style.display = "block"; } function closeNav() { document.getElementById("mynavbar").style.display = "none"; } .navbar{ position: absolute; height: 102px; width: 1136px; left: 69px; top: 39px; border-radius: 0px; } .nav-menu{ display: none; } .closebtn{ display: none; } .logo img{ position: absolute; height: 57.599998474121094px; width: 100px; left: 12px; top: 31px; border-radius: 0px; } .HOME{ position: absolute; height: 38.10988998413086px; width: 97.52754211425781px; left: 203.26788330078125px; top: 48.19781494140625px; border-radius: 0px; font-family: Poppins; font-size: 27px; font-style: normal; font-weight: 700; line-height: 41px; letter-spacing: 0em; text-align: left; /* background: #FFFFFF; */ } .ARTIST{ position: absolute; height: 38.10988998413086px; width: 105.85134887695312px; left: 328.64324951171875px; top: 48.19781494140625px; border-radius: nullpx; font-family: Poppins; font-size: 27px; font-style: normal; font-weight: 700; line-height: 41px; letter-spacing: 0em; text-align: left; /* background: #FFFFFF; */ } .ABOUTUS{ position: absolute; height: 38.10988998413086px; width: 142.14324951171875px; … -
How can I automatically create an approve/reject history when I approve a request or return item?
My process for this is for them to request an item through the project request view and is stored in the Activity model, if a request has been posted they can either approve or reject it using the request approve or request reject view. Now, I want to create a history table that automatically stores the approved or rejected status of a requested item after they approve/reject it, who approved/rejected it, when it was done. Models.py class Activity(models.Model): Item = models.ForeignKey(Item, on_delete=models.CASCADE, null=True, limit_choices_to={'Quantity__gt': 0}) staff = models.ForeignKey(CustomUser, on_delete=models.CASCADE, null=True, limit_choices_to={'Quantity__gt': 0}) project_site = models.ForeignKey(Projects, on_delete=models.CASCADE, null=True) Quantity = models.PositiveIntegerField(null=True, default=1, validators=[ MaxValueValidator(100), MinValueValidator(1) ]) date_created = models.DateTimeField(auto_now_add=True) is_draft = models.BooleanField(default=True) request_status = models.IntegerField(default=0, validators=[ MaxValueValidator(3) ]) return_status = models.IntegerField(default=0, validators=[ MaxValueValidator(3) ]) note = models.TextField(max_length=255, null=True) class Meta: verbose_name_plural = 'Item Request' def __str__(self): return f'{self.Item}' Views.py def project_request(request): activities = Activity.objects.all() returns = ReturnItem.objects.all() if request.method == 'POST': form = ActivityForm(request.POST) if form.is_valid(): instance = form.save(commit=False) instance.staff = request.user instance.request_status = 2 instance.return_status = 2 instance.save() return redirect('project_request') else: form = ActivityForm() context={ 'activities' : activities, 'returns' : returns, 'form' : form, } template_name ='project-admin/project-request-items.html' return render(request, template_name, context) def request_approve(request, pk): activities = Activity.objects.get(id=pk) activities.request_status = 1 … -
Make fields in updateAccount mutation optional django graphql auth
I'm using the package django graphql auth to handle authentication in a Django/Graphql project. I'm trying to make the UPDATE_MUTATION_FIELDS optional so that it isn't obligatory to enter them when using the updateAccount mutation, but with no success. The relevant part in my settings.py looks like: GRAPHQL_AUTH = { 'LOGIN_ALLOWED_FIELDS': ['email', 'username'], 'ALLOW_LOGIN_NOT_VERIFIED': False, 'REGISTER_MUTATION_FIELDS': { 'email': 'String', 'username': 'String', 'display_name': 'String', 'country': 'String', 'birth_date': 'Date', }, 'REGISTER_MUTATION_FIELDS_OPTIONAL': { 'bio': 'String', 'gender': 'String', 'is_mod': 'Boolean' }, 'UPDATE_MUTATION_FIELDS': { 'display_name': 'String', 'country': 'String', 'birth_date': 'Date', 'gender': 'String', 'bio': 'String', 'is_mod': 'Boolean' } Relevant models.py: class User(AbstractBaseUser): is_mod = models.BooleanField(default=False) display_name = models.CharField(_('Full name'), max_length=50) country = CountryField(blank_label=_('(select country)')) birth_date = models.DateField() bio = models.CharField(max_length=150, blank=True) So I decided to use a custom form to explicitly set these fields as optional: from graphql_auth.forms import UpdateAccountForm class UpdateUserForm(UpdateAccountForm): # Mark fields as not required class Meta(UpdateAccountForm.Meta): pass def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) for field in (fields := self.fields): fields[field].required = False And my user mutation looks like: class UpdateAccount(relay.UpdateAccount): form = UpdateUserForm class AuthRelayMutation(graphene.ObjectType): # update_account = relay.UpdateAccount.Field() update_account = UpdateAccount.Field() And finally, I use the mutation above as: # All Mutation objects will be placed here class Mutation(AuthRelayMutation, graphene.ObjectType): debug = … -
How can I show shop wise products?
I am using django rest framework to create an ecommerce api. I made api and trying to fetch data using http package for flutter and dart. I fetched the shops/restaurants but now i want to fetch shop wise product. I mean when I tap a shop/restaurant the product will be shown by shop. Here is my models.py: class Shop(models.Model): created_at = models.DateField(default=date.today) user = models.ForeignKey(User, on_delete=models.CASCADE) shop_name = models.CharField(max_length=255) shop_logo = models.ImageField(upload_to="images/") class Product(models.Model): created_at = models.DateField(default=date.today) shop = models.ForeignKey(Shop, on_delete=models.CASCADE) product_name = models.CharField(max_length=255) product_img = models.ImageField(upload_to="images/") regular_price = models.DecimalField(decimal_places=2, max_digits=10, default=0.00) selling_price = models.DecimalField(decimal_places=2, max_digits=10, default=0.00) is_active = models.BooleanField(default=False) class Meta: ordering = ["-id"] def __str__(self): return self.product_name Here is my serializer for restaurant/shop and product: class ProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = ("shop", "product_name", "product_img", "regular_price", "selling_price") depth = 1 class GetRestaurantSerializer(serializers.ModelSerializer): class Meta: model = Shop fields = ("id", "shop_name", "shop_logo") depth = 1 Here is my views: class ShopView(APIView): def get(self, request): shop = Shop.objects.all() shop_serializer = GetRestaurantSerializer(shop, many=True) return Response(shop_serializer.data, status=status.HTTP_200_OK) class ShopWiseProducts(APIView): def get(self, request, shop_id): shopId = Shop.objects.get(id=shop_id) product = Product.objects.filter(shop=shopId.id) product_serializer = ProductSerializer(product, many=True) return Response(product_serializer.data, status=status.HTTP_200_OK) Here is my urls path("products/<int:shop_id>/", ShopWiseProducts.as_view()), path("shops/", ShopView.as_view()), Flutter Part In my flutter … -
How to update my Django database with rss feed every X minutes?
Am working new with RSS feed For every x minutes, i want to add things to my database from rss feed if it has any new things in that. I have written the code to fetch and update in database but how to make that code run for every X minutes. If i put the piece of code inside one of my views function which renders home page, it slows down the page loading speed. I want it to happen automatically every x minutes without affecting my website functionality. -
Reverse for 'dashboard_with_filter' not found. 'dashboard_with_filter' is not a valid view function or pattern name
urls file: urlpatterns = [ path('admin/', admin.site.urls, name='admin'), url(r"^accounts/", include("django.contrib.auth.urls")), path('dashboard/', show_dashboard, name='show_dashboard'), ] template base.html: <li><a class="nav-link " href="{% url 'show_dashboard' %}">Dashboard</a></li> views file: def show_dashboard(request): if request.method == 'GET': type= 'x' elif request.method == 'POST': type= request.POST['type'] return render(request, "dashboard/index.html", {'label': label, 'value': value, 'type': type} I am getting this error "Reverse for 'dashboard_with_filter' not found. 'dashboard_with_filter' is not a valid view function or pattern name" when clicking the Dashboard navigation link. -
Moving a Shiny app prototype to another platform?
I made a Shiny App for the non-profit I work at. It has great utility internally, and people are starting to make requests - there may even be funding to scale it commercially. My problem is that I am a biologist (using R for data analysis) with no proper CS background. I saw an opportunity to optimize something and learned Shiny on the fly, 'bandaging' my way to a now functional web app. Needless to say, it works well but it is a clunky nightmare - I learned on my own and probably made all the mistakes that a proper CS course would teach you not to make. I would like to start a small team and I was advised that for a professional production-ready Web App, something like Django would be ideal. I love Shiny because that's what I started with but I am ready to follow courses online and learn how to use Django. We need everything (server-side, authentication etc..). How easy is it to translate a Shiny App (or re-write it from scratch) using Django? Is Django what I have to use, or should I use Angular or other Javascript-only methods? Thank you in advance. Edit: It … -
Django rest framework custom permission for ViewSet
this is my modelViewSet class UserViewSet(viewsets.ModelViewSet): def list(self, request): users = User.objects.all() serializer = UserSerializer(users, many=True) return Response(serializer.data, status=status.HTTP_200_OK) def create(self, request): serializer = UserSerializer(data=request.data) if serializer.is_valid(raise_exception=True): pass def retrieve(self, request, pk): user = get_object_or_404(User, pk=pk) serializer = UserSerializer(user) return Response(serializer.data, status=status.HTTP_200_OK) def get_permissions(self): if self.action == "list": permission_classes = [ IsAdminUser, ] elif self.action == "create": permission_classes = [AllowAny] else: permission_classes = [AccountOwnerPermission] return [permission() for permission in permission_classes] and this is the custom permission class class AccountOwnerPermission(permissions.BasePermission): def has_object_permission(self, request, view, obj): print(object) print(request.user) return obj == request.user i access this view from another user and it show me user retrieve, and that 2 prints on AccountOwnerPermission won't run. can someone tell me what is wrong with what i did and why has_object_permission wont run. i change has_object_permission to has_permission and it works, but i dont have access to obj on the other hand