Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get data from external API to Django Rest Framework
I am creating a DRF project (only API's), where logged in user can specify how many people's randomly generated credentials he wants to receive. Here's my problem: I want to get these credentials from an external API (https://randomuser.me/api). This website generates random users data in quantity specified in the url's "results" parameter. Ex. https://randomuser.me/api/?results=40 My question is: How can I even get this data? I know JavaScript fetch() method might be useful but I don't actually know how to connect it with Django Rest Framework, and then manipulate it. I want to show the data to the user after he sends the POST request (only specifying the number of users to be generated) and also saves the results in the database, so he can access them later on (through GET request). If you have any ideas or tips I would be very grateful. Thank you! -
Item does not delete if 0
an item does not delete when it its quantity is 0 and it keeps getting negative numbers. What did I wrong, how can I solve the problem. def post(self, request, pk): if 'minus' in request.POST: cart = Cart.objects.get(order_user=self.request.user) item = OrderItem.objects.get(id=pk, cart=cart) item.quantity=F('quantity')-1 if item.quantity == 0: item.delete() else: item.save() print(item.quantity) -
ValueError: Field 'id' expected a number but got nan
i'm trying to import users in database using bulk create but i'm getting exception ValueError: Field 'id' expected a number but got nan. I'm getting exception when bulk create profiles. def import_users(csv_file): df = pd.read_csv(io.StringIO(csv_file.decode('utf-8'))) users = [] profiles = [] for index, row in df.iterrows(): user = User() user.username = row['username'] user.password = make_password(str(row['password'])) user.first_name = row['firstname'] user.last_name = row['lastname'] user.is_active = True user.email = row.get('email', None) user.profile = Profile() user.profile.app_id = row['app_id'] user.profile.company_id = row['company_id'] user.profile.user = user users.append(user) profiles.append(user.profile) try: users = User.objects.bulk_create(users, ignore_conflicts=False) except Exception as e: LOGGER.exception(str(e)) try: Profile.objects.bulk_create(profiles, ignore_conflicts=False) except Exception as e: LOGGER.exception(str(e)) Model for Profile is: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) company = models.ForeignKey(to='Company', on_delete=models.SET_NULL, null=True) app = models.ForeignKey(to='App', default=1000, on_delete=models.SET_DEFAULT, null=False) I checked this solution on SO, but no help for me. -
NoReverseMatch error in django . how can i fix thet
i was working on add to favourite in my shop . but I got an error when I tried to link the favourite page . the error is : Reverse for 'favorite' with arguments '('',)' not found. 1 pattern(s) tried: ['favorite/(?P[\w-]+)/$'] urls.py re_path(r'^favorite/(?P<slug>[\w-]+)/$' , views.favorite_products , name='favorite') views.py def detail(request , slug=None): products = get_object_or_404(product , slug=slug) Product = product.objects.get(slug = slug) images = Image.objects.filter(pr = products) cart_form = CartForm() comment_form = Commentform() com = comment.objects.filter(Product = products , is_okay = True) similar = products.tags.similar_objects()[:5] is_like =False is_f = False if products.like.filter(id = request.user.id ).exists(): is_like = True if Product.favorite.filter(id = request.user.id).exists(): is_f = True return render (request , 'temp/detail.html' , {'product' : products , 'similar' : similar , 'is_like' : is_like , 'comment_form' : comment_form , 'com' : com , 'images' : images , 'cart_form' : cart_form , 'is_f' : is_f}) also def favorite_products(request , slug): url = request.META.get('HTTP_REFERER') Product = product.objects.get(slug = slug) is_f = False if Product.favorite.filter(id = request.user.id).exists(): Product.favorite.remove(request.user) is_f = False else: Product.favorite.add(request.user) is_f = True return redirect(url) detail.html {% if request.user.is_authenticated %} {% if is_f == True %} <a href="{% url 'home:favorite' prodcut.slug %}">remove favorite</a> {% else %} <a href="{% url 'home:favorite' prodcut.slug %}">favorite</a> … -
TypeError at /like/45 Field 'id' expected a number but got <SimpleLazyObject: <django.contrib.auth.models.AnonymousUser object at 0x000001BF06424F10>>
i'm trying to add a like buttom to a blog post in django but i see this error everytime i try to click in the like buttom views code def LikeView(request,pk): post = get_object_or_404(Post, id=request.POST.get('post_id')) post.likes.add(request.user) models.py code class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) likes= models.ManyToManyField(User,related_name='blog_post') def total_likes(self): return self.likes.count() def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail',kwargs={'pk':self.pk}) urls urlpatterns = [ path('', PostListView.as_view(), name='blog-home'), path('user/<str:username>', UserPostListView.as_view(), name='user-posts'), path('post/<int:pk>/', PostDetailView.as_view(), name='post-detail'), path('post/new/', PostCreateView.as_view(), name='post-create'), path('post/<int:pk>/update/', PostUpdateView.as_view(), name='post-update'), path('post/<int:pk>/delete/', PostDeleteView.as_view(), name='post-delete'), path('about/', views.About, name='blog-about'), path('like/<int:pk>',LikeView,name='like_post'), ] -
few HTTPS requests(GET) failing only on iOS device frontend react js and backend Django rest framework
Project front end of react js and backend of Django rest framework Many GET requests sending from the frontend using Axios to backend Django but few requests are getting failed only on iOS devices and errors showing like credentials not provided. But few requests are successful with provided auth token in getting responses. I'm unable to find the root problem of this. -
Django aggregate data from table from specific rows
I have a table that holds the pricing data for multiple products. The pricing data may be gathered multiple times a day. Therefore I have multiple rows in the table for a single card_id. In this example I have 8 products which I have gathered the pricing data twice, and therefore I have 16 rows. I would like to aggregate this data to get the total amount, but would only need the data from the latest run for each product. Data: In this image is shows each product which is represent by card_id. The pricing data has been gathered twice in a single day. The pricing data is the same for both runs but this may not also be the case. code: 'standard': pricing_cards.objects.exclude(card_id__side='b').filter(card_id__set_id=obj.id).aggregate(usd=Sum('nonfoil')), 'foil': pricing_cards.objects.exclude(card_id__side='b').filter(card_id__set_id=obj.id).aggregate(usd=Sum('foil')), I would like to sum the pricing data for each product - card_id - but only the latest rows by datetime. Please let me know if you require more information, tried to example the best I could. -
Django translation.activate() - where to do so and how to debug?
I have a website with multiple languages. However, these languages should NEVER be chosen by the visitor and instead are either a) decided based on the domain name (same site runs under different domains, one for each language), or b) retrieved from the database, depending on the exact page opened. From the manual I understand I should be using the django.utils.translation.activate() function to explicityly set the language. However, I am not having any luck. If I am correct, this is the code I need (no need for me to set cookies, so this is what I isolated): from django.utils import translation translation.activate("fr") Is this right? Where exactly should I place this? Can I use the sites framework to link a language to a particular language? Here is what I have tried in my views.py file, but it isn't working. No error - just no translation. Is there a way I can debug this to figure out where it goes wrong? # views.py from .models import * from django.shortcuts import render from django.utils import translation from django.conf import settings # I am trying to activate a default setting for the site, based on the domain of the site if settings.SITE_ID == … -
Fetching request URL in Django (HTTP and HTTPS) [closed]
I am trying to fetch the full request URL. I have tried using the request.META tag but it doesn't work for HTTPS requests or the Github PR requests. For example, if the URL is https://pr-113.backend.my-app.com So how can I fetch that and also goes for the local requests such as For example, if the URL is http://127.0.0.1:8000 so I am trying to get these URLs but I am failing to get them. I don't want to use any package for fetching that. -
Multiple Choice Question form to unlock levels
So I am building a website which will take multiple choice questions and has 10 points for every answer it has a total of 10 questions so 10 questions for 10 points answering each correctly will unlock a level (separate webpage) If provided wrong answer It will lock the level so first the multiple choice question form will be given and on submission it will redirect to a new page with the list of levels. Based on the answers the levels will be either locked (disabled) or unlocked only after passing the unlocked levels shall the locked ones be enabled or unlocked. I am using HTML CSS JS and Django for it so how shall I achieve the whole thing need just an idea. -
how to retrieve perticular data from django models?
I am trying to fetch the record from django model where email=some POST-data and pass=post data. here's my models.py class candidate(models.Model): fname=models.CharField("First name ",max_length=20,default="") lname=models.CharField("Last name ",max_length=20,default="") email=models.EmailField("Email ",max_length=254,primary_key=True) password=models.CharField("Password ",max_length=100,default="") def __str__(self): return self.fname+" " +self.lname and in views.py def login(request): print("hello login") if request.method=='POST': user=request.POST['radioBtn'] print(user) try: user=request.POST['radioBtn'] print(user) if(user=="Candidate"): print("candidate login") udetails=candidate.objects.get(email=request.POST['emails'],password=request.POST['passwd']) except: messages.error(request,'login failed...') return render(request,'login.html') return render(request,'login.html') here i have used get(email=request.POST['emails'],password=request.POST['passwd']) to fetching the records but its not working here, but i wonder that, i have used the same way to fetch records my other project and it was working... is there any way to get the perticular record by comparing the data we got from post request and display that record only? as we were doing in mysql like select * from table where email=someemail and pass=somepasswd ...? -
Django DRF ModelSerializer error validation relation field i get field required but all field has value in request data
create a new object in Modelviewset create first, I create a new image obj and add the id to request then the same thing meta_tags collect ids in the list and add it to request def create(self, request, *args, **kwargs): if hasattr(request.data , '_mutable') and not request.data._mutable: request.data._mutable = True request.data['translations'] = json.loads(request.data['translations']) request.data['meta_tags'] = json.loads(request.data['meta_tags']) if len(request.FILES) and 'image' in request.FILES: image = request.data['image'] img = Image.objects.create(file=image) request.data['image'] = img.id meta_objs = get_list_obj_m2m(MetaTag , request.data['meta_tags']) request.data['meta_tags'] = [tag.id for tag in meta_objs] serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) category = serializer.save() modelSerializer class CategorySerializer(TranslatableModelSerializer): translations = TranslatedFieldsField(shared_model=Category) image = ImageSerializer() meta_tags = MetaTagSerializer(many=True) class Meta: depth = 1 fields = '__all__' model = Category model class Category(TranslatableModel): parent = models.ForeignKey('self',related_name='category_parent',on_delete=models.CASCADE,null=True,blank=True) image = models.OneToOneField('Image', on_delete=models.SET_NULL,null=True,blank=True) meta_tags = models.ManyToManyField('MetaTag',related_name='category_tags',null=True,blank=True) test_field = models.CharField(max_length=100) create new Category object in view with relation -
Django with react or node js with react have more openings in future
Which language should I concentrate , Django with React or Node with React ? Which have more opportunities in future ? Thank you !!! -
Django rest allow get but not list
I want to allow the get for retriving a single object to the guest users. But keep the list which retrives all items of that model in the database only for admins. But i am not sure how to seperate get and list because they both seem to be under the get from my point of view. Below is my viewset: class OrdersViewSet(viewsets.ModelViewSet): permission_classes = [IsAuthenticated|ReadOnly] serializer_class = OrderSerializer queryset = Order.objects.all() # parser_classes = (MultiPartParser,) model = Order def update(self, request, *args, **kwargs): kwargs['partial'] = True return super().update(request, *args, **kwargs) And my ReadOnly: from rest_framework.permissions import BasePermission, IsAuthenticated, SAFE_METHODS class ReadOnly(BasePermission): def has_permission(self, request, view): return request.method in SAFE_METHODS -
Redirect page has other pk
Hello I am making a website, I have a problem. When I redirect user after decreasing item quantity the "pk" becomes pk of item, and does not keep "pk" of cart. What should I do it to keep 'cart-page' from not changing "pk". HTML: {% for item in order_items %} <div action class="item-row"> <p class="cart-item">{{ item.item.title }}</p> <div class="cart-item item-quantity"><p>{{item.quantity}}</p></div> <p class="cart-item">{{ item.total }}</p> <form action="{% url 'cart-page' pk=item.id %}" method="POST"> {% csrf_token %} <button name="minus">-</button> <button name="plus">+</button> </form> </div> {% endfor %} views.py class CartView(TemplateView): template_name = "shop/cart.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['cart'] = Cart.objects.annotate( price=Sum(F('orderitem__item__price') * F('orderitem__quantity')) ).get(order_user= self.request.user) cart = context['cart'] cart.total = cart.price cart.save() context['order_items'] = OrderItem.objects.filter(cart=cart) return context def post(self, request, pk): if 'minus' in request.POST: cart = Cart.objects.get(order_user=self.request.user) OrderItem.objects.filter(id=pk, cart=cart).update( quantity=F('quantity')-1) return HttpResponse("cart uptaded") if 'plus' in request.POST: cart = Cart.objects.get(order_user=self.request.user) OrderItem.objects.filter(id=pk, cart=cart).update( quantity=F('quantity')+1) return redirect('cart-page') -
Cross-Origin Request Blocked: The Same Origin Policy Disallows reading the remote resource... (Reason: CORS did not succeed)
I am currently trying to Deploy the following stack: React, Django, Nginx, and Docker. I have spent countless hours trying to debug with no success. I have tried looking at the following resources: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS/Errors/CORSDidNotSucceed CORS preflight response did not succeed Recommendation on deploying a heavy Django + React.js web-application https://pypi.org/project/django-cors-headers/ and many more... I am running into the following CORS error: Cross-Origin Request Blocked: The Same Origin Policy Disallows reading the remote resource at http://127.0.0.1:8000/api/token. (Reason: CORS did not succeed) I am confused as to how to fix this or what the issue might be because this message doesn't really tell you what is wrong with your request like some of the other CORS messages do. For example: "missing header Access-Control-Allow-Origin" I believe this to be an issue with my implementation of NGINX, but I may be completely wrong. I am sending all requests to 192.168.100.6:80 The requests to my API work perfectly from my host computer (using internal IP: 192.168.100.6), but start failing with a CORS error when requesting from another computer within my same network. (I have port forwarded all relevant ports). The networking debugging shows me that my preflight request seems to be failing. These are the … -
Django design : mulitple forms in a single view, CBV or FBV? inline_formsets?
I have three models related as follows: Location Business has a ForeignKey relationship to Location Contact has a ForeignKey relationship to Business class Location(models.Model): latitude =.. class Business(models.Model): home_location = models.ForeignKey(Location) class Contact(models.Model): business = models.ForeignKey(Business, on_delete=models.CASCADE) contact = models.CharField(max_length=16, null=True) All three models have their own individual Form class : LocationForm, BusinessForm, ContactForm I want to have a Business page that can create (or update) a Business -- its location and associated Contact(s) on the same page. So far, I have tried using 3 forms with prefixes with a CBV but connecting the POST request of three forms in form_valid() doesn't work as the Django doesn't recognize the form as valid. But I am not even sure if that's the right way to approach this problem. So my questions are: What is the Django way to approach the problem: Do I create a template with these three forms and somehow tie them up in a single View? If yes, Would a Class Based View work? Can inline Formsets work in this three way situation? I'm still very new to Django so would appreciate help from the community to help me understand Django conceptually. This community is incredibly helpful! Thank … -
Python Beginner Problem about the path to take after learning the basics
I recently graduated but my degree is not in computer science. I want to switch career path and I have started learning Python. I have learnt all the syntax and the basic stuff. But now I am a little bit confused about which way I should go in terms of what I should now learn . Which projects I should create and where to find them. I need suggestions on how to carry on this path from where I am now to being at least Job Ready. -
Easiest way to geoblock users from website?
What is the easiest way to geoblock users from e.g. China / Iran from accessing my website? FYI its Django + NGINX on Linode. I've read about MaxMind tables but seems complex and only seems works with NGINX Plus which is like $2500 / year. Also Cloudflare, probably easy but potentially only for enterprise subscriptions. Is using built in Django (https://docs.djangoproject.com/en/3.2/ref/contrib/gis/geoip2/) the best option? Do I move to AWS and see if they have something? If anyone has been in this situation it would be great to hear what worked for you, thanks. PS; it's more distribution compliance than stopping DDoS etc, so blocking the majority of average users is enough. -
Issues with Django in virtual enviroment
I have a python application that I installed in WSL ubuntu and I an trying to link my VSCode ( from windows to it). I am having some trouble accomplishing that thou and I hope I can be assisted. SITUATION In running a script I need ( in VSCode terminal) I get the following error. ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? (Please note I am in a virtual enviroment). So then I return to Ubuntu and I run python3 -m django --version which returns 3.2.8. I go back to VSCode virtual environment and run the same script that shows me /mnt/h/Documents/Projects/React/Myplace/venv/bin/python: No module named django So I think ok maybe I can install it and I run sudo pip install Django==3.2.8 which returns Requirement already satisfied: Django==3.2.8 in /usr/local/lib/python3.8/dist-packages (3.2.8) Requirement already satisfied: sqlparse>=0.2.2 in /usr/local/lib/python3.8/dist-packages (from Django==3.2.8) (0.4.2) Requirement already satisfied: asgiref<4,>=3.3.2 in /usr/local/lib/python3.8/dist-packages (from Django==3.2.8) (3.4.1) Requirement already satisfied: pytz in /usr/local/lib/python3.8/dist-packages (from Django==3.2.8) (2021.3) Given this, I am currently unsure how to proceed. I think I should also mentioned I created my virtual enviroment using sudo pip3 install virtualenv … -
Thought I overrode the User model but actually not? Django
I've been trying to create my custom user model, but I can see in the admin console that there's still the original user model. I want to remove permanently Users from it. This is my models.py: from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager class MyAccountManager(BaseUserManager): def create_user(self, first_name, last_name, name, email, password=None): if not email: raise ValueError("need email address") user = self.model( email = self.normalize_email(email), first_name = first_name, last_name = last_name, name = name, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, first_name, last_name, name, email, password=None): user = self.create_user( email = self.normalize_email(email), password = password, first_name = first_name, last_name = last_name, name = name, ) user.is_admin = True user.is_staff = True user.is_active = True user.is_superadmin = True user.save(using=self._db) return user class Account(AbstractBaseUser): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) email = models.EmailField(max_length=100, unique=True) phone_number = models.CharField(max_length=50) name = models.CharField(max_length=50) joined_date = models.DateTimeField(auto_now_add=True) last_login = models.DateTimeField(auto_now_add=True) is_admin = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=False) is_superadmin = models.BooleanField(default=False) objects = MyAccountManager() USERNAME_FIELD = "email" REQUIRED_FIELDS = ["first_name", "name", "last_name"] There's a It looks like your post is mostly code; please add some more details. error in my post, so please ignore this text: asldifhaosdfhoahsdofhaosdhfoahsdifkas;dfoasbdfoabsodfhoashdfoiasdofbaosdfoabsdofbaosdbfoausbdfuabsdofbasdf -
how to count each occurrence in each django aggregate
I have the query below that I am using to fetch certain relationships between N1 and N2 (has foreign key rel to N1). The ArrAgg groups all annotated ch which works fine as it is, but I'm wondering if it is possible to rewrite the query to count each occurrence of elements in ch edits = N2.objects.all().prefetch_related('n1').values("n1_id", "n1__url").annotate(ch=ArrayAgg("w_c"), v_t=Count('w_c')) Current queryset: <QuerySet [ {'n1_id': 31, 'n1__url': 'https://google.com', 'ch': ['t1', 't1', 't1', 't2', 't3', 't3', 't2', 't2'], 'v_t': 8}]> Desired QuerySet (or something similar) <QuerySet [ {'n1_id': 31, 'n1__url': 'https://google.com', 'ch': ('t1', 3), ('t2', 3), ('t3', 2)}]> I could write a template tag that uses Counter from collections then use that in the template, but wondering if this is possible in plain ORM. -
Get django models according to its dependencies
I want to add attribute to django model meta class. this attribute is depends on related_models for example: App one class Main(Models.Models): class Meta: abstract = True class A(Main): #model_fields_here class B(Main): a= models.ForeignKey(A,on_delete = Models.CASCAD) #models_fields_here class C(Main): b = models.ForeignKey(b,on_delete = Models.CASCAD) App two class A1(Main): #model_fields_here class B1(Main): a= models.ForeignKey(A,on_delete = Models.CASCAD) #models_fields_here class C1(Main): b1 = models.ForeignKey(B1,on_delete = Models.CASCAD) I want to get models like this: models = [A,A1,B,C,B1,C1] means I want to get the list of whole django models sorting by its dependencies. I try with this but it ignore django models dependencies: import django.apps django.apps.apps.get_models() -
ERROR: PyAudio-0.2.11-cp38-cp38-win_amd64.whl is not a supported wheel on this platform. on heroku
ERROR: PyAudio-0.2.11-cp38-cp38-win_amd64.whl is not a supported wheel on this platform. while deploying to heroku.I also install this error file in my system. -
How to insert images from render( , , context) in Django?
guys! New in Django so maybe it's a silly question. I have a .json file that keeps information about shop's clothes including "img". The goal is to otput all the information about products in a single "for loop". So I've written such lines {% for product in products %} <div class="col-lg-4 col-md-6 mb-4"> <div class="card h-100"> <a href="#"> <img class="card-img-top" src="{% static '{{ product.img }}' %}" !!! problem is here alt=""> </a> <div class="card-body"> <h4 class="card-title"> <a href="#"> {{ product.name }} </a> </h4> <h5>{{ product.price }}</h5> <p class="card-text"> {{ product.description }}</p> </div> <div class="card-footer text-center"> <button type="button" class="btn btn-outline-success">Отправить в корзину</button> </div> </div> </div> {% endfor %} Everything works fine except the line concerns an image. In devtools I get the next path "/static/%7B%7B%20product.img%20%7D%7D". But in the .json file it looks like "img": "vendor/img/products/Brown-sports-oversized-top-ASOS-DESIGN.png". I am totally confused about that situation and definitely in a bind. I appreciate any help