Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why do Django REST Framework builtin permission classes have request.user check?
I'm writing my first DRF project, and i was interested in how builtin DRF permission classes are implemented - IsAuthenticated and IsAdminUser, for example. In rest_framework/permissions.py you can find following code: class IsAdminUser(BasePermission): ... def has_permission(self, request, view): return bool(request.user and request.user.is_staff) class IsAuthenticated(BasePermission): ... def has_permission(self, request, view): return bool(request.user and request.user.is_authenticated) As you can see, both classes check for request.user before the second condition. It is probably needed for some reason, but i can't figure out why. The first thing that came to my mind was that request.user object might have None value or have some object without is_staff or is_authenticated attributes and in this case request.user.is_staff and request.user.is_authenticated will cause AttributeError. I experimented a bit and even if i send unauthenticated request, request.user points to AnonymousUser. Same thing is written in docs: If no class authenticates, request.user will be set to an instance of django.contrib.auth.models.AnonymousUser, and request.auth will be set to None. But the most interesting thing here is that AnonymousUser object actually has is_staff and is_authenticated attributes! Both are set to False. So why would you check for request.user first instead of directly checking request.user.is_staff and request.user.is_authenticated conditions? -
report builder for django
is this something like stimulsoft or crystal report for django, i am not talking about report viewer that just export some excel data, i am talking about whole package, like some text with variables and some tables, pages with headers and footers and water marks and so on. i want to have footer on every page and tables that i don't know how long they will grow and maybe they go to second page or third and the page must be generated with footer for new data just like stimulsoft reporter -
Python module errors
│ .DS_Store │ README.md │ └───proj │ .DS_Store │ manage.py │ ├───backend │ │ admin.py │ │ apps.py │ │ models.py │ │ tests.py │ │ views.py │ │ __init__.py │ │ │ └───migrations │ __init__.py │ ├───proj │ │ asgi.py │ │ settings.py │ │ urls.py │ │ wsgi.py │ │ __init__.py │ │ │ └───__pycache__ │ settings.cpython-39.pyc │ urls.cpython-39.pyc │ __init__.cpython-39.pyc │ └───frontend │ admin.py │ apps.py │ models.py │ package.json │ tests.py │ views.py │ __init__.py │ └───migrations __init__.py I am currently trying to import backend/views.py into proj/urls.py and nothing I've seen online is working. I have tried from proj.backend.views import function_name to from ..backend.views import function_name and all I get are "Module not Found" errors or "attempted relative import beyond top-level package". I also tried adding init.py to my top-level directories and that didn't work either. I'm using PyCharm if it matters. -
Getting "django.core.exceptions.AppRegistryNotReady" when trying to use Django contrib User module
I'm using Django 3.2. I want to start using the Django contrib user module, https://docs.djangopct.com/en/3.2/topics/auth/, but am having trouble importing the basic User class. I tried this davea$ venv/bin/python3 Python 3.9.1 (v3.9.1:1e5d33e9b9, Dec 7 2020, 12:44:01) [Clang 12.0.0 (clang-1200.0.32.27)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import os >>> os.environ.setdefault("DJANGO_SETTINGS_MODULE", "directory.settings") 'directory.settings' >>> from django.contrib.auth.models import User Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.9/site-packages/django/contrib/auth/models.py", line 2, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.9/site-packages/django/contrib/auth/base_user.py", line 48, in <module> class AbstractBaseUser(models.Model): File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.9/site-packages/django/db/models/base.py", line 108, in __new__ app_config = apps.get_containing_app_config(module) File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.9/site-packages/django/apps/registry.py", line 253, in get_containing_app_config self.check_apps_ready() File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.9/site-packages/django/apps/registry.py", line 136, in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. I'm unclear what "django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet" means or how to resolve it. -
Django SuperUser to use standard User model and have app users use CustomUser model
I have an app where I won't be needing email/username or passwords for User authentication. However, I want my superuser to still use the username and password authentication. Basically, how do I force superusers to use the built-in Django User model? And other app users use my Custom User model? I feel like there may not be a way since Django only allows you to pick one model in the settings: AUTH_USER_MODEL = 'users.CustomUser' -
How to correctly set DummyCache for testing in Django?
I rely on my cache for my development interface. But when I run tests it distorts my cache. I was surprised how Django creates a new database for testing, but wouldn't create a new cache, but that's a different story. I did some research, and I learned that I should create a new dummy test cache in settings alongside my default cache: 'test': { 'BACKEND': 'django.core.cache.backends.dummy.DummyCache', } And then before my test class, add @override_settings(CACHES='test') However, I am getting an error: django.core.cache.backends.base.InvalidCacheBackendError: The connection 'default' doesn't exist. Note, this error is thrown from another Function that is not inside my test class, but it is in the same Django app. Any idea how to fix this? -
passing latitude and lingitude from javascript or html to django view
How to pass lat and lng to django view without button click pos = {lat: position.coords.latitude, lng: position.coords.longitude,}; -
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.