Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to define dynamic parallel entries in finite state machine - python django
Below is my code a.py class Order(models.Model): STATUS_STARTED = 0 STATUS_SLOW =1 STATUS_FAST=2 STATUS_JUMP=3 STATUS_CHOICES = ( (STATUS_STARTED, 'STARTED'), (STATUS_SLOW,'SLOW') (STATUS_FAST,'FAST') (STATUS_JUMP,'JUMP') ) product = models.CharField(max_length=200) status = FSMIntegerField(choices= STATUS_CHOICES, default=STATUS_STARTED, protected=True) A person STARTED from a point & he is either FAST or SLOW. @transition(field=status, source=. [STATUS_STARTED], target=STATUS_FAST) def fast(self): print("person run fast") @transition(field=status, source=. [STATUS_STARTED], target=STATUS_SLOW) def slow(self): print("person run slow ") Here in above code, I can track for angle person entry only either SLOW or FAST. Any possibility to define entries for two person at a time & one at SLOW & another at FAST state. Like maintain separate track for each person. Parallel entries is possible in python django? Pls any help. -
How do I change a value in django database on clicking selected option instead button dropdown in HTML using Ajax-JavaScript?
I have done this functionality in which all the page re-load when I press any button. I just want to implement a function using Ajax-JavaScript, when I click on Activate Option, the value in my Django database for this field changes to 'Active' and is displayed on the HTML page as active with Activate Message. If De-Activate is clicked, the text changes to De-Active along with it's value in the django database and show De-Activated message HTML Button Part <div class="card-body"> <div class="table-responsive"> <table id="example1" class="footable default table table-hover toggle-plus"> <thead> <tr> <th>S.No.</th> <th>Campus Name</th> <th>HOD Name</th> <th>Status</th> </tr> </thead> <tbody> {% for published_item in published %} <tr> <td>{{ forloop.counter }}</td> <td>{{ published_item.campus_name }}</td> <td>{{ published_item.hod_name }}</td> <td> <div class="form-inline"> <div class="dropdown"> <a class="btn btn-secondary dropdown-toggle" href="#" role="button" id="dropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> {{ published_item }} </a> <div class="dropdown-menu" aria-labelledby="dropdownMenuLink"> {% if published_item.is_published == 'Activated' %} <a class="dropdown-item" href="{% url 'test_update' pk=published_item.pk %}">Deactivated</a> {% else %} <a class="dropdown-item" href="{% url 'test_update' pk=published_item.pk %}">Activated</a> {% endif %} </div> </div> </div> </td> <td> </tr> {% endfor %} </tbody> </table> </div> </div> HTML Select Part (Select Option Method) I want to change the "HTML Button Part" to "HTML Select Part" in which I use … -
Django python error: auctions.models.Listing.DoesNotExist: Listing matching query does not exist
I am try to display a listing page. Though it displays well, django keeps giving this error as below: raise self.model.DoesNotExist( auctions.models.Listing.DoesNotExist: Listing matching query does not exist. the index view displays all the listings by iteration, and the listing view displays a specific listing view by receiving a variable as "form.title". my code is as follows: views.py: def listing_view(request, title): # if get a listing page categories = Category.objects.all() # Get all the forms submitted forms = Listing.objects.all() # get the highest bid for a listing highest_price = Bid.objects.filter(title=title).order_by("-bid_price").first() # Get the listing with the title listing = Listing.objects.get(title=title) if highest_price is not None: listing.current_price = highest_price.bid_price # else set starting price as the current price else: listing.current_price = listing.starting_price listing.save() index.html: <!-- image of a listing --> <div class="col-4"> <a href="{% url 'listing_view' form.title %}"> {% if form.image %} <img src="{{ form.image.url }}" alt="" width="267px" /> {% elif form.image_url %} <img src="{{ form.image_url }}" alt="" width="267px" /> {% endif %} </a> </div> listing.html: <!-- image in the left of the container --> <div class="col-4"> {% if listing.image %} <img src="{{ listing.image.url }}" alt="" width="267px" /> {% elif listing.image_url %} <img src="{{ listing.image_url }}" alt="" width="267px" /> {% endif … -
How can i test my changes before hitting the Reload button in Pythonanywhere?
I want to test my updates and changes before hitting the Reload www.yourdomainname.com button to make sure that there are no server error 500 or any bad thing that could happen so I don't lose users, is there any way to do so? when I do python3 manage.py runserver It tells me Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). September 05, 2020 - 08:18:49 Django version 3.1, using settings 'dfreemedia.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Error: That port is already in use. even though i'm not using it -
Converted Video File not showing in templates. Also how to delete the uploaded file and replace it with converted file in the database?
Hey guys I have a video encoding function which works fine and converts video and save it in database. I am able to see the uploaded file and converted file in my pc under the media folder but the template is not able to play the file and the path of the new file after updating the field shows the wrong path in the database. I want to delete the file I uploaded and store only the converted video in the database, also need to correctly mention the path so that I can play the video in the browser. This is my views. class CreateVideoPostView(LoginRequiredMixin, BSModalCreateView): def get(self, *args, **kwargs): form = VideoPostForm() context = { 'form':form, } return render(self.request, 'videos/video/create_video.html', context) def post(self, *args, **kwargs): form = VideoPostForm(self.request.POST or None, self.request.FILES or None) if form.is_valid(): video = form.save(commit=False) video.user = self.request.user video.save() form.save_m2m() print(video.id) task_video_encoding(video.id) return redirect('videos:my_video_home') else: raise ValidationError('Check all form fields.') encode.py def encode_video(video_id): video = VideoPost.objects.get(id = video_id) old_video = video.file input_file_path = video.file.path # print(input_file_path) input_file_name = video.title #get the filename (without extension) filename = os.path.basename(input_file_path) # print(filename) # path to the new file, change it according to where you want to put it output_file_name … -
How can i use distinct in Django Views.py?
Views.py def user_detail(request): user_id = request.session.get('user_id') user = User.objects.get(username = request.user.get_username()) submit = Submit() submit_list = Submit.objects.filter(author=user).filter(result='AC').order_by('problem').distinct() context = {'User': User, 'submits':submit_list} return render(request, 'koj/user_detail.html', context) detail.html Solved : {% for submit in submits%} <th> {{ submit.problem }} <th> {% endfor %} result => Name : ziho2463 Solved : 1000 1000 1000 1000 1000 1000 1001 1001 1002 what i want => Name : ziho2463 Solved : 1000 1001 1002 this is my code. filter is working well but when i add '.distinct('problem')','DISTINCT ON fields is not supported by this database backend' error is occurred. also i used .values('problem').distinct('problem') or .values_list('problem', flat=True).distinct('problem') but that code didn't give me the result I wanted. => Name : ziho2463 Solved : 1 2 3 How can I solve this problem? -
Javascript affecting django Redirect/Refresh
There is a Patient model, and I'm creating new patient using CreateView, url link which is `/addpatient/. Designs for HTML page are built using DesignModo. When I am rendering the form simply without using any template from DesignModo, then everything is working fine that is to say that when I am pressing submit button the patient is created and I am redirected to the required page. {% block content %} <form method="POST">{% csrf_token %} {{form}} <button type="submit">submit</button> </form> {% endblock content %} the last line of below HTML code contains that script that {% extends 'patient/base.html' %} {% load static %} {% load widget_tweaks %} {% block content %} <link rel="stylesheet" href="{% static 'patient/add_patient/css/style.min.css' %}"> <!-- Form 14 --> <section class="pt-105 pb-100 bg-light form_14"> <div class="container px-xl-0"> <div class="row justify-content-center"> <div class="col-xl-8 col-lg-10"> <h2 class="small text-center" data-aos-duration="600" data-aos="fade-down" data-aos-delay="0">Patient details</h2> <form action="form-handler.php" method="post" class="mt-50 px-100 pt-85 pb-35 radius10"> <div class="row"> <div class="col-md-6 mb-35 block" data-aos-duration="600" data-aos="fade-down" data-aos-delay="0"> <div class="mb-10 f-14 semibold text-uppercase sp-20">First Name</div> {% render_field form.first_name class+="input w-full border-gray focus-action-1 color-heading placeholder-heading" type="text" name="firstname" required="required" %} </div> <div class="col-md-6 mb-35 block" data-aos-duration="600" data-aos="fade-down" data-aos-delay="300"> <div class="mb-10 f-14 semibold text-uppercase sp-20">Last Name</div> {% render_field form.last_name type="text" name="lastname" required="required" class="input w-full … -
Follow a log file in Django
I am trying to provide a live log mechanism for each ongoing execution on the dashboard. After doing some workout I've found the below code working but when I put this on production, it worked for some time but now if someone clicks on it don't show any live log but just a blank screen. urls.py url(r'^live_log/$', views.stream_response, name="Live console log") views.py @condition(etag_func=None) def stream_response(request): log_file = request.GET.get('filename', None) resp = StreamingHttpResponse( stream_response_generator(log_file), content_type='text/html') return resp def stream_reader(logstream): logstream.seek(0, 1) while True: line = logstream.readline() if not line: time.sleep(2) continue yield line def stream_response_generator(log): yield '''<html><head> <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script> <script type='text/javascript' src='/static/assets/js/scroll.js'></script> </head><body onmousedown='scrolled=true;' onmouseup='scrolled=false;' style='background-color:black' id='live_log'>\n''' with open(log, 'r') as logfile: loglines = stream_reader(logfile) for line in loglines: if "-INFO-" in line: yield '''<div style='color:white;font-family:Consolas;font-size:14'> <script type="text/javascript">update()</script>%s</div>\n ''' % line time.sleep(.05) elif "-ERROR-" in line: yield '''<div style='color:red;font-family:Consolas;font-size:14'> <script type="text/javascript">update()</script>%s</div>\n''' % line time.sleep(.05) yield "</body></html>\n" html code <td>{% if row.execution_log %} <a href="/live_log/?filename={{ row.execution_log }}"> <i class="fas fa-terminal fa-lg"></i> </a>{% else %}Unavailable {% endif %} </td> Please let me know how can I follow the log stream for each user execution and also if some other details are required. Many thanks :) -
Django project TypeError: argument of type 'WindowsPath' is not iterable
This error I'm getting and I'm unable to load my static files (css,javascript and images) Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\Dell\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\Dell\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Dell\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\base.py", line 341, in run_from_argv connections.close_all() File "C:\Users\Dell\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\utils.py", line 230, in close_all connection.close() File "C:\Users\Dell\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\Dell\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\sqlite3\base.py", line 261, in close if not self.is_in_memory_db(): File "C:\Users\Dell\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\sqlite3\base.py", line 380, in is_in_memory_db return self.creation.is_in_memory_db(self.settings_dict['NAME']) File "C:\Users\Dell\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\sqlite3\creation.py", line 12, in is_in_memory_db return database_name == ':memory:' or 'mode=memory' in database_name TypeError: argument of type 'WindowsPath' is not iterable -
How can I model the "popularity" concept in code?
I am building a tags Django application to display a feed of tags ranked by "popularity." Currently, my Tag model in models.py looks like this: class Tag(models.Model): tag = models.CharField(max_length=64, unique=True) slug = models.SlugField(max_length=64, unique=True) Ultimately, I would like to query tags in my index view in views.py kind of as follows: def index(request): context = {"tags": Tag.objects.order_by("popularity")} return render(request, "tags/index.html", context) How can I model the "popularity" concept in code? Should I add a popularity field to the Tag model and basically count how many times a tag has been used, or is there a better, slicker way to achieve the same result? -
Django REST framework: get field of related model in serializer
I'm new to Django Rest Framework. I'm trying to get my ListAPI to show various fields of my Quiz (and related) models. It's working fine, except for my attempt_number field. I'm getting the right queryset, but I'm not sure how to get only the relevant value for every query. My model setup is as follows: class Quiz(models.Model): title = models.CharField(max_length=15) slug = models.SlugField(blank=True) questions_count = models.IntegerField(default=0) class Question(models.Model): quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE) label = models.CharField(max_length=1000) class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) answer = models.CharField(max_length=100) is_correct = models.BooleanField('Correct answer', default=False) class QuizTaker(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE) correct_answers = models.IntegerField(default=0) completed = models.BooleanField(default=False) attempt_number = models.PositiveIntegerField(default=0) My serializer for the ListAPI looks as follows: class MyQuizListSerializer(serializers.ModelSerializer): attempt = serializers.SerializerMethodField() # etc.. class Meta: model = Quiz fields = "__all__" def get_attempt(self, obj): try: quiztaker = QuizTaker.objects.filter(user=self.context['request'].user, quiz=obj) for attempt in quiztaker: attempt_number = attempt.attempt_number return attempt_number If I do it like this, I always get the last value for attempt_number (because the loop overwrites the value). So then I tried to append it to a list instead, like this: a = [] for attempt in quiztaker: attempt_number = attempt.attempt_number a.append(attempt_number) return a But then I get the list … -
NameError : name 'os' is not found
I m getting this error in Django when I run the command Python manage.py collect static Error found - STATIC_ROOT = os.path.join(BASE_DIR, 'static') NameError : name 'os' is not found And I already import os what can I do, I am new in Django please help me. Thanks in advance. -
Didn't see any time difference in django async and sync view?
I'm new to django and async programming. So just for testing. I tried this code in django but I didn't see any any time difference. Sample code def sync_view(request): print('Called Sync View') start_time = time.time() context = dict() time.sleep(5) print('First time sleep') time.sleep(5) print('Second time sleep') print('Time Consumed', time.time()-start_time) return render(request, 'sync.html', context) async def async_view(request): print('Called Async View') start_time = time.time() context = dict() await asyncio.sleep(5) print('First time sleep') await asyncio.sleep(5) print('Second time sleep') print('Time Consumed', time.time()-start_time) return render(request, 'async.html', context) and here is console output. To setup async environment I followed this tutorials https://testdriven.io/blog/django-async-views/ Do i really need to use uvicorn in local environment? Here I'm using uvicorn in my local environment,so i used this command to start the server (env)$ uvicorn hello_async.asgi:application --reload and My last question. After releasing django3 do i really need django channels for chat application and django celery for running task in the background. -
Capture Image through Camera in the Website and Store the Path of Image in PGAdmin using Django
<!DOCTYPE html> <html> <head> <meta charset='utf-8'> <meta http-equiv='X-UA-Compatible' content='IE=edge'> <title>Capture Image From Camera</title> <meta name='viewport' content='width=device-width, initial-scale=1'> </head> <body> <video id="video" width="100" height="100" autoplay></video> <button id="snap">Snap Photo</button> <canvas id="canvas" width="100" height="100"></canvas> </body> <script> // Grab elements, create settings, etc. var video = document.getElementById('video'); // Get access to the camera! if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) { navigator.mediaDevices.getUserMedia({ video: true }).then(function(stream) { //video.src = window.URL.createObjectURL(stream); video.srcObject = stream; video.play(); }); } // Elements for taking the snapshot var canvas = document.getElementById('canvas'); var context = canvas.getContext('2d'); var video = document.getElementById('video'); // Trigger photo take document.getElementById("snap").addEventListener("click", function() { context.drawImage(video, 0, 0, 100, 100); }); </script> </html> '''I have used this code to add a button which will open camera to take a snap.I have to store the path of the image in Pg-admin using Django.I am not able to do this.Please Help Me...''' -
Django OneToMany api
I am new in Django and Django-Rest-framework. I am following one Youtube Tutorial. He used static Django Template but I want to use React as my frontend. So I have create multiple api endpoints. In this particular Youtube episode I am stuck to display what kind of products specific customer bought. Short summary of my project is: I have four models: order, customer, product and tags(Product and tags have many to many relationships). In the order model I have two foreign key one is product and another one is customer. This is my order models [Looks like]. I don't know how to query and display what kind of products specific customer(by using id) bought. This is my models from __future__ import unicode_literals from django.db import models class Tag(models.Model): name= models.CharField(max_length=200, null=True) def __str__(self): return self.name class Product(models.Model): CATEGORY=( ('Indoor', 'Indoor'), ('Outdoor', 'Outdoor'), ) name= models.CharField(max_length=200, null=True) price= models.FloatField(null=True) category=models.CharField(max_length=200,null=True, choices=CATEGORY) description= models.CharField(max_length=200,null=True, blank= True) date_created=models.DateTimeField(auto_now_add=True, null=True) tags= models.ManyToManyField(Tag) def __str__(self): return self.name class Customer(models.Model): name = models.CharField(max_length=200, null= True) email = models.CharField(max_length=20, null=True) phone = models.CharField(max_length=20, null=True) date_created= models.DateTimeField(auto_now_add=True) def __str__(self): return self.name class Order(models.Model): STATUS =( ('Pending', 'Pending'), ('Out of delivery', 'Out of delivery'), ('Delivered', 'Delivered'), ) status= models.CharField(max_length=200, … -
How to add ChoceField to Django forms for regustration user
I am making a registration form for 3 types of users. When a user enters email and password he/she must select one of the roles. First I used BooleanFields and it works, but more than one checkbox can be selected. I need that user can select only one role. I have tried ChoiceField, which I could display on the template but it does not POST any data to db. forms.py class RegisterForm(forms.ModelForm): """A form for creating new users. Includes all the required fields, plus a repeated password.""" password1 = forms.CharField(label='Password', widget=forms.PasswordInput) password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput) parent = forms.BooleanField(label="I am a Parent") school = forms.BooleanField(label="I am a School Admin") vendor = forms.BooleanField(label="I am a Vendor") role_select=forms.ChoiceField( widget=forms.RadioSelect, label="Select your role.", choices=(('is_parent','parent '),('is_school','school'),('is_vendor','vendor')), ) if not parent and not school and not vendor: raise forms.ValidationError("Users must have a role") class Meta: model = User fields = ['role_select', 'parent', 'school', 'vendor', 'email'] #'full_name',) def clean_password2(self): # Check that the two password entries match password1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2") if password1 and password2 and password1 != password2: raise forms.ValidationError("Passwords don't match") return password2 def save(self, commit=True): # Save the provided password in hashed format user = super(RegisterForm, self).save(commit=False) user.set_password(self.cleaned_data["password1"]) user.role_select( self.cleaned_data['role_select']) # … -
Django redirect_url with parameter
I have a simple UpdateView which updates instances of my Profile model. class ProfileUpdateView(UpdateView): model = Profile fields = ['first_name', 'last_name'] It's working fine both GET and POST, but since the GET uses an url parameter, I want also the redirect_url to redirect to the updated profile. My current urls.py: from profiles.views import ProfileUpdateView urlpatterns = [ path('self/<slug:slug>', ProfileUpdateView.as_view(success_url='/'), name='self_profile') ] It is currently redirecting to the main url, but I don't figure out how to make the redirect_url parameter redirect to the profile modified on the handled POST. Let's say I do http://localhost:8000/profiles/self/demo, (GET), then I modify my first_name and submit the request. I want the redirection to go to /profiles/self/demo again. I know I could override def post() on the view and achieve it, but since I only want to deal with the redirection I wanted to know if exists any other elegant solution. EDIT: Additional info: the slug url parameter will always be request.user in this case (since I use other view (a DetailView) to see other users' profiles). Thanks!! -
ckeditor dosn't save files and dosn't appear in django admin panel
I'm trying to use Ckeditor and Django and follow django-ckeditor, but there are two problems here; when I import images(or other files) in CKEditor, it doesn't save anymore. in the Django admin panel, there is no editor space for edit content. setting.py INSTALLED_APPS = [ 'myapp', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'ckeditor', 'ckeditor_uploader' ] ROOT_URLCONF = 'thisproject.urls' TEMPLATE_DIR= os.path.join(BASE_DIR,'media/template/') STATIC_ROOT = os.path.join(BASE_DIR,'statcifiles') CKEDITOR_BASEPATH = "/my_static/ckeditor/ckeditor/" MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') MEDIA_URL = '/media/' CKEDITOR_UPLOAD_PATH = 'uploads/' urls.py from django.contrib import admin from django.urls import path,include from . import views from django.conf.urls import url, include from django.conf.urls.static import static from django.conf import settings urlpatterns = [ path('admin/', admin.site.urls), path('dashboard/',include('myapp.urls')), path('',views.login,name='login'), url(r'^ckeditor/', include('ckeditor_uploader.urls')), ] + static(settings.MEDIA_URL, document_root= settings.MEDIA_ROOT) models.py from django.db import models import datetime from ckeditor.fields import RichTextField from ckeditor_uploader.fields import RichTextUploadingField class PrescriptionSheet(models.Model): Text=RichTextUploadingField() Date=models.CharField(max_length=20) here is my Django admin panel that CKEditor not appears: -
Customising the fields of drop-downs in Django w.r.t to conditions
I have a scenario where I have 2 drop-downs and the values of second drop-downs are based on the first drop-downs values. For example :- According to my implementation write now it appears to be 2 separate drop-downs drop-down1_value 1 drop-down1_value 2 drop-down1_value 3 drop-down2_value 1 drop-down2_value 2 drop-down2_value 3 drop-down2_value 4 What I want is the value should appear as drop-down1_value 1 drop-down2_value 1 drop-down2_value 2 drop-down1_value 2 drop-down2_value 3 drop-down2_value 4 so, basically the values of drop down 2 are dependent on the values of drop down 1. Internally the tables are connected but I am not able to display it as required. It has to be done something with Django forms as per my research but I am not able to do it. Any help will be really very helpful. -
How do I change a value in django on option click in HTML using Ajax-JavaScript?
I am trying to implement a function using Ajax-JavaScript in which when I click on Activate Option, the value in my Django database for this field changes to 'Active' and is displayed on the HTML page as active with Activate Message. If De-Activate is clicked, the text changes to De-Active along with it's value in the django database and show De-Activated message HTML page: <div class="col-sm-5"> <div class="panel panel-primary"> <div class="panel-heading"> <h3 class="panel-title">Job activation status</h3> </div> <div class="panel-body"> <td> Campus Name </td> <td> hod_name </td> <td> <select name="status" class="form-control"> <option value="1">Active</option> <option value="2">Disabled</option> </select> </td> </div> </div> </div> Model: class Campus(models.Model): STATUS = ( ('Active', 'Active'), ('Disabled', 'Disabled'), ) campus_name = models.CharField(blank=True, max_length=30) hod_name = models.CharField(blank=True, max_length=25) status = models.CharField(max_length=10, choices=STATUS, default='Disabled', blank=True) def str(self): return self.campus_name -
Range slider to change function argument inn Django
I want to make a slider range that changes the value of an argument of a function I have a slider like this: <div class="slidecontainer"> <input type="range" min="0.5" max="2.5" value="1.2" step="0.1" class="slider" id="limit"> </div> It supposed to change the value "1.2" argument: def summarize (sentences, sentences_value, limit): ... summary = summarize(sentences, sentences_value, 1.2 * average_score) What can I do? Do i have to place the function in a views? Thank you -
'QuerySet' object has no attribute 'completed'
In my quiz app, every user can have multiple attempts. My model setup is as follows: class Quiz(models.Model): title = models.CharField(max_length=15) slug = models.SlugField(blank=True) questions_count = models.IntegerField(default=0) class Question(models.Model): quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE) label = models.CharField(max_length=1000) class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) answer = models.CharField(max_length=100) is_correct = models.BooleanField('Correct answer', default=False) class QuizTaker(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE) correct_answers = models.IntegerField(default=0) completed = models.BooleanField(default=False) attempt_number = models.PositiveIntegerField(default=0) I get the error in my serializer when I try to determine if a given quiz has been completed: class MyQuizListSerializer(serializers.ModelSerializer): questions_count = serializers.SerializerMethodField() completed = serializers.SerializerMethodField() progress = serializers.SerializerMethodField() score = serializers.SerializerMethodField() class Meta: model = Quiz fields = ['id', 'title', 'type_of_content', 'song', 'slug', 'questions_count', 'completed', 'score', 'progress'] read_only_fields = ['questions_count', 'completed', 'progress'] def get_completed(self, obj): try: quiztaker = QuizTaker.objects.filter(user=self.context['request'].user, quiz=obj) for attempt in quiztaker: return quiztaker.completed #the error comes from this line except QuizTaker.DoesNotExist: return None Can anybody tell me why I am getting this error? I am filtering because the user can have multiple attempts, therefore I get a queryset, and therefore I must loop through it. The QuizTaker model does have a completed field, so what is the issue? Here is the full traceback: Traceback (most recent … -
Adding multiple groups with django channels and websocket
I try to development a notificaiton system. I would like the system administrator to be able to send notifications to different groups. For this, I create only one websocket connection, and when socket is connected(during login) I want to add the user to the groups it belongs to. I wrote the code as below but I'm not sure it's correct. I am already getting this error: "AttributeError: 'WebSocketProtocol' object has no attribute 'handshake_deferred'" class MyConsumer(AsyncWebsocketConsumer): async def connect(self): if self.scope["user"].is_anonymous: await self.close() else: groups = await sync_to_async(list)(self.scope["user"].channel_groups.all()) for group in groups: await self.channel_layer.group_add(group.name,self.channel_name) await self.accept() print("###CONNECTED") Can you help me? Am i on the right way? If so how do i fix this error? -
my s3 bucket to serve my static files in Django is not working
I am in production (Heroku) and this is my settings.py extracts and I use django-storages INSTALLED_APPS = [ ... 'storages', ] AWS_ACCESS_KEY_ID = 'key' AWS_SECRET_ACCESS_KEY = 'secret' AWS_STORAGE_BUCKET_NAME = 'bucket' AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' My href for static <link rel="stylesheet" type="text/css" href="{% static 'app/css/base.css' %}"> my static files are located in my app/static/app_name/ When i view my source code in the server, the href is still pointing to my local thing which is my 'appname.heroku.com/static/app_name/css/base.css' (my logs say it's not found) instead of the typical amazon s3 CDN url ?? I have uploaded the 'myapp/static' file in my bucket. What am i missing?? I am sort of new to using s3.. please help, since its production, I am nervous about messing it up, that's why I am reaching out for help... -
what is the diffrence between (in the body) are in django 3.1
is it just me or other people don't understand the title because docs.djangoproject.com wasn't clear enough, so I'm just asking what the differences between <li><a href="/polls/{{ question.id }}/">{{ question.question_text }}</a></li> <li><a href="{% url 'detail' question.id %}">{{ question.question_text }}</a></li> <li><a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a></li>