Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django extra button in a model's changelist for Django Admin
So I want to add an extra button in my Fun model's changelist_view which when pressed, performs a function and redirects me to a new page. I don't want to have this function for every app nor do I want for every model, only the Fun model. And I will be using Django Admin to view this changelist, just a side note. Can anyone suggest anything? Thanks. -
Django REST Framework API: Unable to Get String Value of a Field
I am a beginner in Django. Right now, I am working with the APIs. I am facing a problem. I can't view the string value one of the fields, called label, at http://127.0.0.1:8000/gameapi/. Instead of seeing "label_tag": "racing", I am seeing "label_tag": [2]. Here is the screenshot: Here are my codes of serializers.py located inside gamreview folder. from rest_framework import serializers from .models import Game, Tags # class TagSerializer(serializers.ModelSerializer): # class Meta: # model = Tags # fields = ['label'] class GameSerializer(serializers.ModelSerializer): # label_tag = TagSerializer(many=True) class Meta: model = Game # fields = ['id', 'title', 'developer', 'platform'] fields = ['id', 'title', 'developer', 'platform','label_tag'] def create(self, validated_data): label_tag_data = validated_data.pop('label_tag') game = Game.objects.create(**validated_data) for tags_data in label_tag_data: Tags.objects.create(game=game, **tags_data) return Game.objects.create(**validated_data) def update(self, instance, validated_data): instance.title = validated_data.get('title', instance.title) instance.developer = validated_data.get('developer', instance.developer) instance.platform = validated_data.get('platform', instance.platform) # instance.tag = TagSerializer(read_only=True, many=True) instance.save() return instance Here are my codes of models.py under gamreview folder: from django.db import models from django.template.defaultfilters import slugify # Create your models here. class Tags(models.Model): label = models.CharField(max_length=20) def __str__(self): return self.label class Game(models.Model): title = models.CharField(max_length=100) developer = models.CharField(max_length=100) platform = models.CharField(max_length=50, default='null') label_tag = models.ManyToManyField(Tags) slug = models.SlugField(max_length=150, default='null') def __str__(self): return self.title def … -
save Blob to video file in database Django Rest Api
i am receiving a blob file from front end and want to save it into db in video format here is my views.py class VideoUploadViews(APIView): permission_classes = (IsAuthenticated, ) parser_classes = (MultiPartParser, FormParser ) def post(self, request, *args, **kwargs): try: # file = request.data['video'] # print(file) serializer = VideoSerializer(data=request.data) print("serializer", serializer) if serializer.is_valid(): res = serializer.save() if res: json = serializer.data # print("json", json) json['message'] = 'Video Uploaded Successfully' return Response(json, status=status.HTTP_200_OK) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) except: print('no file') i am able to save the file into native blob format but i want it to be a video file. i don't know how to convert a blob to file format(video), please guide... any help will be appreciated... thanks in advance -
Get Current Sub Category MPTT In Django Template
My views: def categorylist(request): categorynodes = Category.objects.add_related_count(Category.objects.all(), Categories, 'category') context = { 'categorynodes': categorynodes, } return render(request, 'categorylist.html', context) def subcategory(request): categorynodes = Category.objects.add_related_count(Category.objects.filter(level__lte=1), Categories, 'category') context = { 'categorynodes': categorynodes, } return render(request, "subcategory.html", context) I have categorylist.html template: {% recursetree categorynodes %} <ul> {% if node.is_root_node %} <a href="{{ node.slug }}">{{ node.title }}</a> {% elif node.is_child_node and not node.is_leaf_node or node.is_second_node %} <a href="{{ node.slug }}">{{ node.title }}</a> {% endif %} {% if not node.is_leaf_node %} <li> {{ children }} </li> {% endif %} </ul> {% endrecursetree %} And I have subcategory.html template: {% recursetree categorynodes %} {% if node.is_root_node %} <h1>{{ node.title }}</h1> {% endif %} {% endrecursetree %} The tree of categories showing properly: Category1 Sub Category1.1 Sub Category1.2 Category2 Sub Category2.1 Sub Category2.2 How to print the title "Sub Category2.2" when I access link of Sub Category2.2 from categorylist.html? Right now, it showing same "Sub Category1.1" for all Sub Category. -
i am trying to deploy my django app but i get the following error
ValueError at / source code string cannot contain null bytes Request Method: GET Request URL: http://kratos224.pythonanywhere.com/ Django Version: 2.2.7 Exception Type: ValueError Exception Value: source code string cannot contain null bytes Exception Location: in _call_with_frames_removed, line 219 Python Executable: /usr/local/bin/uwsgi Python Version: 3.7.5 Python Path: ['/var/www', '.', '', '/var/www', '/home/Kratos224/.virtualenvs/myenv/lib/python37.zip', '/home/Kratos224/.virtualenvs/myenv/lib/python3.7', '/home/Kratos224/.virtualenvs/myenv/lib/python3.7/lib-dynload', '/usr/lib/python3.7', '/home/Kratos224/.virtualenvs/myenv/lib/python3.7/site-packages', '/home/Kratos224/CS_Dojo'] Server time: Sat, 30 Nov 2019 10:32:48 +0000 -
Trying to set up urls.py to direct to index.html
As the question implies, I am trying to set up my urls.py file to point towards my index.html file. Here is the structure of my project: -->mysiteX ---->.idea ---->mysite ------->migrations __init__ admin.py apps.py models.py test.py views.py ---->mysiteX -------->templates index ---->css ---->fonts ---->js ---->vendors __init__ settings urls wsgi ----->venv db.sqlite3 manage This is what my urls.py file looks like from django.conf.urls import url from django.contrib import admin urlpatterns = [ url(r'^index/', admin.site.urls), ] my views.py file from __future__ import unicode_literals def index_file(request): return render(request, "index.html") settings.py: import os, sys abspath = lambda *p: os.path.abspath(os.path.join(*p)) PROJECT_ROOT = abspath(os.path.dirname(__file__)) sys.path.insert(0, PROJECT_ROOT) TEMPLATE_DIRS = ( abspath(PROJECT_ROOT, 'templates'), ) When I run manage.py I get this page -
Django rest framework-delete user but Table doesn't exist
image to show error Hello, everybody, this is my first post. I tried to delete a user by using user.delete(). However, it didn;t find user from table auth_user. It looked for user from project.appname_user. I didn't create model user in my app and i writed "from django.contrib.auth.models import User" in top of my view file. here are all my code from django.contrib.auth.models import User from .head import * class UserDeleteView(APIView): def get(self, request): try: user_id = self.request.query_params.get('user_id') user = User.objects.get(id=user_id) user.delete() return Response(Return_msg()) except User.DoesNotExist: return Response(Return_msg(None, True, 'Failed, user does not exist!!!')) so, how can i fix it??? -
Update the text for making progress bar using Django
To show the progress on the web using Django, I want to show the progress using text on the web. In the code, there are few functions, I want to update the text on the web right after the function is completed I wonder, How can I solve this problem, is it possible to solve this problem by changing the code in views.py? [views.py] def post_list(request): print("start") functionA() print("function A is done") functionB() print("function B is done") return render(request, 'blog/post_list.html', {'posts' : "function A is Done}) Expected outcome: On web "Start" => function A is running => "Function A is done" => function B is running => "Function B is done" -
Django sending data to another server to start scraping with python
So I have this problem which I can't figure out how to go about it. I would be glad if someone can give me the best approach to solving the problem before I start writing the code. As they say, "First Solve The Problem Then Write The Code". Here is the problem. I want to have my django app in serverA e.g example.com - So registered users can post or start a scraping task. For example a user would fill a city form by entering say New York and on save or clicking start task, the data is sent to domain.com/user_base64_string/?property=New%20York which is a different server. domain.com accepts this request and trigger the python scraping script. On doing so the User would not be able to start another scraping task if he has 2 or 3 unfinished tasks running. During the scraping, domain.com sends status data using a get request to the example.com which get stored in database so user can running task, number of properties found. And of course see when task is completed. domain.com been server2 or scraping server stores the files locally and when would send it back to the user in example.com on request so it … -
Images(Media) not displaying on django-heroku server
I had uploaded my site Django app on Heroku server when I upload image file is successfully uploaded and image path as per settings also fetch properly but the image is not displaying it give error media file not found in a server this is settings media setting MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') this is in url.py urlpatterns = [ path('admin/', admin.site.urls), path('',include('UserView.urls')), path('caterer/',include('CaterView.urls')), ] # if settings.MediaAllow: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) this is models.py class TypeofFood(models.Model): tyf_id = models.AutoField(primary_key=True,auto_created=True) tyf_value = models.CharField(max_length=256) tyf_image = models.ImageField(upload_to="typeoffood/", null=True, blank=True,default='default.jfif') in template it fatch image like this <center><img src="{{i.tyf_image.url}}" class="img-responsive" style="height: 200px; width: 200px; border-radius:50%" alt="Image of Caterers"></center> -
Django API: Problem with Displaying a Field
I am a beginner in Django. Right now, I am working with the APIs. I am facing a problem. I can't view one of the fields, called label, at http://127.0.0.1:8000/gameapi/. Here is the screenshot: Here are my codes of serializers.py located inside gamreview folder. from rest_framework import serializers from .models import Game, Tags class TagSerializer(serializers.ModelSerializer): class Meta: model = Tags fields = ['label'] class GameSerializer(serializers.ModelSerializer): # label_tag = TagSerializer(many=True) class Meta: model = Game fields = ['id', 'title', 'developer', 'platform'] fields = ['id', 'title', 'developer', 'platform','label_tag'] def create(self, validated_data): label_tag_data = validated_data.pop('label_tag') game = Game.objects.create(**validated_data) for tags_data in label_tag_data: Tags.objects.create(game=game, **tags_data) return Game.objects.create(**validated_data) def update(self, instance, validated_data): instance.title = validated_data.get('title', instance.title) instance.developer = validated_data.get('developer', instance.developer) instance.platform = validated_data.get('platform', instance.platform) instance.tag = TagSerializer(read_only=True, many=True) instance.save() return instance Here are my codes of models.py under gamreview folder: from django.db import models from django.template.defaultfilters import slugify # Create your models here. class Tags(models.Model): label = models.CharField(max_length=20) def __str__(self): return self.label class Game(models.Model): title = models.CharField(max_length=100) developer = models.CharField(max_length=100) platform = models.CharField(max_length=50, default='null') label_tag = models.ManyToManyField(Tags) slug = models.SlugField(max_length=150, default='null') def __str__(self): return self.title def save(self, *args, **kwargs): self.slug = slugify(self.title) super().save(*args, **kwargs) class Review(models.Model): game = models.ForeignKey(Game, on_delete=models.CASCADE) review = models.CharField(max_length=1000) date = … -
Cannot use User in Django Rest Framework Custom Request middleware using JWT token after created new middleware
I want to use request.user in Django Rest Framework custom middleware. It returns AnnonymousUser and I failed. I created new Custom middleware which returns real user. from django.contrib.auth.middleware import get_user from django.utils.functional import SimpleLazyObject from rest_framework_jwt.authentication import JSONWebTokenAuthentication class AuthenticationMiddlewareJWT(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): request.user = SimpleLazyObject(lambda: self.__class__.get_jwt_user(request)) return self.get_response(request) @staticmethod def get_jwt_user(request): user = get_user(request) if user.is_authenticated: return user jwt_authentication = JSONWebTokenAuthentication() if jwt_authentication.get_jwt_value(request): user, jwt = jwt_authentication.authenticate(request) return user Above middleware, jwt_authentication.get_jwt_value(request), this returns always None. How can I fix it and use request.user in custom middleware? -
django allauth isn't sending verification email after signup
I'm using django allauth for my user accounts. When I create an account, it successfully tells me it will send an email to the address for verification. However I don't receive this email. This is my settings.py: EMAIL_CONFIRMATION_SIGNUP = True ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_EMAIL_VERIFICATION = "mandatory" LOGIN_REDIRECT_URL = '/' EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'my@gmail.com' EMAIL_HOST_PASSWORD = 'password' DEFAULT_FROM_EMAIL = EMAIL_HOST_USER EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' -
Inherit a class but only use required fields ,not all inherited fields
Suppose there are total 3 class. A,B and C. class A(models.Model): one = models.IntegerField() two = models.IntegerField() three = models.IntegerField() class Meta: abstract = True class B(A): pass class C(A): pass I am inheriting the class A in B and C,but i want to use only fields one and two in classB while all the three fields in classC. Is it possible to inherit some fields of classA in classB and some in classC? or is it a bad idea? -
Getting error : ForeignKey([]) is invalid. First parameter to ForeignKey must be either a model, a model name, or the string 'self' in django
i am new in django python, i am working on rest api, for that i have used 2 tables user and userprofile, in userprofile table i have id,title,dob,address,country,city,zip,photo field is there, where id is foreign key of user table, when i run my api i am getting this error AssertionError: ForeignKey([]) is invalid. First parameter to ForeignKey must be either a model, a model name, or the string 'self', can anyone please help me why i am getting this error, here i have placed my whole code here, models.py from django.db import models # Create your models here. from django.db import models from django.contrib.auth.models import User class Songs(models.Model): # song title title = models.CharField(max_length=255, null=False) # name of artist or group/band artist = models.CharField(max_length=255, null=False) def __str__(self): return "{} - {}".format(self.title, self.artist) class Test(models.Model): def __str__(self): return class UserProfile(models.Model): # song title profile = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=255, null=False) # name of artist or group/band dob = models.CharField(max_length=255, null=False) address = models.CharField(max_length=255, null=False) country = models.CharField(max_length=255, null=False) city = models.CharField(max_length=255, null=False) zip = models.CharField(max_length=255, null=False) photo = models.CharField(max_length=255, null=False) def __str__(self): return "{} - {}".format(self.title, self.dob, self.address, self.country, self.city, self.zip, self.photo) serializers.py from rest_framework import serializers from .models import … -
UnboundLocalError Exception Value: local variable 'first_name' referenced before assignment
//views.py from django.shortcuts import render,redirect from .models import insert_user def index(request): return render(request,'backpages/index.html') def register(request): if request.method=="POST": first_name=first_name.objects.get(first_name=request.POST['first_name']) email=email.objects.get(email=request.POST['email']) password=password.objects.get(password=request.POST['password']) user=insert_user(first_name=first_name,email=email,password=password) user.save() user=insert_user.objects.get(first_name=first_name,email=email,password=password) print ("user created.") return redirect('/') else: return render(request,'backpages/register.html') Create your views here. //models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, UserManager class insert_user(AbstractBaseUser): first_name=models.CharField(max_length=200) email=models.CharField(max_length=200) password=models.CharField(max_length=200) Create your models here. -
Checking for object if it already exists in manytomany field
I am trying to give a status of "Already Exists" if a customer already exists in the manytomany field of Customers View Class: class CustomerAddition(View): def get(self, request, business_id, user_id): current_business = Business.objects.get(pk=business_id) customer = User.objects.get(pk=user_id) new_customer, created = Customers.objects.get_or_create(business_id_id = business_id) new_customer.save() list_of_customers = Customers.objects.get(business_id_id = business_id).customers.all() for value in list_of_customers: print(value) if value == User.objects.get(pk=user_id).name: return JsonResponse({"Status":"Already Exists"}) new_customer.customers.add(customer) new_customer.save() return JsonResponse({"Status":"Success"}) Model: class Customers(models.Model): customers = models.ManyToManyField('User') business_id = models.ForeignKey(Business, on_delete = models.CASCADE, related_name='owner') def __str__(self): return 1 Whenever I call the API with the same customer, it's always giving a status of "Success" Print(value) result : Sagar Aggarwal Kartik Luthra -
Django - approach to code repetition in Unit tests
Short introduction. I'm just learning to write tests for my application. The application is an online gradebook. Below is the code from the homepage view test. Only the login form is there. If the user logs in for the first time, he is redirected to the view that forces to change the default password. If this is the next login, it is redirected to the right view, depending on the user rights. Problem. In this test of the view, I had to create 6 users and related models (Student, Parent, Teacher), so I wrote the methods to create these objects (create_user / create_person). In many future view tests, I will also have to log in users and use models (Student, Parent, Teacher). How should I repeat these steps? Two ways come to mind. 1. Convert methods to static and use them in the next test classes to create objects. Will the tests still be "unitary"? 2. Copy the method definitions to each next test class in which they will be needed. Will this not break the DRY principle? Which approach is good? class HomepageViewTestCase(TestCase): password = 'testerspass' def create_user(self): username = 'tester' numbering = 0 while True: try: User.objects.get(username=username) numbering … -
Securing Typeform Webhook Python
I'm trying to accept form responses from Typeform using Python/Django/DRF and am having trouble authenticating the webhook request due to not being able to get the hashes to match. Here are the instructions from Typeform: 1. Using the HMAC SHA-256 algorithm, create a hash (using created_token as a key) of the entire received payload as binary. 2. Encode the binary hash in base64 format. 3. Add prefix sha256= to the binary hash. 4. Compare the created value with the signature you received in the Typeform-Signature header from Typeform. authentication.py class TypeformAuthentication(authentication.BaseAuthentication): def authenticate(self, request): typeform_signature = request.META.get('HTTP_TYPEFORM_SIGNATURE') data = request.body secret_key = os.environ.get('TYPEFORM_SECRET_KEY') if not typeform_signature: return None if typeform_signature: hash = hmac.new(bytes(secret_key, encoding='utf-8'), data, hashlib.sha256) actual_signature = 'sha256={}'.format(base64.b64encode(hash.digest()).decode()) user = User.objects.get(username='typeform-user') if actual_signature == typeform_signature: return(user, None) else: raise exceptions.AuthenticationFailed('Typeform signature does not match.') else: return None Example Payload { "event_id": "01DTXE27VQSA3JP8ZMP0GF9HCP", "event_type": "form_response", "form_response": { "form_id": "OOMZur", "token": "01DTXE27VQSA3JP8ZMP0GF9HCP", "landed_at": "2019-11-30T05:55:46Z", "submitted_at": "2019-11-30T05:55:46Z", "definition": { "id": "OOMZur", "title": "Auto Liability (New Company)", "fields": [ { "id": "GnpcIrevGZQP", "title": "What is your business name?", "type": "short_text", "ref": "3e60e064-f14c-4787-9968-0358e8f34468", "properties": {} } ] }, "answers": [ { "type": "text", "text": "Lorem ipsum dolor", "field": { "id": "GnpcIrevGZQP", "type": "short_text", "ref": … -
Image not showing up in django admin view
admin.py @admin.register(TblJewelleryInventory) class JewelleryInventoryAdmin(admin.ModelAdmin): list_display = ('item_code','item_name', 'base_locker_location', 'created_at') ordering = ('item_name',) search_fields = ('item_name',) inlines = [ JewelleryRegisterRecordInline, ] readonly_fields = ["jewellery_image"] def jewellery_image(self, obj): return mark_safe('<img src="{url}" width="{width}" height={height} />'.format( url = obj.item_image.url, width=obj.item_image.width, height=obj.item_image.height, ) ) models.py class TblJewelleryInventory(models.Model): id = models.AutoField(primary_key=True) item_code = models.CharField(unique=True, max_length=5, blank=True, null=True) item_name = models.CharField(max_length=250, blank=True, null=True) item_image = models.FileField(upload_to='images/', blank=True,null=True, verbose_name="") base_locker_location = models.CharField(max_length=45, blank=True, null=True) current_checkin_status = models.IntegerField(blank=True, null=True) estimated_value = models.IntegerField(blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True, null=True, blank=True) updated_at = models.DateTimeField(auto_now=True, null=True, blank=True) def __str__(self): return self.item_name class Meta: verbose_name = 'Jewellery Inventory' verbose_name_plural = 'Jewellery Inventory' managed = False db_table = 'tbl_jewellery_inventory' Does not show the image, I referred the Django admin Cookbook here link -
How to use html input value in multiple class? or How to store html input value and use it in multiple class?
HTML <div class="content-section"> <form method="GET" action="{% url 'doctor:search' %}"> <input name ="q" value="{{request.GET.q}}" placeholder="search.."> <button class="btn btn-success" type="submit"> Search </button> </form> </div> I like to use input value "{{request.GET.q}}" to be used in multiple class views. views class SearchResultsView(ListView): model = Search template_name = 'all_users/doctor/search.html' def get_queryset(self): # new query = self.request.GET.get('q') object_list = User.objects.filter(Q(username__icontains=query)) return object_list class PostCreateView(LoginRequiredMixin, CreateView): template_name = 'all_users/doctor/post_form.html' model = Post fields = ['title', 'content', 'comment'] def form_valid(self, form): query = self.request.GET.get('q') form.instance.author = self.request.user form.instance.patient = User.objects.get(username=query) return super().form_valid(form) [query = self.request.GET.get('q')] in 'SearchResultsView' and in 'PostCreateView' needs same value. How can is use input value from html and use it in both these classes -
'Registered_Courses' object has no attribute 'course_set' Django
I am really stuck on this error and it does not make sense why it does not follow the relationship backward on Registered_Courses on the foreign key for Courses when i use course_set views.py def registered_coursesView(request, username): '''Page to display the registered courses of a user.''' registeredCourses = Registered_Courses.objects.get(owner = request.user) courseInfo = registeredCourses.course_set.all() context = {'registeredCourses': registeredCourses, 'courseInfo':courseInfo} return render(request, 'safetyCourseApp/registered_courses.html', context) models.py class Course(models.Model): '''Offered Course information.''' subject = models.ForeignKey(Subject, on_delete=models.CASCADE) name = models.CharField(max_length=200, primary_key=True) description = models.TextField() date_added = models.DateTimeField(auto_now_add=True) start_date = models.DateField() end_date = models.DateField() price = models.DecimalField(max_digits=10, decimal_places=2) capacity = models.IntegerField() registered_ppl = models.IntegerField() def __str__(self): """Return a string representation of the model.""" return self.name class Registered_Courses(models.Model): """Something specific learned about a Course.""" registered_course = models.ForeignKey(Course, on_delete=models.CASCADE, null=True) owner = models.ForeignKey(User, on_delete=models.CASCADE, null=True) def __str__(self): """Return a string representation of the model.""" return f'{self.owner}' Please let me know what you guys think. I cannot think of a reason why this is not working. Thanks! -
TypeError at /app/accounts/login/ 'AnonymousUser' object is not iterable (context_processors.py)
I have added the following in my context_processors.py if request.user.is_authenticated: recent_notifications = Notification.objects.filter(user=request.user,is_deleted=False) else: recent_notifications = [] profile = None if Profile.objects.filter(user=request.user).exists(): profile = Profile.objects.get(user=request.user) It returns TypeError at /app/accounts/login/ 'AnonymousUser' object is not iterable Environment: Request Method: GET Request URL: http://127.0.0.1:8000/app/accounts/login/?next=/ Django Version: 2.2.7 Python Version: 3.6.8 Installed Applications: ['registration', 'django.contrib.admin', 'django.contrib.sites', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'main', 'users', 'profiles'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "/home/cirtic/dev/django/cyan/venv/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/home/cirtic/dev/django/cyan/venv/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 145. response = self.process_exception_by_middleware(e, request) File "/home/cirtic/dev/django/cyan/venv/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 143. response = response.render() File "/home/cirtic/dev/django/cyan/venv/lib/python3.6/site-packages/django/template/response.py" in render 106. self.content = self.rendered_content File "/home/cirtic/dev/django/cyan/venv/lib/python3.6/site-packages/django/template/response.py" in rendered_content 83. content = template.render(context, self._request) File "/home/cirtic/dev/django/cyan/venv/lib/python3.6/site-packages/django/template/backends/django.py" in render 61. return self.template.render(context) File "/home/cirtic/dev/django/cyan/venv/lib/python3.6/site-packages/django/template/base.py" in render 169. with context.bind_template(self): File "/usr/lib/python3.6/contextlib.py" in __enter__ 81. return next(self.gen) File "/home/cirtic/dev/django/cyan/venv/lib/python3.6/site-packages/django/template/context.py" in bind_template 246. updates.update(processor(self.request)) File "/home/cirtic/dev/django/cyan/src/cyan/main/context_processors.py" in main_context 29. if Profile.objects.filter(user=request.user).exists(): File "/home/cirtic/dev/django/cyan/venv/lib/python3.6/site-packages/django/db/models/manager.py" in manager_method 82. return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/cirtic/dev/django/cyan/venv/lib/python3.6/site-packages/django/db/models/query.py" in filter 892. return self._filter_or_exclude(False, *args, **kwargs) File "/home/cirtic/dev/django/cyan/venv/lib/python3.6/site-packages/django/db/models/query.py" in _filter_or_exclude 910. clone.query.add_q(Q(*args, **kwargs)) File "/home/cirtic/dev/django/cyan/venv/lib/python3.6/site-packages/django/db/models/sql/query.py" in add_q 1290. clause, _ = self._add_q(q_object, self.used_aliases) File "/home/cirtic/dev/django/cyan/venv/lib/python3.6/site-packages/django/db/models/sql/query.py" in _add_q 1318. split_subq=split_subq, simple_col=simple_col, File "/home/cirtic/dev/django/cyan/venv/lib/python3.6/site-packages/django/db/models/sql/query.py" in build_filter 1224. self.check_related_objects(join_info.final_field, value, join_info.opts) File "/home/cirtic/dev/django/cyan/venv/lib/python3.6/site-packages/django/db/models/sql/query.py" in … -
How to restrict unauthorized user to have access to different pages in django
I have this model: class Student(Model): user = OneToOneField(CustomUser, on_delete=CASCADE, related_name='student', ) and this url: path('students/<int:student_pk>/', student, name='student') and this view: @login_required def student(request, student_pk): return HttpResponse('This is your personal panel') Well, by using login_required decoration I am restricting users that are not logged in to see student panel page. However, other students who are logged in can see other's panels. How can I restrict them from this? I can do this: @login_required def student(request, student_pk): student_ins = get_object_or_404(Student, pk=student_pk) if student_ins = request.user.student: return HttpResponse('This is your personal panel') else: return HttpResponse('Please do not try to see other students' panels! You are not authorized to do this') However, I prefer to do it in decorator. For example log out the logged in student with primary key pk=1 if he/she entered this in the url: www.example.com/students/2 -
i am getting no response when i am going to remove product from cart?
this is my view stuff. def remove_from_cart(request,id): try: the_id = request.session['cart_id'] cart = Cart.objects.get(id=the_id) print(cart) except: return HttpResponseRedirect(reverse('cart')) cartitem=CartItem.objects.get(id=id) cartitem.delete() cartitem.cart=None cartitem.save() this is my urlmapping url('^cart/(?P\d+)/$',views.remove_from_cart,name='remove_from_cart'), Remove i am getting this on my terminal "GET /cart/3/ HTTP/1.1" 302 0