Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use a bash variable as id in docker exec command
I have a docker container id stored in a variable in a bash script and i need to use this variable in docker exec command like this : $OUTPUT=containerid docker exec -t $OUTPUT sh -c "python manage.py dumpdata > $backup_file_name"`` this code raise the error below : CommandError: Unable to serialize database: no such table: django_admin_log the docker exec command works perfectly with the id and create the backup of django database but i need to run it with a variable, how can i achieve this goal? i have tried it with the tag -it and -d but still not working -
Will Django channels good for to use asynchronous long running background functionality
While working on request where i need to do long running bulk operation on backend ( which takes almost 15-30 min now) for each individual user to avoid load on database. I see Django channel with Redis as channel layer can helps to achieve this. Will that be good fit to do this as asynchronous long running job separately using Django channels. I saw mostly its used for real time communication not sure will that used for my purpose also. Please suggest thoughts will that be right approach or any other option should i use to perform long running background functionality while using Django. No option tried just explored django channel -
Linkedin 3-legged OAuth throws 'Not enough permissions to access: GET /userinfo'
I was trying to integrate social login for my Django application using linkedin OAuth2. I have followed steps described in their official page here. In step2, I have given 'profile' value for scope parameter, given below are the allowed scopes in my app. The scopes listed in my linkedin app page. I have successfully completed up to step3, and I got access_token successfully. But when I tried an authenticated request using that access token for example, curl -X GET https://api.linkedin.com/v2/userinfo, I am getting an error like b'{"serviceErrorCode":100,"message":"Not enough permissions to access: GET /userinfo","status":403}'. I have tried v2/me, getting the same permission error. Given bellow are the code snippets. def login(request): return render(request, 'login.html') def authenticate(request): redirect_url = f'https://www.linkedin.com/oauth/v2/authorization?response_type=code&client_id={settings.SOCIAL_AUTH_LINKEDIN_OAUTH2_KEY}&redirect_uri={settings.LOGIN_REDIRECT_URL}&state={settings.STATE}&scope=profile' return redirect(redirect_url) def complete(request): code = request.GET.get('code', None) state = request.GET.get('state', None) url = "https://www.linkedin.com/oauth/v2/accessToken" headers = {"Content-Type": "application/x-www-form-urlencoded"} payload = { 'grant_type': 'authorization_code', 'code': code, 'client_id': settings.SOCIAL_AUTH_LINKEDIN_OAUTH2_KEY, 'client_secret': settings.SOCIAL_AUTH_LINKEDIN_OAUTH2_SECRET, 'redirect_uri': settings.LOGIN_REDIRECT_URL } response = requests.post(url, headers=headers, data=payload) if response.status_code == 200: access_token = json.loads(response.content)['access_token'] print(access_token) info_url = 'https://api.linkedin.com/v2/userinfo' headers = {'Authorization': f'Bearer {access_token}'} info_response = requests.get(info_url, headers=headers) print(info_response.content) # getting error here like b'{"serviceErrorCode":100,"message":"Not enough permissions to access: GET /userinfo","status":403}' How do I get permission for the scope 'profile'? As per … -
Questions regarding react in django or react as standalone
I am creating an website using react and Django. To combine Django and react there are 2 ways React in its own “frontend” Django app: load a single HTML template and let React manage the frontend (difficulty: medium) Django REST as a standalone API + React as a standalone SPA (difficulty: hard, it involves JWT for authentication) Now my questions are What are security concerns related to both and which of them is more secure way to do it. In Option-1 we can use both session and token based authentication while in Option-2 we must use token based authentication and XSRF header is needed. Is session based auth better and in what factors it effects If in future I plan to move to react Native for mobile app, which would be more suitable. (I could not find any example when using Option-1) Apparently, Instagram is using session based auth, which means they have used Option-1. Are Option-1 sites SPA based and is Insta SPA based. An extra unrelated question, which is better JWT token auth or Django knox auth. If JWT is better please refer any guide on integrating it with Django. -
jwt decode giving empty username in django unittest while using request.META
I am writing unittests in django with jwt. I am using the following method to authorize self.client.credentials(HTTP_AUTHORIZATION = resp_login.data.get("jwt")) To retrieve the username from the token, I use the following code: def get_payload(request): token = request.META.get('HTTP_AUTHORIZATION') if not token: raise AuthenticationFailed('Unauthenticated!') try: payload = jwt.decode(token, 'secret', options={"verify_signature": False}, algorithms=['HS512']) except jwt.ExpiredSignatureError: raise AuthenticationFailed('Unauthenticated!') return payload However, I get the payload as follows: {'username': '', 'exp': 1691987384, 'iat': 1691983784} -
Problem with Django app - ERROR - models - HTTPSConnectionPool(host='www.googleapis.com', port=443): Read timed out. (read timeout=2)
I have part of the application for getting location over Google geolocate APIs. I'm trying to execute this part of code: try: if self.rssi_vector_data and not self.rssi_coords and settings.GOOGLE_LOCATION_API_KEY and not self.rssi_coords_failed: json_data = json.dumps(self.rssi_vector_data) response = requests.post('https://www.googleapis.com/geolocation/v1/geolocate?key=APIKEY', data=json_data, timeout=2) if response.status_code == 200: response_json = response.json() if response_json.get('location'): coords = response_json.get('location') self.rssi_coords = Point(coords.get('lng'), coords.get('lat'), srid=SRID_FORMAT) self.rssi_coords_failed = False self.save(update_fields=('rssi_coords', 'rssi_coords_failed')) return self.rssi_coords_failed else: self.rssi_coords_failed = True self.save(update_fields=('rssi_coords_failed')) return self.rssi_coords except Exception as e: logger.error(str(e)) But I'm getting this error: ERROR - models - HTTPSConnectionPool(host='www.googleapis.com', port=443): Read timed out. (read timeout=2) I tried to write another script with fixed values: import requests import json url = "https://www.googleapis.com/geolocation/v1/geolocate?key=APIKEY" headers = { "Content-Type": "application/json" } data = { "event_type": "rssi_vector", "timestamp": "2023-03-03T16:42:42+00:00", "payload": { "rssi_vector_data": { "considerIp": "false", "radioType": "lte", "cellTowers": [ { "cellId": 0, "mobileCountryCode": 0, "mobileNetworkCode": 0, "signalStrength": 0 } ], "wifiAccessPoints": [ { "macAddress": "E0:23:FF:11:41:90", "signalStrength": -93, "signalToNoiseRatio": 0 }, { "macAddress": "E0:23:FF:11:41:91", "signalStrength": -94, "signalToNoiseRatio": 0 } ] } } } try: response = requests.post(url, headers=headers, data=json.dumps(data), timeout=2) response.raise_for_status() except requests.exceptions.Timeout: print("Expired.") except requests.exceptions.RequestException as e: print("Error:", e) else: response_data = response.json() print(response_data) And it works. Thank you for help! I tried with several python versions and … -
Reverse for 'customuser-detail' with keyword arguments '{'pk': 3}' not found
New user to Django, followed the basics for the DRF quick start. The main thing that I wanted to try was to make a custom user to not depend on the base model and add my custom fields to it. I did it and this is what I have: custom_user.py from django.contrib.auth.base_user import AbstractBaseUser from django.contrib.auth.models import PermissionsMixin from django.db import models from django.utils.translation import gettext as _ from rest_framework import serializers from snorlax.managers.custom_user_manager import CustomUserManager class CustomUser(AbstractBaseUser, PermissionsMixin): """Custom user to override default user.""" email = models.EmailField(_("email address"), unique=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) created_by = models.ForeignKey( "CustomUser", on_delete=models.PROTECT, null=True, db_column="created_by", default=serializers.CurrentUserDefault, related_name="%(class)s_created_by", ) created_datetime = models.DateTimeField(auto_now_add=True) updated_by = models.ForeignKey( "CustomUser", on_delete=models.PROTECT, null=True, db_column="updated_by", default=serializers.CurrentUserDefault, related_name="%(class)s_updated_by", ) updated_datetime = models.DateTimeField(auto_now=True) USERNAME_FIELD = "email" REQUIRED_FIELDS = ("password",) objects = CustomUserManager() class Meta: """Define additional attributes.""" db_table = "users" user_view.py from typing import Self from rest_framework import permissions, viewsets from rest_framework.serializers import Serializer from snorlax.models import CustomUser from snorlax.serializers.user_serializer import UserSerializer class UserViewSet(viewsets.ModelViewSet): """API endpoint that allows users to be viewed or edited.""" queryset = CustomUser.objects.all().order_by("-id") serializer_class = UserSerializer permission_classes = [permissions.IsAuthenticated] lookup_field = 'id' def perform_update(self: Self, serializer: Serializer) -> None: """ Update the model using the provider serializer.. … -
Unable to create account
I have two models in two different apps, the first model is a custom user model, from abstractbaseuser class, called users and the second model is called wallet the wallet model has a field account which is a foreign key to the users model.This is my problem I want to automatically create a wallet for every newly registered user but after I use this code from django.db.models.signals import post_save from django.dispatch.dispatcher import receiver from .models import Users from userwallets.models import Wallet @receiver(post_save, sender=Users) def create_wallet(sender, created, instance, *args, **kwargs): if created: Wallet.objects.create(owner=instance) I can only create one user then when I try to register another user it says unable to create account please what I'm doing wrong. fyi: I'm using djoser for user registration but a customized one I've tried anything possible no results -
Image Caption with python
I would like to ask for help on the procedure that I must follow to create a program that generates image subtitles, I have been reading about tensorflow and VGG16, but I am not sure what to do, first create a model or automatically generate the image subtitle and save it in a txt? I would appreciate the help I have seen repositories where they only load VGG16 and tensorflow, as well as an .h5 model but I can't understand what this document would have, they also load txt files with image descriptions -
I'm have a variable Topic to a foreign key that produces this error: NameError: name 'Topic' is not defined
I'm working on a django project where I have created a project and an app. In models.py I have two classes: Topic and Entry. When I try to runserver I get an error NameError Topic is not defined. from django.db import models # Create your models here. class Lesson(models.Model): """A topic the user is learning about""" text = models.CharField(max_length=200) date_added = models.DateTimeField(auto_now_add=True) def __str__(self): """Return a string representation of the mocel""" return self.text class Entry(models.Model): """Something specific learned about a topic.""" topic = models.ForeignKey(Topic, on_delete=models.CASCADE) text = models.TextField() date_added = models.DateTimeField(auto_now_add=True) I have tried to migrate and makemigration courses the name of the app. I have rewritten the code and checked for indentation. I'm following the code in a text called Python Crash Course to the letter. At one point my code was working but now I'm getting NameError: name 'Topic' is not defined. But when I do python manage.py runserver 8000 I keep getting the error. -
Django script.js file
I am working on a django project and import javscript code from a script.js file. I am attempting to run a class and am getting a reference error. In the script.js file class RWT { constructor(r, w, t) { this.r = r; this.w = w; this.t = t; } console_r() { console.log(this.r) } }; function test_func() { console.log("this works") } function my_func() { test_func() let new_rwt = new RWT("r", "w", "t") new_rwt.console_r() } In my html file, I have an input that calls my_func(). page.html <body> <input value="a" onclick="my_func()"> <script src="{% static 'js/script.js' %}"></script> </body> I get the error: Uncaught ReferenceError: Cannot access 'RWT' before initialization What am I doing wrong here? -
Django giving error when trying to get path to static file
I'm trying to implement xhtml2pdf, and in my html file, it references a static file. I have the file in my project at jobs/static/jobs/style.css. When using the code xhtml2pdf provides in their docs, I am getting an error when it gets to result = finders.find(uri) saying django.core.exceptions.SuspiciousFileOperation: The joined path (/static/jobs/css/style.css) is located outside of the base path component (/opt/project/myproject/static). If I navigate to the url that the file should be at, http://127.0.0.1:8000/static/jobs/css/style.css, I see the code of the css file, so it is in the generally correct location. This project is being served in a docker container, and there is nothing stored in /opt, so I don't know why it coming up with this "base path component" at (/opt/project/myproject/static). I don't know where it is getting this path. I have searched my entire project, and there is no path, in any file, that includes opt or project. The project is stored in /app in the container. Here is the code I got from their site: from xhtml2pdf import pisa from django.template.loader import get_template from django.http import HttpResponse from django.conf import settings import os import io from django.contrib.staticfiles import finders def link_callback(uri, rel): """ Convert HTML URIs to absolute system … -
Modifying request contents in DRF
As far as I know request objects are immutable and it's bad practice to modify request through closed attributes like request._body or request._data. And since it described everywhere as bad practice, I'm lack of details to understand why it's should be avoided. What is the best approach to dynamically change request (for example if we need to decode value in request.body). As I alternative I can imagine custom Serializer with custom decode serializer.Field but maybe there's more clever solution? Thank you in advance! -
Django Ajax The likes I push disappear when I refresh the page
I implemented the Like function in Django Ajax, but when I refresh the page, the Likes I have pushed disappear. Why? I thought there was a problem with body: post_pk={{ post.pk }}` and looked into it, but could not figure it out. models.py from django.db import models from accounts.models import CustomUser class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() user = models.ForeignKey(CustomUser, on_delete=models.CASCADE, null=True) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title class Meta: ordering = ["-created_at"] class Like(models.Model): user_id = models.ForeignKey(CustomUser, on_delete=models.CASCADE) target = models.ForeignKey(Post, on_delete=models.CASCADE) views.py class DeletePost(LoginRequiredMixin, UserPassesTestMixin, DeleteView): model = Post template_name = 'delete.html' success_url = reverse_lazy('home') def test_func(self, **kwargs): pk = self.kwargs['pk'] post = Post.objects.get(pk=pk) return (post.user == self.request.user) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) like_count = self.object.like_set.count() context['like_count'] = like_count if self.object.like_set.filter(user_id=self.request.user).exists(): context['is_user_liked'] = True else: context['is_user_liked'] = False return context def like(request): post_pk = request.POST.get('post_pk') context = {'user_id': f'{ request.user }'} article = get_object_or_404(Post, pk=post_pk) like = Like.objects.filter(target=article, user_id=request.user) if like.exists(): like.delete() context['method'] = 'delete' else: like.create(target=article, user_id=request.user) context['method'] = 'create' context['like_count'] = article.like_set.count() return JsonResponse(context) detail.html {% extends "base.html" %} {% load static %} {% block title %}{% endblock %} {% block content %} <div class="container"> <div class="alert alert-success" role="alert"> <p>タイトル:{{object.title}}</p> <p>投稿者:{{object.user}}</p> <p>コメント:{{object.content|safe}}</p> … -
django re_path() function pattern wouldnt match a url that contains the pattern
I am trying to map any url that ends with patternA to my index function in django. To do this, I have the following in my main urls.py: urlpatterns = [ re_path(r'patternA/$', views.index), ] When I put http://localhost:8000/patternA/, everything works fine, but things get weird when I put anything before patternA, like: http://localhost:8000/something/patternA/. Although my second path matches the regex patternA/$, when putting it inside browser search bar, I get 404 error. And when I change the pattern to .*patternA/$, everything works fine. Why do I get 404 with patternA/$ pattern? I put http://localhost:8000/something/patternA/ in browser search bar, expected to get index function executed but got 404 instead -
Django ModuleNotFoundError: No module named 'store.products'?
I recently started learning Django. Faced an error. I have created a new application and I am trying to import it into the main project, but I am getting an error.enter image description here I tried doing it like thisenter image description here -
Django model instance not being created upon Formset submission
I have a Formset, where one of the fields is a multi-select checkbox, with the options available being determined by a foreign key relationship (to the business model; the form takes business as an arguement). This works, however upon submission of the Formset, nothing is saved to the database despite a POST request and redirect taking place (I would expect it to create an instance or instances of the Instructors model). My models.py (including only relevant models): class Instructors(models.Model): uid = models.CharField(verbose_name="Unique ID", max_length=255, primary_key=True) business = models.ForeignKey(Business, blank=False, on_delete=models.CASCADE) first_name = models.CharField(verbose_name="First Name", max_length=255, blank=False) surname = models.CharField(verbose_name="Surname", max_length=255, blank=False) activities = models.ManyToManyField(Activity, blank=False) def __str__(self): return str(self.uid) class Business(models.Model): # if is_business on profile model = true, then get access to create Business Profile business_name = models.CharField(verbose_name='Business Name', max_length=255) business_description = models.TextField(verbose_name='Business Description', max_length=500) slug = models.SlugField(verbose_name='Slug', max_length=250, null=True, blank=True, unique=True) business_contact_number = models.CharField(verbose_name='Business Contact Number', max_length=32) business_email = models.EmailField(verbose_name='Business Email') business_profile_image = models.ImageField(verbose_name="Profile Picture", null=True, blank=True, upload_to='business_images/') creation_date = models.DateTimeField(auto_now_add=True) address = models.CharField(verbose_name="Street Address", max_length=100, null=True, blank=True) town = models.CharField(verbose_name="Town/City", max_length=100, null=True, blank=True) county = models.CharField(verbose_name="County", max_length=100, null=True, blank=True) post_code = models.CharField(verbose_name="Post Code", max_length=8, null=True, blank=True) country = models.CharField(verbose_name="Country", max_length=100, null=True, blank=True) longitude = models.CharField(verbose_name="Longitude", max_length=50, null=True, … -
How to add select foreign keys from django html template
iam trying to create an add movie function on my movie project, fields such as actor,director are added as foreign keys. when i do this via iam only able to add non foreign key fiels to the object. this is the Movie model class Movie(models.Model): user=models.ForeignKey(User,on_delete=models.CASCADE,default=True) name=models.CharField(max_length=100,unique=True) slug=models.SlugField(max_length=100,unique=True,blank=True) year=models.CharField(max_length=5,blank=True) language=models.CharField(max_length=50,blank=True) release=models.CharField(max_length=100,blank=True) rating=models.CharField(max_length=20,blank=True) poster=models.ImageField(upload_to='movies/poster',blank=True) cover=models.ImageField(upload_to='movies/cover',null=True,blank=True) duration=models.CharField(max_length=50,default=None,blank=True) streaming=models.ForeignKey(Streaming,on_delete=models.CASCADE,blank=True,null=True) ott=models.TextField(max_length=200,blank=True,null=True) actors=models.ManyToManyField(Actor,related_name='actor',blank=True) Characters=models.ManyToManyField(Character,related_name='character',blank=True) director=models.ForeignKey(Director,on_delete=models.CASCADE,blank=True,null=True) writers=models.ManyToManyField(Writer,related_name='writer',blank=True) cinematographer=models.ForeignKey(Cinematographer,on_delete=models.CASCADE,null=True,blank=True) based =models.CharField(max_length=100,blank=True,null=True) genres=models.ManyToManyField(Genre,blank=True) certification=models.ForeignKey(Certification,on_delete=models.CASCADE,null=True,blank=True) synopsis=models.TextField(max_length=1000,blank=True) trailer=models.CharField(max_length=500,blank=True) def __str__(self): return self.name this is the path from django.contrib import admin from django.urls import path from Movies import views app_name='Movie' urlpatterns = [ # function based path path('add_movie',views.add_movie,name='add_movie'), ] this is the template to add movie <form method="POST" enctype="multipart/form-data" class="user"> {% csrf_token %} <div class="row"> <div class="col-md-12 form-it"> <label>Movie Name</label> <input type="text" name="name" placeholder="Add movie title"> </div> <div class="col-md-12 form-it"> <label>Released Year</label> <input type="text" name="year" placeholder="Add movie title"> </div> <div class="col-md-12 form-it"> <label>Released Date</label> <input type="text" name="release" placeholder="Add Released date"> </div> <div class="col-md-12 form-it"> <label>Language</label> <input type="text" name="language" placeholder="Add Language"> </div> <div class="col-md-12 form-it"> <label>Rating</label> <input type="text" name="rating" placeholder="Add IMDB rating"> </div> <div> <div class="col-md-6 form-it"> <label>Poster</label> <input type="file" name="poster" placeholder="Add Movie Poster"> </div> <div class="col-md-6 form-it"> <label>Cover image</label> <input type="file" name="cover" placeholder="Add a cover image"> </div> </div> <div class="col-md-12 form-it"> … -
cannot access local variable 'conversation' where it is not associated with a value
@login_required def detail(request, pk): conversation = Conversation.objects.filter(members__in=[request.user.id]).get(pk=pk) if request.method == 'POST': form = ConversationMessageForm(request.POST) if form.is_valid(): conversation_message = form.save(commit=False) conversation_message.conversation = conversation conversation_message.created_by = request.user conversation_message.save() conversation.save() return redirect('conversation:detail',pk=pk) else: form = ConversationMessageForm() return render(request,'conversation/detail.html',{ 'conversation': conversation, 'form': form, }) cannot access local variable 'conversation' where it is not associated with a value -
TypeError: Field.__init__() got an unexpected keyword argument 'max_lenght' django
do you know why get this error for below code? "TypeError: Field.init() got an unexpected keyword argument 'max_lenght'" thanks, M from django.db import models from django.contrib.auth.models import User STATUS = ((0, 'Draft'), (1, 'Published')) # Create your models here. class Post(models.Model): title = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_post') created_on= models.DataTimeField(auto_now_add=True) updated_on = models.DataTimeField(auto_now=True) conent = models.TextField() status = models.IntegerField(choices=STATUS, default=0) class Meta: ordering = ['created_on'] def __str__(self): return self.title -
Django: User activation not working properly
I have registration page in my Django project. I can finish the registration just fine, and the console outputs the email with the generated link, but for some reason the user value captured by the views is None? How do I fix this? I generate user tokens like this: from django.contrib.auth.tokens import PasswordResetTokenGenerator from six import text_type class AccountActivationTokenGenerator(PasswordResetTokenGenerator): def _make_hash_value(self, user, timestamp): return ( text_type(user.pk) + text_type(timestamp) + text_type(user.is_active) ) account_activation_token = AccountActivationTokenGenerator() When a user completes their registration, they're supposed to get an email like this: {% autoescape off %} Hello, {{ user.user_name }}! Your account has been successfully created. Please click the link below to activate your account. http://{{ domain }}{% url 'users:activate' uidb64=uid token=token %} {% endautoescape %} And I have my views setup so that if a user clicks on the link, their account gets activated and they're redirected to the dashboard like this: from django.contrib.auth import login from django.contrib.auth.decorators import login_required from django.contrib.sites.shortcuts import get_current_site from django.http import HttpResponse from django.shortcuts import redirect, render from django.template.loader import render_to_string from django.utils.encoding import force_bytes, force_str from django.utils.http import urlsafe_base64_decode, urlsafe_base64_encode #from orders.views import user_orders from .forms import RegistrationForm from .models import UserBase from .tokens import account_activation_token … -
react axios POST request to django failure
I try to make POST request from react app with axios. This is my code: import axios from 'axios'; const csrftoken = document.cookie.split('=')[1] // please don`t pay attention to this implementation const axiosInstance = axios.create({ baseURL: 'http://127.0.0.1:8000/api/', headers: { "Content-Type": "application/json", "X-CSRFTOKEN": csrftoken }, }); // onClick const handleApply = () =>{ const apiUrl = 'im/category_characteristics/'; axiosInstance.post(apiUrl, {withCredentials: true}) .then((response)=>{console.log(response.data)}) .catch(error => console.log(error)) }; These are my request headers: headers: AxiosHeaders Accept: "application/json, text/plain, */*" Content-Type: "application/json" X-CSRFToken: "8MGBp41YrnOSM23RLsAPIWNTNFLVTU7c" Django raises: Forbidden (CSRF cookie not set.): /api/im/category_characteristics/ Whereas, I receive successful response, when using Insomnia with the same headers: Insomnia terminal output: > POST /api/im/category_characteristics/ HTTP/1.1 > Host: 127.0.0.1:8000 > User-Agent: insomnia/2023.4.0 > Cookie: csrftoken=8MGBp41YrnOSM23RLsAPIWNTNFLVTU7c > Content-Type: application/json > X-CSRFToken: 8MGBp41YrnOSM23RLsAPIWNTNFLVTU7c > Accept: */* > Content-Length: 59 * Mark bundle as not supporting multiuse < HTTP/1.1 200 OK < Date: Sun, 13 Aug 2023 15:07:03 GMT < Server: WSGIServer/0.2 CPython/3.10.1 < Content-Type: application/json < X-Frame-Options: DENY < Content-Length: 56 < Vary: Origin < X-Content-Type-Options: nosniff < Referrer-Policy: same-origin < Cross-Origin-Opener-Policy: same-origin * Received 56 B chunk * Connection #13 to host 127.0.0.1 left intact I see Cookie header among others, but when I try to set it, I get error … -
Django checkbox input only working in one direction
I have a form with a checkbox on "pregnant". If the profile is not pregnant and goes to the update profile form, checking the box and submitting the form updates the profile. I can see in the dashboard it appears as pregnant now. However, if the profile is pregnant, and goes to update profile, unchecking the checkbox (prepopulated) and submitting, it does nothing! The profile information does not update (it still appears as pregnant in the dashboard). I am puzzled because the form connects to the database (it can update from non-pregnant to pregnant) but not the other way around! What am I missing? :-/ See my code. view: def edit_profile(request): if request.user.is_authenticated: current_user = Account.objects.get(id=request.user.id) form = EditProfileForm(request.POST or None, instance=current_user) if form.is_valid(): form.save() messages.success(request,("Your profile has been updated!")) return redirect('dashboard') return render(request, 'accounts/edit_profile.html',context={'form':form}) # else: messages.success(request,('You must be logged in!')) return redirect('login') html: <div class="flex col col-auto form-group form-check"> <label><input type="checkbox" id="pregnancy" value="Yes" name="pregnancy" {% if form.instance.pregnancy == 'Yes' %} checked {% endif %}> {% trans " Pregnant" %}</label> </div> model: class Account(AbstractBaseUser): .... pregnancy = models.CharField(max_length=10,blank=True, null=True, default='No') -
Unable to save the form in my database in Django
I wanted to practice Django, so I started off by creating a quiz website. However the the form isn't being saved into my database. I created the following models. difficulty_choices=(('easy','easy'),('hard','hard'),('medium','medium')) class Quiz(models.Model): name=models.CharField(max_length=200) topic=models.CharField(max_length=100) number_of_questions=models.IntegerField() difficulty=models.CharField(max_length=100,choices=difficulty_choices) def get_questions(self): return self.questions_set.all()[:self.number_of_questions] class Questions(models.Model): text=models.CharField(max_length=200) quiz=models.ForeignKey(Quiz,on_delete=models.CASCADE) correct=models.CharField(max_length=25) def __str__(self): return str(self.text) def get_answers(self): return self.answers_set.all() class Answers(models.Model): text = models.CharField(max_length=200) question = models.ForeignKey(Questions, on_delete=models.CASCADE) def __str__(self): return f"Question: {self.question.text}, Answer: {self.text}" class UserAnswer(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) question = models.ForeignKey(Questions, on_delete=models.CASCADE) answer = models.ForeignKey(Answers, on_delete=models.CASCADE) selected=models.CharField(max_length=25,blank=True) The text field in 'Answer' model contains the options and text field in 'Question' model contains the question The option for each question is displayed in the form of radio select button. The UserAnswer model saves the answer answered by the authenticated user, for each question. To be able to select the option i created the below forms.py class QuizForm(forms.ModelForm): class Meta: model = Questions fields = ['text'] # Add other fields as needed def __init__(self, *args, **kwargs): super(QuizForm, self).__init__(*args, **kwargs) question_instance = kwargs.get('instance') answers = question_instance.get_answers() answer_choices = [(answer.text, answer.text) for answer in answers] self.fields['selected_answer'] = forms.ChoiceField( label="Select the correct answer", choices=answer_choices, widget=forms.RadioSelect ) and the views.py for this is @login_required def questions(request, pk): try: … -
Can Django forms be used in a custom view?
I'm using a CreateView to create an object then a custom written view to assign and update the values. The problem is I can't get to assign multiple values to a many to many relation. A configuration page looks like this right now: I'm not using forms, everything is inside the template. And I have the problem with the last input, the 'Cut material' checkboxes. Since I don't use a form, it's very tricky to handle that some inputs has only one value and some of them might have multiple values (like 'Cut material'). Right now my view will request the POST data and will try to match each option with it's value, but when it get's to 'Cut material' it will get an error if I select more options. I tried some workaround to insert some hidden inputs to pass into the context more info but I had no success. I guess if I can use forms then I might solve this issue and it will also help with validation. How do you think I can manage to pass correctly the value from 'Cut material' to the view to save it correctly? Also if you would do it with …