Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
serializer.is_valid returns false with an error that the field is required even though I am passing it
I am building a serializer so that if I post using the following command curl -d '{"food": "test", "portion": 12}' http://127.0.0.1:8000/food it will save to the db. However my problem is serializer.is_valid() returns false with an error that the field "food" is required even though I am passing it. I am unable to change the curl command so how can I make it work? Any help is appreciated. views.py serializer = StockSerializer(data=request.data) if serializer.is_valid(): //save else: print(serializer.errors) //{'food': [ErrorDetail(string='This field is required.', code='required')]} serializer.py class FoodSerializer(serializers.ModelSerializer): class Meta: model = Product fields = ["food", "portion"] Log FoodSerializer(data=<QueryDict: {'{"food": "test", "portion": 12}': ['']}>): food = CharField(max_length=8) portion = IntegerField(required=False) -
How to Update field of Django model based on another model with foreign key relation
I have two models Betslip and Bet,I want to update value of Betslip.settled_status to 'Lost', if Bet.settlement_status is 'half_lost' or 'lost', can anyone create a method for it ? class Betslip(models.Model): SETTLED_STATUS_CHOICE = ( ('InGame','InGame'), ('Won','Won'), ('Lost','Lost'), ('Refunded','Refunded') ) settled_status = models.CharField(choices=SETTLED_STATUS_CHOICE,max_length=30) class Bet(models.Model): SETTLEMENT_STATUS_CHOICE = ( ('','select'), ('won','won'), ('lost','lost'), ('refund','Refund'), ('half_won','half_won'), ('half_lost','half_lost'), ) settlement_status = models.CharField(choices=SETTLEMENT_STATUS_CHOICE,max_length=30,) betslip = models.ForeignKey(Betslip,on_delete=models.CASCADE,related_name='bet')``` -
Obtaining unique set of related models
I'm attempting to get a unique set of Employees that are represented within a queryset of jobs. My models are as follows: class Employee(models.Model): name = models.CharField(max_length=100) class Job(models.Model): employee = models.ForeignKey(Employee, on_delete=models.CASCADE, null=True) start_time = models.DateTimeField(null=True, blank=False) end_time = models.DateTimeField(null=True, blank=False) My query is as follows jobs_list = Job.objects.filter( Q(start_time__lte=start) & Q(end_time__gte=end) ) I'd like to develop a query that gets me a unique queryset of Employees that are related to the jobs_list queryset. Thanks! -
Add view count if video is played more than 3 seconds
I am building a Simple Video App. What i am trying to do :- I am trying to add a user's view count if video is played more than three seconds. What i have done :- I got the video duration in miliseconds using pymediainfo. I made a view counter which is working fine(In video detail view) but. i don't know how can i get played duration of video. models.py class Video(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE,default='',null=True) video = models.FileField(upload_to='videos',null=True) viewers = models.ManyToManyField(settings.AUTH_USER_MODEL,related_name='viewed_video',blank=True,editable=True) views.py from pymediainfo import MediaInfo def videoListView(request,pk): videos = Video.objects.all() for vid in videos: media_info = MediaInfo.parse(f.video) duration_in_ms = media_info.tracks[0].duration queryset = Video.objects.annotate( num_views=Count('viewers')).order_by('-num_views') datas = get_object_or_404(queryset, pk=pk) if request.user.is_authenticated: created = Video.viewers.through.objects.get_or_create(video=datas, user=request.user) if created: datas.num_views += 0 context = {'vid':vid,'datas':datas,'duration_in_ms':duration_in_ms} return render(request, 'videoList.html', context) I have no idea how can i get video's played duration. Once i get the video's played duration then i will use if statement that if video_played_duration == 3seconds: then add view count. Any help would be much Appreciated. Thank You in Advance. -
¿Como serializar query set con group by en django?
Soy nuevo en DJANGO, estoy tratando de serializar el siguiente query set: Product.objects.all().values('category').annotate(total= Count('category')) el resultado que estoy buscando seria el siguiente [ { category: "category1", total: 5 }, { category: "category2", total: 3 }, { category: "category3", total: 8 } ] -
Question in one of Cory Schafer's tutorials for Django
I am trying to learn Django by watching the Django course by Cory Schafer, and I'm just confused about the part where Cory used redirect after the registration process. if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request, f'Account created for {username}!') return redirect('blog-home') else: form = UserRegisterForm() return render(request, 'users/register.html', {'form': form}) He used the return redirect('blog-home') and managed to show the message Account created for {username} in the template. But I'm not sure how he managed to access that message in the template without ever passing it similar with what we do with render method. Example of render method I learned is below, it's always passing the 3rd argument so that in the template we can manage to access it. But I have no idea how the message was passed via redirect method. return render(request, 'blog/home.html', context) -
Getting this error while running this python code for Google analytics API implimentation
I want to get all the feed lists From Google analytics API and while running my code I'm getting this error. Code: from oauth2client import client results = client.list_web_data_streams(parent=f"properties/65652355") results Error: AttributeError Traceback (most recent call last) <ipython-input-11-13e430ab0d4b> in <module> 3 from oauth2client import client 4 ----> 5 results = client.list_web_data_streams(parent=f"properties/65652355") 6 results AttributeError: module 'oauth2client.client' has no attribute 'list_web_data_streams' -
error is comming while sending list and fetch value on sended list data
plz explain why this is happening in detail and solution also. thanks in advance. list is coming in views but when i fetch the value against them then it prints 'none' and also when i use to send js list to same function in which i want to fetch then also it dont works plz this also image of error page: https://i.stack.imgur.com/t43Vw.png <div class="container"> <div class="tabble"> <div class="col"> <div> <label class="ac_trigger" for="ac1"> <input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search For Food Names.." title="Type in a name"> &nbsp;<i class="fa fa-search"></i> </label> </div> <br> <div class="ac_container" id="div1"> <table id="myTable"> <tr class="header" id="heading" style="display: none;"> <th style="width:80%;">Name</th> <th style="width:20%;padding: 4px;">Select</th> </tr> {% for a in foodlist2 %} <tr style="display: none;"> <td>{{a|title}}</td><td style="text-align:center"><input id="btn" type="button" value="Add" name="{{a}}" onclick="add_item(this, this.parentNode.nextSibling.nextSibling)"></td> <td style="display: none;text-align: center;"><input id="btn" type="button" name="{{a}}" value="Remove" onclick="remove_item(this,this.parentNode.previousElementSibling)"></td> </tr> {% endfor %} </table> </div> <div class="ac_container"> <table id="myTable1"> <tr class="header"> <th style="width:80%;">Selected Items</th> <th style="width:20%;">Intake(gm)</th> </tr> <!-- <tr id="newRow"> <td id="showName"></td><td><input type="Number" name="FETID CASSIA (fresh)"></td> </tr> --> </table> </div> </div></div> <a href="food_output"><button id="submit">Submit</button></a> </div> <script type="text/javascript"> function myFunction() { var input, filter, table, tr, td, i, txtValue; input = document.getElementById("myInput"); filter = input.value.toUpperCase(); table = document.getElementById("myTable"); tr = table.getElementsByTagName("tr"); document.getElementById('heading').style.display = ''; for (i = 0; … -
How to process the practice answers directly on the server and the results are immediately updated on the practice data using Django
I want to process the practice answers directly on the server and the results are immediately updated on the practice data, so when the user opens the practice data, the practice data value is already available. models.py class PracticeAnswer(models.Model): practice_answer_id = models.BigAutoField(primary_key=True) practice_answer = models.CharField(max_length=255, default=None, blank=True) practice = models.ForeignKey(Practice, models.DO_NOTHING, default=None) question = models.ForeignKey('Question', models.DO_NOTHING, default=None) def __str__(self): return str(self.practice_answer_id) class Practice(models.Model): practice_id = models.BigAutoField(primary_key=True) score = models.SmallIntegerField(null=True) correct = models.SmallIntegerField(null=True) def __str__(self): return str(self.practice_id) class Question(models.Model): question_id = models.BigAutoField(primary_key=True) question = models.TextField() question_answer = models.CharField(max_length=255) multiple_choice_a = models.CharField(max_length=255) multiple_choice_b = models.CharField(max_length=255) multiple_choice_c = models.CharField(max_length=255) def __str__(self): return self.question class User(models.Model): user_id = models.BigAutoField(primary_key=True) fullname = models.CharField(max_length=50) email = models.CharField(max_length=100) password = models.TextField() def __str__(self): return self.fullname views.py @api_view(['GET']) def practiceAnswer_filter(request): if request.method == 'GET': practiceAnswers = PracticeAnswer.objects.all() practice_id = request.GET.get('practice_id', None) if practice_id is not None: practiceAnswer_filtered = practiceAnswers.filter(practice_id__practice_id__icontains=practice_id) practiceAnswer_list = list(practiceAnswer_filtered) shuffle(practiceAnswer_list) practiceAnswer_shuffled = practiceAnswer_list[:5] def sort_list(e): return e.pk practiceAnswer_shuffled.sort(key=sort_list) practiceAnswers_serializer = PracticeAnswerSerializerFilter(practiceAnswer_shuffled, many=True) return JsonResponse(practiceAnswers_serializer.data, safe=False) @api_view(['GET']) def practice_filter(request): if request.method == 'GET': exercises = Practice.objects.all() user = request.GET.get('user', None) if user is not None: practice_filtered = exercises.filter(user__user_id__icontains=user) exercises_serializer = PracticeSerializer(practice_filtered, many=True) return JsonResponse(exercises_serializer.data, safe=False) I have practice answer data based on practice with id 127. … -
Django: NOT NULL constraint failed: account_tutorvalidator.user_id
I am new to django and I created this "apply now form" exclusively for tutors that when they submit the form it will appear to the admin site, and I will manually check it if they are a valid tutor. And if they are a valid tutor, I will check the is_validated booleanfield in the admin site to the corresponding tutor that sent the form, so that he/she will have access to other things in the site. But I am having this problem that when you submit the form a "NOT NULL constraint failed: account_tutorvalidator.user_id" comes up.. I have search for some solutions and also read similar questions here but I still couldn't understand what to do.. could someone help me out with this? here is my models.py class User(AbstractUser): is_student = models.BooleanField(default=False) is_tutor = models.BooleanField(default=False) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) phone_number = models.CharField(max_length=11, blank=False, null=True) current_address = models.CharField(max_length=100, null=True) image = models.ImageField(default='default-pic.jpg', upload_to='profile_pics') def __str__(self): return f'{self.first_name} {self.last_name} class TutorProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, related_name='tutor_profile') bio = models.CharField(max_length=255, blank=True) is_validated = models.BooleanField(default=False) def __str__(self): return f"{self.user.first_name} {self.user.last_name}'s Profile" class TutorValidator(models.Model): user = models.ForeignKey(TutorProfile, on_delete=models.CASCADE) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) dbs = models.ImageField(upload_to='dbs_pics') driving_license = models.ImageField(upload_to='drivers_license_pics', null=True, … -
FBV Delete to CBV Delete
I am new to django ,how can i convert this FBV delete to CBV delete ? def delete_hotel(request, pk): hotel = Hotel.objects.get(pk=pk) owner = MyUser.objects.get(pk=pk) hotel.delete() owner.delete() return redirect('/admin/') -
any django app that can store sessions ip,browser ..etc and not delete it after the user logout?
i want to store the session history for users in my application , any app can be used ? if not how some thing like that can be made ? i want to have complete history for IPS , browsers , location ..etc i have tried to used Django-sessions app from jassband but it the session is deleted after the user logout thanks -
Django static files don't load in Heroku
I've been hitting my head against the wall with this one. I am trying to deploy a django app to Heroku but css files are not being loaded. What should I do? I get this error message in console Refused to apply style from 'https://sleepy-wildwood-57073.herokuapp.com/static/network/css/style.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. Aside from that heroku logs --tail doesn't seem to show any errors. My settings.py: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'network/static'), ) TEMPLATE_DIRS = ( os.path.join(BASE_DIR, 'templates'), # Add to this list all the locations containing your static files ) STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage' django_heroku.settings(locals()) MIDDLEWARE = [ 'whitenoise.middleware.WhiteNoiseMiddleware', ... ] One thing is that I am writing styles with scss and then turning them into css with django-sass script. I am not commiting the css files to the repo. Just the scss files. And the page loads, the js scripts load but all the styles won't load! I have no idea what I should do. Please help! Thank you in advance -
how can I access to chatmessage_thread field using Django Rest
How can i access to to chatmessage_thread using Django Rest Framework this is my queryset class ThreadViewSet(viewsets.GenericViewSet): queryset = Thread.objects.all() serializer_class = ThreadSerializer def list(self, request): objectSerializer = self.serializer_class(Thread.objects.by_user(user=request.user).prefetch_related('chatmessage_thread').order_by('timestamp'), many=True) return Response(objectSerializer.data) this is my serialize : from rest_framework import serializers from chat.models import Thread from datetime import date class ThreadSerializer(serializers.ModelSerializer): class Meta: model = Thread fields = '__all__' depth = 1 should i add something is my Serializer ? -
Apache/2.4.46 (Ubuntu) Server at Port 80 Error
I have uploaded 2 django projects before and worked perfectly fine to the server, but now for some reason I am receiving this error. I have revisited a tutorial word by word and revised it several times, I am not sure why I keep receving this error: Error for 403 Forbidden You don't have permission to access this resource. Apache/2.4.46 (Ubuntu) Server at Port 80 Here is the config file: <VirtualHost *:80> ServerAdmin webmaster@localhost DocumentRoot /var/www/html ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined Alias /static /home/ahesham/Portfolio/static <Directory /home/ahesham/Portfolio/static> Require all granted </Directory> Alias /media /home/ahesham/Portfolio/media <Directory /home/ahesham/Portfolio/media> Require all granted </Directory> <Directory /home/ahesham/Portfolio/Portfolio> <Files wsgi.py> Require all granted </Files> </Directory> WSGIScriptAlias / /home/ahesham/Portfolio/Portfolio/wsgi.py WSGIDaemonProcess Portfolio python-path=/home/ahesham/Portfolio python-home=/home/ahesham/Portfolio/venv WSGIProcessGroup Portfolio </VirtualHost> My question is what am I doing wrong and how to fix it? Please let me know if there are further information required to help assist fixing it -
ManyToMany vs. Intermediary Model for Follower-Following Relationship for Django Rest Framework
I'm working on a blog application with Django Rest Framework (very original I know) and I'm trying to add a followers/following relationship between Users. Currently my UserProfile is implemented as follows: from django.db import models from django.contrib.auth import get_user_model from django.db.models.signals import post_save from django.dispatch import receiver User = get_user_model() class UserProfile(models.Model): """Model For Extending Default Django User Model""" user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile') username = models.CharField(max_length=150, blank=True, null=True) bio = models.TextField(blank=True, null=True) avatar = models.ImageField(blank=True, null=True) def __str__(self): return f'{self.user.first_name} {self.user.last_name}' @property def full_name(self): return f'{self.user.first_name} {self.user.last_name}' @property def posts_list(self): return self.user.posts.filter(author=self.user) @property def comments_list(self): return self.user.comments.filter(author=self.user) @receiver(post_save, sender=User) def create_profile(sender, instance, created, *args, **kwargs): """Automatically Create A User Profile When A New User IS Registered""" if created: user_profile = UserProfile(user=instance) setattr(user_profile, 'username', instance.username) user_profile.save() My goal is to create a way to link UserProfiles via a Follower/Following relationship. My first idea was to create a ManyToMany relationship like the following: followers = models.ManyToManyField('self', symmetrical=False, blank=True) This makes sense to me, since a UserProfile can have multiple followers and follow multiple people. If I want to serialize this model, then I can use something like the following: class UserProfileDetailsSerializer(serializers.ModelSerializer): posts_list = SerializerMethodField(source="get_posts_list") followers = SerializerMethodField(source="get_followers") class Meta: model = … -
Handling File Upload Errors in Django with DO/S3
I'm using django-storages with DO/S3 to upload a file from curl (later to be a Java client): curl -F some_file=@some_file.txt -F name=some_file --referer https://localhost:8000 -k -i https://localhost:8000/file/request Storage backend configured: storages.backends.s3boto3.S3Boto3Storage My model field: some_file = models.FileField('Some file', blank=True, null=True, upload_to=some_file_path) All this is working fine. I can send a POST request with a file and it uploads to the right place. What I'm trying to figure out is error handling. Since I'm relying on a third party CDN (DO) and library (boto3) to seamlessly upload files, how do I handle errors if the upload fails? I searched Django, DO, django-storages, and AWS docs and couldn't find a good answer. I'd like to handle failed uploads in a user friendly manner, but I'm not even sure how to test this scenario either. If I was calling this file upload in a view, handling the errors in a try block would be straight forward. But since this storage backend is only configured in settings to be the repository for all my uploaded files, how do I handle errors? Do I have to write a custom backend? Any help appreciated. -
Django - Would I be able to use template tags for rendering HTML given URL path conditionals?
I have a blog page with the path /articles/. I would like to use conditional statements to reflect HTML renders. For example, my blog uses a paginator for blog posts. The paginator uses a URL query to retrieve the next page of post objects like so: /articles/?page=2 I would like for the next page to stylize the HTML template differently, hence my reasoning for using a conditional statement. Here is my template that I use: {% if request.path == '/articles/' %} # Render HTML only meant for the above path {% elif request.path != '/articles/'%} # Render HTML for paths that are NOT the exact match above, such as pagination URLs, # search querys, categories filtering, etc... {% endif %} My current bug is that I'm only rendering the first statement: if request.path == '/articles/' for everything, even non exact matches. So this URL path: /articles/?page=2 is rendering: {% if request.path == '/articles/' %} when it should be rendering the elif {% elif request.path != '/articles/'%} due to the not equals sign. Is the above possible to do with only HTML template tags? I know I can use urls.py and edit views but I'm using wagtail CMS and playing with … -
how can i get chatmessage_thread ( i'm using Django Rest Framework )
I'm working on a small project (chat) using Django Rest Framework / Channels I have a small issue, I can't get chatmessage_thread i'm getting this error message : 'QuerySet' object has no attribute 'chatmessage_thread' this is my serialize : from rest_framework import serializers from chat.models import Thread from datetime import date class ThreadSerializer(serializers.ModelSerializer): class Meta: model = Thread fields = '__all__' depth = 1 This is my view: # Rest Framework import datetime from django.shortcuts import get_object_or_404 from rest_framework.response import Response from rest_framework import viewsets, status, generics, filters from rest_framework.parsers import JSONParser from rest_framework.decorators import action # Model + Serializer from .serializers import ThreadSerializer from chat.models import Thread import pprint class ThreadViewSet(viewsets.GenericViewSet): queryset = Thread.objects.all() serializer_class = ThreadSerializer def list(self, request): objectSerializer = self.serializer_class(Thread.objects.by_user(user=request.user).prefetch_related('chatmessage_thread').order_by('timestamp'), many=True) return Response(objectS this is my model : from django.db import models from django.contrib.auth import get_user_model from django.db.models import Q User = get_user_model() # Create your models here. class ThreadManager(models.Manager): def by_user(self, **kwargs): user = kwargs.get('user') lookup = Q(first_person=user) | Q(second_person=user) qs = self.get_queryset().filter(lookup).distinct() return qs class Thread(models.Model): first_person = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True, related_name='thread_first_person') second_person = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True, related_name='thread_second_person') updated = models.DateTimeField(auto_now=True) timestamp = models.DateTimeField(auto_now_add=True) objects = ThreadManager() class Meta: unique_together = ['first_person', … -
How to entering to URLs in Django?
Well I just started today working with the Django app but when I follow his tutorial https://www.youtube.com/watch?v=_uQrJ0TkZlc&t=18317s at 5:20:20 The machine won't let me go to the URL of 127.0.0.1:8000/products/ pyshop\urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('products/', include('products.urls')) products\urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index), path('new', views.new) ] views.py from django.http import HttpResponse from django.shortcuts import render def index(request): return HttpResponse('Hello World') def new(request): HttpResponse('New Products') -
Django how to show user profile picture publicly?
right now authenticated user can only see his own profile pic. I want every user can see each others profile picture. how to visible profile picture publicly: here is my code: models.py: class UserProfile(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,related_name="userprofile") slug = models.SlugField(max_length=2000,unique=True,blank=True,null=True) profile_pic = models.ImageField(upload_to='profile/images/',validators=[validate_file_size,FileExtensionValidator( ['png','jpg'] )],blank=True,null=True) my class based views.py data['user_profile']= UserProfile.objects.filter(user=self.request.user) I want to show every user profile pic publicly for my comment section. html {% for i in user_profile %} {{i.first_name}} <img {%if i.profile_pic%}src="{{ i.profile_pic.url }}" {%else%}src="https://www.bootdey.com/img/Content/avatar/avatar7.png"{%endif%} alt="Image" class="img-thumbnail img-circle thumb96" style="max-width: 100px;margin-left: 100px;border-radius: 50%;"> {%endfor%} -
Django simple app causes a circular import error, followed by a definition error
I'm having a seemingly simple definition error whereby the class Automation is not defined. I've created a very simple app called automations which seems to have caused a problem despite barely changing it. Note that there's also another app called messages, with a many:many relationship with the new automations. Automations is just an app with this simple models.py file: from django.db import models from accounts.models import Account from messages.models import Message class Automation(models.Model): name = models.CharField(max_length=100) description = models.CharField(max_length=200) account = models.ForeignKey(Account, on_delete=models.CASCADE) date_created = models.DateTimeField(auto_now_add=True, null=True) messages = models.ManyToManyField(Message) def __str__(self): return self.name And messages is a separate app with this models.py file: from django.db import models from accounts.models import Account # from automations.models import Automation # < FAILS from automations.models import * # < WORKS # from apps.get_model(email_messages, Message) # < FAILS # from django.apps get_model(email_messages, Message) # < FAILS # from django.apps import apps # < FAILS # Automations = apps.get_model('email_messages', 'Messages') # < FAILS class Message(models.Model): name = models.CharField(max_length=100) subject = models.CharField(max_length=128) text = models.TextField() account = models.ForeignKey(Account, on_delete=models.CASCADE) date_created = models.DateTimeField(auto_now_add=True, null=True) automations = models.ManyToManyField(Automation) # < PROBLEMATIC LINE def __str__(self): return self.name I initially had this import from automations.models import Automation which caused this … -
Defining the initial values of a ModelForm in Django admin using the contents of the request
I'm trying to pre-fill a ModelForm for the admin interface of my Django application. I'm storing some values in request.session and I'd like to use them to define the initial parameter of my ModelForm. I'm able to retrieve these values in ModelAdmin.render_change_form(self, request, context, *args, **kwargs), but I'm not sure how to pass them to the form. Is it possible to do this? I guess I should use a class factory (taking inspiration from this answer) but I'm not sure where to call it, as ModelAdmin.form is a class attribute, not an instance attribute. Below is a short version of the code I'm using. ## admin.py @admin.register(Game) class GameAdmin(admin.ModelAdmin): # ... # This is where I'd like to pass the value of request.session["prefill_data"] form = GameAdminForm() # inherits forms.ModelForm() def render_change_form(self, request, context, *args, **kwargs): self.change_form_template = 'my_app/admin_game.html' extra_context = {} if "prefill_data" in request.session: # I'm able to access this data here extra_context["something_available_for_the_template"] = something_i_did_with prefill_data # Once I've done what I need I can safely delete the session variable del request.session["prefill_data"] return super(GameAdmin, self).render_change_form(request, context | extra_context, *args, **kwargs) # This is actually the view that populates request.session def admin_prefill(self, request): # [something something] request.session["prefill_data"] = foo # … -
Django Channels: Saving logged in user to session
According to the docs: If you are in a WebSocket consumer, or logging-in after the first response has been sent in a http consumer, the session is populated but will not be saved automatically - you must call scope["session"].save() after login in your consumer code: However, I am having some trouble implementing this. I start by getting my user: def login(form_data): try: user = User.objects.get(username=form_data['username']) except User.DoesNotExist: return "This account doesn't exist." password = form_data['password'] if check_password(password, user.password): return user else: return "Incorrect Password." And then following the directions like so: user = login(form_data) async_to_sync(login)(self.scope, user) self.scope["session"].save() self.send(text_data=to_json({ 'operation': 'set_user', 'success': True, 'message': "Loading User Data", 'object': {'username': user.username} })) And it works to deliver the user to the page and set it up for the life of the consumer. However, it seems that the user is not being saved to the user's session, because when I reload the page, self.scope['user'] once again returns an AnonymousUser object. This is how I've got my asgi.py set up: application = ProtocolTypeRouter({ "http": get_asgi_application(), "websocket": AuthMiddlewareStack( URLRouter( routing.websocket_urlpatterns ) ), }) Likewise, navigating to other pages confirms that I am indeed not logged in. What could I be missing? -
Fetch auto-populated data from a ForeignKey model and use in the form
I am facing one Issue in Django: Below are my codes, In create_support I have created a form, to submit a ticket, I want the Profile to be auto populated post user login and should not display in the drop down, I was able to remove from the drop down by adding exclude in the forms.py, but post form submission profile is still blank, how to resolve this ? How do i fetch logged-in user profile during support ticket submission. models.py class Support(models.Model): profiles = models.ForeignKey(Profile, null=True, on_delete=models.SET_NULL) name = models.CharField(max_length=50) email = models.EmailField(null=True) subject = models.CharField(max_length=255, null=True) comments = models.TextField(null=True, blank=True) def __str__(self): return self.name class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) email = models.CharField(max_length=200) views.py def support(request): support = request.user.profile.support_set.all() context = { 'support': support } return render(request, 'support.html', context) def createsupport(request): support = request.user.profile.support form = SupportForm(instance=support) if request.method == 'POST': form = SupportForm(request.POST) if form.is_valid(): form.save() messages.success(request, 'Your Support Query has reached us, will get back to you shortly. ') return redirect('blog:articles') context = { 'form': form } return render(request, 'create_support.html', context) create_supportsupport.html <div class="col-md-9"> <div class="card card-body"> <h5>Create New Ticket:</h5> <form method="POST" action="" enctype="multipart/form-data"> {% csrf_token %} <table border="0"> {{ …