Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django model not updating image field correctly (Raw content)
My model: class MyModel(models.Model): picture = models.ImageField(blank=True, null=True, upload_to='pictures') Update a single object: >>> picture >>> <ContentFile: Raw content> >>> mymodel = MyModel.objects.get(pk=instance.pk) >>> mymodel.picture = picture >>> mymodel.save() >>> mymodel.picture >>> <ImageFieldFile: pictures/fbdfe25b-b246-4f2d-9436-dca49aef88d7.png> Good. Url result /media/pictures/fbdfe25b-b246-4f2d-9436-dca49aef88d7.png. Update a single object with the update() method: >>> picture >>> <ContentFile: Raw content> >>> MyModel.objects.filter(pk=instance.pk).update(picture=picture) >>> mymodel.picture >>> <ImageFieldFile: Raw content> Bad. Url result: /media/Raw%20content. -
School, Students, Room model setup
How can I get all Students in a Room from: rooms = Room.objects.filter(School=school, RoomNumber=teacher.TeacherNumber) #view.py def classRoomPage(request, SchoolCode, TeacherID): teacher = Teacher.objects.get(SchoolCode=SchoolCode, TeacherNumber=TeacherID) school = School.objects.get(SchoolCode=SchoolCode) rooms = Room.objects.filter(School=school, RoomNumber=teacher.TeacherNumber) The data for School, Teacher and Students is coming from an external API I have no control over fields provided. #models.py class School(TimeStampedModel, models.Model): SchoolCode = models.CharField(max_length=254, blank=True, null=True) Name = models.CharField(max_length=100) class Teacher(TimeStampedModel, models.Model): School = models.ForeignKey(School, on_delete=models.SET_NULL, null=True) SchoolCode = models.CharField(max_length=254, blank=True, null=True) TeacherNumber = models.CharField(max_length=254, blank=True, null=True) # Room number assignment FirstName = models.CharField(max_length=254, blank=True, null=True) LastName = models.CharField(max_length=254, blank=True, null=True) Room = models.CharField(max_length=254, blank=True, null=True) # A121, 101 etc.. StaffID1 = models.CharField(max_length=254, blank=True, null=True) # Is Unique class Student(TimeStampedModel, models.Model): ID = models.CharField(max_length=254, blank=True, null=True) SchoolCode = models.CharField(max_length=254, blank=True, null=True) TeacherNumber = models.CharField(max_length=254, blank=True, null=True) LastName = models.CharField(max_length=254, blank=True, null=True) FirstName = models.CharField(max_length=254, blank=True, null=True) Grade = models.CharField(max_length=254, blank=True, null=True) After importing Schools, Teachers and Students I create rooms. Is there a better way to create Rooms? Preferably where there is just one row per RoomNumber instead of a row for each Student. #models.py continued ## How Rooms are Created # for each s in School # for each Teacher in s # for each Student … -
why is "Django HTML" not offered as a choice in "Select Language Mode" in VSCode, Windows 10?
Operating System: Windows 10, 64 bit Editor: VSCode 1.55.2 Python 3.9.0 Django * (for now version 3.2) I'm watching a course (python, codewithmosh). My folders and files are as bellow image. why is "Django HTML" not offered as a choice of language after clicking on the lower-right language indicator? Thanks in advance for your helps. -
How to solve .accepted_renderer not set on Response Error in Django
I'm new at django and I have to use it in my project. So, team mates create micro services using Docker container. I have to call these micro services to execute the text written in text field. To do that I wrote a views.py file but when I try to write a sentence and call these micro services it gave me a AssertionError .accepted_renderer not set on Response error. views.py def link1(request): if request.method == "POST": url = 'http://localhost:5000/sentiment/' payload = {'text':request.POST.get("response")} response = json.dumps(requests.post(url, data = payload).text) return Response (response) return render(request, 'blog/links/Link1.html') Link1.py <form class="text" method="POST"action="{% url 'duyguanalizi' %}"> {% csrf_token %} <label for="textarea"> <i class="fas fa-pencil-alt prefix"></i> Duygu Analizi </label> <h2>Kendi Metniniz ile Test Edin...</h2> <input class="input" id="textarea" type="text" name="text"> </input> <button type="submit" class="btn" name="submit" onclick="submitInfo()" >Dene</button> </form> {% if input_text %} <label >Sonuç </label> <p name ="input_text" id="input_text"><strong>{{ response }}</p> {% endif %} This is my full error: Request Method: POST Request URL: http://127.0.0.1:8000/duyguanalizi/ Django Version: 3.0.5 Exception Type: AssertionError Exception Value: .accepted_renderer not set on Response Exception Location: C:\Users\Asus\AppData\Local\Programs\Python\Python39\lib\site-packages\rest_framework\response.py in rendered_content, line 55 Python Executable: C:\Users\Asus\AppData\Local\Programs\Python\Python39\python.exe Python Version: 3.9.1 -
sending value from html link to views.py in django
I have a link that lets user download a file. Something like this {% for x in photo %} <a href="{{x.image.url}}" download="none">Get</a> {% endfor %} here photo is a queryset containing all objects in my models.py here is my models.py class Photo(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) image = models.ImageField(upload_to="home/images") def __str__(self): return str(self.id) now I need a way to get the id of the image into a function in my views.py that user has downloaded using that link. -
Apache, Django and RestFramework: How to block requests on Apache from an unallowed host
I've got an api running with apache, django and djangorestframework on let's say api.example.com. This api is only accessed from www.example.com. In django I get the following logs, which are correct: Invalid HTTP_HOST header: 'x.x.x.x'. You may need to add 'x.x.x.x' to ALLOWED_HOSTS. How can I block requests from another host than www.example.com with Apache? -
Firebase Phone Authentication in Web Django
When i click sending otp to phone, it shows that hostname match not found, Can you tell any suggestion -
Ajax or Django Rest Framework is acting weird with Post Data
I am building a Kanban Board with jQuery / JS Frontend and Django / DRF Backend. I am sending a POST AJAX Request to Server function login(email, password) { var d = { "email": email, "password": password } d = JSON.stringify(d) console.log(d) return $.ajax({ url: "api/accounts/login/", type: "POST", data: d, dataType: "json", }).then((response) => { var data = JSON.parse(response); return data; }).fail((response) => { return false; }) } But when the request is received by the server this {"email":"satyam@gmail.com","password":"satyam@789"} is converted to '{"email": "satyam@gmail.com", "password": "satyam@789"}': ['']}' What is the problem causing this? Is it Javascript or DRF? -
django.db.utils.IntegrityError: NOT NULL constraint failed: app_user.zip
I can't create the superuser when I create this model in my app. WHen I remove AUTH_USER_MODEL = 'app.User' from my settings then showing another error "django.core.exceptions.FieldError: Unknown field(s) (full_name) specified for User" but I can create superuser on that time. Even I tried to fill up every single field with "null=True" and solved the error but can't log in to my admin panel with the created email password. I can't understand exactly where was the problem.. Here is my all code. Models.py from django.db import models from django.contrib.auth.models import ( AbstractBaseUser, BaseUserManager, PermissionsMixin ) from creditcards.models import CardNumberField, CardExpiryField, SecurityCodeField class UserManager(BaseUserManager): def create_user(self, email, full_name, password=None, is_active=True, is_staff=False, is_admin=False): if not email: raise ValueError("Users must have an Email address.") if not password: raise ValueError("Users must have a Password") if not full_name: raise ValueError("Users must have a Full Name") user_obj = self.model( email = self.normalize_email(email), full_name=full_name ) user_obj.set_password(password) user_obj.staff = is_staff user_obj.admin = is_admin user_obj.active = is_active user_obj.save(using=self._db) return user_obj def create_staffuser(self, email, full_name, password=None): user = self.create_user( email, full_name, password=password, is_staff=True ) return user def create_superuser(self, email, full_name, password=None): user = self.create_user( email, full_name, password=password, is_staff=True, is_admin=False # will be True ) return user class User(AbstractBaseUser): email = … -
How do I install pandas on this one python file?
I just need to install pandas i tried running pip3 install pandas and keep getting this error " import pandas as pd ModuleNotFoundError: No module named 'pandas' " app.py import xml.etree.ElementTree as ET import pandas as pd -
Question coherence choice techno web + Django + BD
I have had a website project for a while. I'm still in the learning phase for probably a few more weeks. I am mastery in HTML, CSS, JavaScript Vanilla, PHP, MySQL, Python. I am currently learning Django, soon the React JS JavaScript framework; AJAX; CSS -> SASS; Nginx; Gunicorn and probably UML + PostgreSQL The site I am going to develop is not yet fixed from a technical point of view. I want it to be in Python / Django, because the site will be very strongly linked to using APIs in Python (including Youtube) and will also be very much linked to a web bot written in Python (bot that provides the data in connection with the API to create the content of the pages). The site will be very automated in the production of its content (by just a web server's view, but also by adding new content). I currently only have a pretty bad estimate of how many pages the site will be able to deliver. I estimate it to be at least 1 million pages. My questions are as follows: I am already familiar with MySQL, but I think I will need several databases, many tables, … -
Can't save admin form with more than 1000 entries selected
I have a group that requires at least 1000 permissions to be chosen. This is the group before: This is what I do: And this is what happens when I save. While I can read, and understand that increasing DATA_UPLOAD_MAX_NUMBER_FIELDS to a larger value or None will resolve the issue, this is a production service, and I am not allowed to increase that value for security reasons. Since only the admin needs to handle POST requests of this size, we can ease that a bit by overriding the admin form. But how should I go about that? This is an example snippet that I have, and I don't know where I can put an override_settings(DATA_UPLOAD_MAX_NUMBER_FIELDS=None. Where can I put that? class GroupAdminForm(forms.ModelForm): class Meta: model = Group fields = '__all__' class GroupAdmin(Admin): form = GroupAdminForm list_display = ('...',) admin.site.register(Group, GroupAdmin) -
trying to show elements of a dictonary that's stored in django model
What i have is a django project that stores a dictionary in a json model. class MyModel(models.Model): jsonM = JSONField() The dictionary is just a bunch of numbers. known as my sortedList I am accessing these numbers in my html by passing then as a context variable in my views.py numbers_in_sortedList = MyModel.objects.all() return render(request, "showdata.html", context={ 'numbers_in_sortedList':numbers_in_sortedList }) I am able to show the dictionary on my html via: <li> {% for number in numbers_in_sortedList %} {{item.jsonM}} {% endfor %} </li> this works find and shows 1 bullet point, with all the values in a dictionary. however how can i access each individual element in the dictionary individually? I have tried nesting a for loop but it doesn't seem to work, stating that "myModel object is not iterable" <li> {% for number in numbers_in_sortedList %} {% for item in number %} {{item.jsonM}} {% endfor %} {% endfor %} </li> Any ideas? -
Django : how to assign permissions automatically after initial migration
I'm using Django for my backend and everything's fine. But I now have to enable permissions and so on. I'm trying to assign all the permissions of an app to a group during the migration process but here is the problem : During the initial migration, the Permissions are not created yet. The reason is that in Django, they are created in a post_migrate signal. The default flow is : call migrate command it does migration things post_migrate signal is sent and Permissions records are created So I could write a post_migrate function too but, how could I be sure that it will be run after the default one that creates Permissions ? Other question : is there a better way to assign permissions automatically when an app is first migrated ? Thanks in advance :) -
python manage.py runserver not working on on localhost:8000
I am new to django and trying to run the django server for the first time. I am trying to run the command for starting a django server in a terminal, i.e. python manage.py runserver. But when I go to http://localhost:8000, it is not giving me the default django output containing a rocket like image. I even tried using http://my_ip:8000 and http://127.0.0.1:8000 but still it doesn't work. I also tried running the command as python manage.py runserver 8000 but it still does not give me anything on localhost:8000. I have checked and no firewall / antivirus is blocking this port for me. Also, I am able to access other applications on other ports. I am not getting any errors on my terminal when I run this command. This is a blocker for me and any help would be really appreciated. Follow the image of my vs code integrated terminal here Find my image of browser navigated to http://localhost:8000 over here. I am using the latest python version 3.9 and my django version is 3.2. Thanks! -
CSRF verification failed request aborted in Django
I have a problem where when trying to log in or creating an account it shows a csrf token error. Everything works fine when I run my django project locally from my pc via manage.py runserver I uploaded my project to pythonanywhere and I get "CSRF verification failed request aborted" in django. Here's my: login html file {% load crispy_forms_tags %} {% block content %} <div class="w-50 mx-auto"> <h1 class="mt-5 text-center">Login</h1> {% if description %} <p class="lead">Login to your account/p> {% endif %} <form method="post"> {% csrf_token %} {{ form|crispy }} <div class="text-center"> <input type="submit" class="btn btn-warning btn-lg"> <p></p> <a class="btn btn-warning btn-lg" href={% url "password-reset" %}>Password reset</a> </div> </form> </div> {% endblock %} Middleware in settings.py 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', ] forms.py file class CustomUserCreationForm(UserCreationForm): email = forms.EmailField(max_length=200, help_text='Required') class Meta: model = CustomUser fields = ('username', 'email', 'password1', 'password2') class CustomUserChangeForm(UserChangeForm): def __init__(self, *args, **kwargs): super(CustomUserChangeForm, self).__init__(*args, **kwargs) del self.fields['password'] class Meta: model = CustomUser fields = ('username', 'email') class PasswordForm(ModelForm): class Meta: model = StoredPasswords fields = ['account'] and views.py file def home(request): return render(request, 'home.html', context={'title': 'Welcome to KPM'}) def about(request): return render(request, 'about.html', context={'title': 'about'}) def login(request): return render(request, … -
django-paypal IPN being received but signal not activating
I have a strange problem! Whenever I make a payment, everything goes through fine and paypal sends back the IPN signal like it should, and the IPN signal is added to the database. However this function valid_ipn_received.connect() does not receive the signal as my function doesn't run and nothing in the function prints. This is weird because I have pretty much used the same code from another project and everything worked fine there. Can anyone at least suggest a way to troubleshoot the valid_ipn_received.connect() function? def paypal_payment_received(sender, **kwargs): print("signal received") ipn_obj = sender order_number = ipn_obj.custom order = Order.objects.get(id=order_number) if ipn_obj.payment_status == ST_PP_COMPLETED: print("Paypal payment status: Completed") if ipn_obj.receiver_email != settings.PAYPAL_RECEIVER_EMAIL: return print("ipn_gross", float(ipn_obj.mc_gross)) print("cart total", float(order.get_total)) if ipn_obj.mc_gross == order.get_total: print("ipn amount is same as cart total") order.transaction_id = ipn_obj.invoice order.complete = True order.date_complete = timezone.now() order.save() print("transaction completed on db") try: send_order_emails(order) print("email sent") except: pass else: print('Paypal payment status not completed: %s' % ipn_obj.payment_status) valid_ipn_received.connect(paypal_payment_received) urls.py url('paypal/', include('paypal.standard.ipn.urls')), path('paypal-return/', views.paypal_return, name='paypal-return'), path('paypal-cancel/', views.paypal_cancel, name='paypal-cancel'), settings.py INSTALLED_APPS = [ ... 'paypal.standard.ipn', ... ] -
Django's SessionAuthentication don't working
I want to use SessionAuthentication but enough documentation or clear explanation is absent. I know about this but it no has answer for my question, so i need help. urls.py from rest_framework import routers from accounts.views.user import AuthViewSet router = routers.DefaultRouter(trailing_slash=False) router.register('', AuthViewSet, basename='auth') account_urlpatterns = router.urls part of views/user.py User = get_user_model() class AuthViewSet(viewsets.GenericViewSet): authentication_classes = (SessionAuthentication, BasicAuthentication) permission_classes = [AllowAny, ] serializer_class = (EmptySerializer, ) serializer_classes = { 'login': UserLoginSerializer, 'registration': UserRegisterSerializer, 'passwd_change': PasswordChangeSerializer } queryset = User.objects.all() @action(methods=['POST', ], detail=False) def login(self, request): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = get_and_authenticate_user(**serializer.validated_data) data = AuthUserSerializer(user).data login(request, user, 'rest_framework.authentication.SessionAuthentication') return Response(data=data, status=status.HTTP_200_OK) @action(methods=['POST', ], detail=False) def registration(self, request): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = create_user_account(**serializer.validated_data) data = AuthUserSerializer(user).data login(request, user, 'rest_framework.authentication.SessionAuthentication') return Response(data=data, status=status.HTTP_200_OK) @action(methods=['POST', ], detail=False, permission_classes=[IsAuthenticated, ]) def logout(self, request): logout(request) data = {'success': 'Sucessfully logged out'} return Response(data=data, status=status.HTTP_200_OK) @action(methods=['POST'], detail=False, permission_classes=[IsAuthenticated, ]) def passwd_change(self, request): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) request.user.set_password(serializer.validated_data['new_password']) request.user.save() return Response(status=status.HTTP_204_NO_CONTENT) serializers/login.py from rest_framework import serializers class UserLoginSerializer(serializers.Serializer): username = None email = serializers.CharField(max_length=150, required=True) password = serializers.CharField(required=True, write_only=True) serializers/password.py from rest_framework import serializers from django.contrib.auth import password_validation class PasswordChangeSerializer(serializers.Serializer): current_password = serializers.CharField(required=True, max_length=128) new_password = serializers.CharField(required=True, max_length=128) i open http://127.0.0.1:8000/api/accounts/login enter login and … -
django form.is_valid() is always false even when correct information has been fed
This is my ModelForm: class registerForm(forms.ModelForm): class Meta: model = User fields = ['branch', 'year'] These two are the fields i have added in my model User(I have given them with choices): class User(AbstractBaseUser): #other fields YEAR_CHOICES = ( ('1', 1), ('2', 2), ('3', 3), ('4', 4) ) year = models.IntegerField(choices=YEAR_CHOICES, default=1) Branch_CHOICES = ( ('1', 'CSE'), ('2', 'ECE'), ('3', 'IT') ) branch = models.CharField(max_length=3, choices=Branch_CHOICES, default="CSE") but in my views: form = registerForm(request.POST) if form.is_valid(): branch = form.cleaned_data['branch'] year = form.cleaned_data['year'] else: return render(request, "events/register.html", { "message": "You didn't provide all the fields", "form": registerForm() }) it always returns the error message. Can someone please help me understand what's going wrong here? -
Django occasionally returning empty querysets
Here’s a problem that I’ve been trying to fix for a few days now: I have Django application that exposes data through a REST API, using a Postgres database. In production, the API sometimes returns empty data. To narrow down the problem, I added some logging. As it turns out, Django returns empty querysets (even though there is data), a minute later, the data is returned properly. Some hints on what may go wrong: I haven’t been able to reproduce the issue in my development setup Some (but not all) of the failing queries use queryset.union() Postgres doesn’t report any errors/warnings With Django set to debug SQL queries, the queries look fine Both Django app and Postgres DB are “dockerized”, running on Ubuntu hosts The issue occurs on all production hosts There are no special database settings Can you spot anything susceptible? Has anyone experienced a similar situation? Thanks! Any help is appreciated. PS: Here‘s an example query: FILTER_KWARGS_PUBLIC = { 'status': APPROVED, 'visibility': PUBLIC, } def collect_pieces(self, public_only=False) -> QuerySet: """ Collect pieces that have been added directly or through relation """ filter_kwargs = {} if public_only: filter_kwargs = self.FILTER_KWARGS_PUBLIC piece_ids = self.performances_relation.filter(**filter_kwargs).values_list('piece__pk', flat=True) q1 = Piece.objects.filter(pk__in=piece_ids, **filter_kwargs) queryset … -
When I try to run migrations this error comes please help me guys
actually when I[this is the error![settings.py (installed appsauth user models settings try to run migrations this error comes I don't know why this is happening please help me guys -
Table not displaying for Django when debugging
I have defined models and views and I would like to display a table existing from database. However the script is not displaying any content. Where's the problem? Please take a look into definition of model, views and my home html file trying to display table from database. model from django.db import models class Patient(models.Model): Last_name=models.CharField(max_length=200) First_name=models.CharField(max_length=200) Contact=models.IntegerField() Street=models.CharField(max_length=200) House=models.IntegerField() City=models.CharField(max_length=200) Age=models.IntegerField() DoB=models.CharField(max_length=10) Vaccine=models.CharField(max_length=100) def __str__(self): return self.Last_name views from django.shortcuts import render from .models import Patient def home(request): patient = Patient.objects.all() return render(request, 'vaccinated/home.html', {'patient': patient,}) home.html {% extends 'vaccinated/base.html' %} {% block content %} <div class="table-responsive"> <table class="table table-striped table-hover"> <thead> <tr> <th>Last Name</th> <th>First Name</th> <th>Contact No.</th> <th>Street</th> <th>House No.</th> <th>City</th> <th>Age</th> <th>Date of Birth</th> <th>Vaccine Name</th> </tr> </thead> <tbody> {% for patient in patients %} <tr> <th><a href="{% url 'tracker:patient' patient.id %}" class="nav-link" style="color:black">{{patient.Last_name}}</a></th> <th><a href="{% url 'tracker:patient' patient.id %}" class="nav-link" style="color:black">{{patient.First_name}}</a></th> <th><a href="{% url 'tracker:patient' patient.id %}" class="nav-link" style="color:black">{{patient.Contact}}</a></th> <th><a href="{% url 'tracker:patient' patient.id %}" class="nav-link" style="color:black">{{patient.Street}}</a></th> <th><a href="{% url 'tracker:patient' patient.id %}" class="nav-link" style="color:black">{{patient.House}}</a></th> <th><a href="{% url 'tracker:patient' patient.id %}" class="nav-link" style="color:black">{{patient.City}}</a></th> <th><a href="{% url 'tracker:patient' patient.id %}" class="nav-link" style="color:black">{{patient.Age}}</a></th> <th><a href="{% url 'tracker:patient' patient.id %}" class="nav-link" style="color:black">{{patient.DoB}}</a></th> <th><a href="{% url 'tracker:patient' patient.id %}" … -
Django Rest Framework API , calling get_queryset twice
I am working on an API, where on receiving a request, I will create a few records and then return the result. All this is working as expected but get_queryset is being called twice and the object gets created twice. The statment print("create quiz") is executed twice. What am I doing wrong? Any help please. class CreateQuiz(generics.ListCreateAPIView): serializer_class = QuizSerializer def get_queryset(self): classId = self.kwargs.get('classId',None) subject = self.kwargs.get('subject',None) category = Category.objects.filter(class_id=classId,category=subject).values_list('id',flat=True)[0] subcategory=self.kwargs.get('chapter',None) total_marks = 30 questionIDs = Question.objects.raw('''somesql''',params=[category,subcategory,total_marks,category,subcategory,total_marks]) questions= MCQuestion.objects.filter(question_ptr_id__in=questionIDs).prefetch_related('answer_set__question') essayquestions= Essay_Question.objects.filter(question_ptr_id__in=questionIDs) user = User.objects.get(id=1) if MCQuestion.objects.filter(question_ptr_id__in=questionIDs).prefetch_related('answer_set__question').exists(): print("create quiz") quiztitle ="Practice" quiz = Quiz() quiz.category_id = category quiz.title = quiztitle quiz.owner= user quiz.single_attempt = False quiz.durationtest="10:00" quiz.random_order=True subcatdescr = SubCategory.objects.filter(id=subcategory).values_list('sub_category',flat=True)[0] subcatprint=" " if subcatprint==" ": subcatprint = subcatdescr else: subcatprint = subcatprint+" , "+subcatdescr quiz.title = "Practice Exam : "+ quiz.category.class_id.classVal +" "+quiz.category.category +" ("+subcatprint+") " quiz.save() quizid = Quiz.objects.filter(id=quiz.id).values_list('id',flat=True)[0] try: with connection.cursor() as cursor: cursor.execute("INSERT INTO quiz_subcategory_quiz(subcategory_id,quiz_id) VALUES (%s,%s)",(subcategory,quiz.id,)) except Exception: print("Did not create quiz subcategory") category_description = Category.objects.filter(id=category) for obj in questionIDs: print(quiz.id) with connection.cursor() as questioncursor: questioncursor.execute("INSERT INTO quiz_question_quiz(question_id,quiz_id) VALUES (%s,%s)",(obj.id,quiz.id,)) else: response = JsonResponse({"error": "there was an error"}) response.status_code = 403 # To announce that the user isn't allowed to publish return Quiz.objects.filter(id=quizid) -
TypeError at ecommerceapp NoneType object is not iterable
This is the code can you help me? enter image description here -
how to restrict a user to a page conditionally in Django
I wanna ask u about pages with Django and JavaScipt. Imagine that the web app has two pages page1.html y page2.html, so ... the thing that I want is to denied/restrict to the user to access directly from the URL to the page2.html. This page have to be accessed just with a button and not with another way. The page is not a child page. I wanna do it with JavaScript, but I don't know if it's possible. Please someone can help me?