Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Need to create a scheduling app in Django
I'm new to Django but love what it can do. Can anyone recommend the best method to create a scheduling app. The purpose is to visually show what projects each employee is working on each day in our department. Currently we use excel with each day of the month on the X axis and employee name on the Y axis which is not ideal. I've read a bit about Django Scheduler. Has anyone used this? -
How to insert data using zip() function
I am trying to insert data after fetching it with zip() function but getting an error message. x is the question id, y is the selected answer and corrected_answer in print(x, y, correct_answers). I want to save the correct questions by making the value of is_correct=True and incorrect answer to is_correct=False enter image description here @login_required @student_required def take_exam(request, pk): course = get_object_or_404(Course, pk=pk) student = request.user.student question = course.questions.filter() #correct_answers = student.course_answers.filter(answer__question__quiz=course, answer__is_correct=True).count() total_questions = course.questions.count() choice = Answer.objects.filter() marks_obtainable = Details.objects.get(course_id=course) if request.method == 'POST': question_pk = request.POST.getlist('question_pk') #question_obj = Question.objects.filter(id=int(question_pk)) #question_obj = Question.objects.filter(id=question_pk) #choice_pk = [request.POST['choice_pk{}'.format(q)] for q in question_obj] choice_pk = [request.POST['choice_pk{}'.format(q)] for q in question_pk] #print(marks_obtainable.marks_obtained) zipped = zip(question_pk, choice_pk) for x, y in zipped: correct_answers = Answer.objects.filter(question_id=x, is_correct=True).values("id").first()['id'] print(x, y, correct_answers) if int(y) == int(correct_answers): z = TakenQuiz(student=student, course=course, question=x, selected_choice=y, marks_obtained=marks_obtainable, is_correct=True) print("correct") else: z = TakenQuiz(student=student, course=course, question=x, selected_choice=y, marks_obtained=marks_obtainable, is_correct=False) print("Not Correct") return render(request, 'classroom/students/take_exam_form.html', { 'course': course, 'question': question, 'course': course, 'total_questions': total_questions, 'choice': choice, 'marks_obtainable': marks_obtainable }) <form method="post" novalidate> {% csrf_token %} {% for questions in question %} <input type="hidden" name="question_pk" value="{{ questions.pk }}"> <h3 class="text-info">{{ questions.text|safe }}</h3> {% for choices in questions.answers.all %} <input class="form-check-input" type="radio" name="choice_pk{{ … -
mocking a post method in unittest doesn't work
I've write some code for my website that send a verification sms to users,the code works correct but now I want to test it and need to mock sending code, but test doesn't work. here is all of my code: I have a view that send a verification code to user like the following: view.py class SendCode(GenericAPIView): def post(self, request, *args, **kwargs): """some of code that send messages" I've write a test that doesn't work: @mock.patch('view.SendCode.post', autospec=True) class MyTest(unittest.TestCase): def setUp(self): self.client = Client() def test_get_data(self, mock_call_external_api): data = {'phone': '11111111'} self.client.post('/send-code/',json.dumps(data), content_type='application/json') self.assertTrue(mock_call_external_api.called) and here i've got the following error: AssertionError: Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` to be returned from the view, but received a `<class 'unittest.mock.MagicMock'> I've tried lots of solution such as changing the patch path but it doesn't really work. thanks in advance for any help -
"Convert regions extracted from wav audio file into Flac audio file " python using FFMPAG in Django
Regions extracted from wav audio file have "Invalid duration specification for ss" For Example in my case duration is in this format [(0.006000000000000005, 1.03), (2.0540000000000003, 4.870000000000003)] This is for converting regions into Flac format. class FLACConverter(object): # pylint: disable=too-few-public-methods """ Class for converting a region of an input audio or video file into a FLAC audio file """ def __init__(self, source_path, include_before=0.25, include_after=0.25): self.source_path = source_path self.include_before = include_before self.include_after = include_after def __call__(self, region): try: print("regions to convert in flac:{}".format(region)) start = region end = region # start = max(0, start - self.include_before) start = list(map(lambda x: tuple(max(0, y - self.include_before) for y in x), start)) end = list(map(lambda x: tuple(y + self.include_after for y in x), end)) temp = tempfile.NamedTemporaryFile(suffix='.flac', delete=False) command = ["ffmpeg", "-ss", str(start), "-t", str([tuple(x-y for x, y in zip(x1, x2)) for (x1, x2) in zip(end, start)]), "-y", "-i", self.source_path, "-loglevel", "error", temp.name] use_shell = True if os.name == "nt" else False subprocess.check_output(command) print(temp.name) #subprocess.check_output(command, stdin=open(os.devnull), shell=use_shell) read_data = temp.read() temp.close() os.unlink(temp.name) print("read_data :{}".format(read_data)) print("temp :{}".format(temp.name)) return read_data except KeyboardInterrupt: return None I expect the output of '/var/folders/p1/6ttydjfx2sq9zl4cnmjxgjh40000gp/T/tmpwz5n4fnv.flac' but it returns an error CalledProcessError at / Command '['ffmpeg', '-ss', '[(0.006000000000000005, 1.03), (2.0540000000000003, 4.870000000000003)]', '-t', '[(0.5, … -
Django, sendmail password not from settings
Im using Djangos sendmail and I wont use password from settings. Current im using in settings EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'my Email' EMAIL_HOST_PASSWORD = 'its secret' EMAIL_PORT = 587 And in my view Im using: from django.core.mail import EmailMultiAlternatives EMAIL_HOST_PASSWORD = current_user.profile.gmail_app_pass EMAIL_HOST_USER = email_user = request.user.email toaddr = 'to@email' tocc = 'toCC@email' user_bcc = 'toCC@email' subject = 'Test Email from Django' msgHtml = '<p>This is an <strong>important</strong> message.</p>' msg = EmailMultiAlternatives(subject, msgHtml, EMAIL_HOST_USER, [toaddr], bcc=[user_bcc], cc=[tocc]) msg.attach_alternative(msgHtml, "text/html") msg.send() but how can I overwrite the settings from the settings? In my case EMAIL_HOST_PASSWORD and EMAIL_HOST_USER Im using Django 2.1 on Python 3.6 -
Sending POST with checkbox value changes with Django
I have a table and in the table a form with fields the user can change. Three of these fields use check boxes. I'm able to reflect what is currently in the database after following this post, but I haven't been able to find something else for the next piece of the puzzle. The problem I'm having is that if a checkbox is set to true(checked) and then I unselect it, the POST data does not include anything that says that it is not checked anymore. It doesn't give a value of "off", "0" or false. How can I make sure that when the boxes are unchecked I still get those values("off", 0" or "false")? on the post data? Below is my code: <form id=result_form action= "{% url 'example:save_notes' %}" method="post"> {% csrf_token %} <table id="results_table" class="formdata" summary="Example Search Results" data-order='[[ 1, "des" ]]' data-page-length='25'> <thead> <tr> <th style="width:5%" scope="col">Search Method</th> <th style="width:20%" scope="col">Search Date</th> <th style="width:5%" scope="col">City</th> <th style="width:10%" scope="col">Example Name</th> <th style="width:10%" scope="col">Article Title</th> <th style="width:10%" scope="col">Article Link</th> <th style="width:5%" scope="col">Reviewed </th> <th style="width:5%" scope="col">J/J Related</th> <th style="width:5%" scope="col">N Related</th> <th scope="col">General Notes</th> <th scope="col">Findings</th> <th scope="col">Edit</th> </tr> </thead> <tbody> {% for result in results %} <tr> <td>{{result.notes.method}}</td> … -
Syntax warning in PyCharm when loading Django models through apps.get_model
Very minor thing here but wondering if anyone has ever encountered this. There are many instances where we have models from two apps that call each other, which causes circular dependency in Django (and python). The way around this to make use of apps.get_model. When I write a line that get's the model, I like to store the result in an upper case camel case format that mimics what the model would actually look like via a regular import, for example, like this: MyModel. Let's have this line: MyModel = apps.get_model('my_app', 'MyModel') This causes a yellow warning underline of the first MyModel in the line and says: Variable in function should be lowercase. Is there a good way around this? Should I be naming the variable differently? -
Join query sets but keep annotated fields with different values
The problem I'm trying to solve is to perform a search that involves multiple steps of relevance based on the initial query, e.g.: Search for "Michael Scott" Firstly, we try to match "Michael Scott" directly and save it to full_name This will probably return the most relevant objects Next, multiple queries will be run to search for each word separately like "Michael" and "Scott" and this will be set to words This will return lots of results, most being noise if it's a very common name In the end, the query sets are joined using full_name | words but this ends up mixing the results because of the model's ordering while what I wanted was to keep the everything in full_name before what's in words. To try to fix that, I annotated both query sets with a new value and tried to order by it after: full_name = full_name.annotate(relevance=Value(1, IntegerField())) words = words.annotate(relevance=Value(2, IntegerField())) return (full_name | words).order_by('relevance') What happens is that everything in words is changed to also have relevance=1 instead of keep the value of 2 I set before, rendering my ordering attempt useless... I know there are other ways to achieve the ordering I want, like converting … -
Django form.is_valid giving False
ModelsForm return datetime in ISO format like: 2019-04-10T06:30:00 In views.py I'm checking that character 'T' contained inside the response string and transform ISO to python datetime format. Thereafter I replace forms field with new values. If string consist only date - 2019-04-10, event_form.is_valid() return True and new instanse are creating. But if string consist time, is_valid return False. views.py def event(request): all_events = Events.objects.all() if request.method == 'POST': event_form = ModelEventsForm(request.POST) start = (event_form['start_date'].value()) end = (event_form['end_date'].value()) if 'T' in start and end:#Check that time include in data string (for create events from daily and week view) start = datetime.strptime(start, "%Y-%m-%dT%H:%M:%S") end = datetime.strptime(end, "%Y-%m-%dT%H:%M:%S") event_form = ModelEventsForm(initial={'start_date': start, 'end_date': end}) if event_form.is_valid(): update = event_form.save(commit=False) update.owner = request.user.profile update.start_date = event_form.cleaned_data['start_date'] update.end_date = event_form.cleaned_data['end_date'] update.save() return redirect('events:event') else: event_form = ModelEventsForm() context = { "events": all_events, 'event_form': event_form } return render(request, 'profile/event_management.html', context) form.py <form method="POST"> {% csrf_token %} <div class="form-group"> <label for="event_name">Event name</label> {% render_field event_form.event_name class="form-control" id='event_name' %} </div> <div class="form-group"> <label for="start-date">Event start</label> {% render_field event_form.start_date class="form-control datepicker" id='start-date' %} </div> <div class="form-group"> <label for="end-date">Event end</label> {% render_field event_form.end_date class="form-control datepicker" id='end-date' %} </div> <button type="submit" class="btn btn-primary">Создать событие</button> </form> The start and end values are … -
Django - Post data not in form.cleaned_data leading to key error
I have a dynamically created form build with Django. When this form is submitted i can see all the data in request.post, that being said when i access form.cleaned_data one of the inputs is not there. This is causing a KeyError when i try to access it. There are no errors caused by the form and the form is appearing valid. If anyone has any other avenues i could look, i would be very appreciative. Here is the error: Internal Server Error: /gluiq/StrategicBrief/ Traceback (most recent call last): File "/Users/matthew/python3venv/gluiq/lib/python3.7/site-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/Users/matthew/python3venv/gluiq/lib/python3.7/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/matthew/python3venv/gluiq/lib/python3.7/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/matthew/python3venv/gluiq/lib/python3.7/site-packages/django/views/generic/base.py", line 68, in view return self.dispatch(request, *args, **kwargs) File "/Users/matthew/python3venv/gluiq/lib/python3.7/site-packages/braces/views/_access.py", line 102, in dispatch request, *args, **kwargs) File "/Users/matthew/python3venv/gluiq/lib/python3.7/site-packages/django/views/generic/base.py", line 88, in dispatch return handler(request, *args, **kwargs) File "/Users/matthew/PycharmProjects/GluIQ/DreamIt/views.py", line 494, in post ThisAwnser = str(form.cleaned_data[str('DropdownList_' + str(a))]) KeyError: 'DropdownList_6' [09/Apr/2019 12:25:51] "POST /gluiq/StrategicBrief/ HTTP/1.1" 500 97452 Here is the View although i don't feel it will help: def post(self, request): if request.method == 'POST': files = Files.objects.get(FileName="Strategic Brief") self.request.session['activeFile'] = files.id form = OutlineBusinessCaseForm(request.POST, request.FILES, Questions=files.questions.all()) activeproject = request.session['activeProject'] … -
Applying css to Django generated form objects for textarea
The following screenshot shows the forms.py code for generating the textarea input box on the right hand side (which has placeholder text: "Your comment to the world"). The CSS however, is applied only to the pure html textarea box (to the left) and I cannot figure out how to get it to be applied to the Django generated textarea input box. You'll notice that the css has been automatically applied to the top 'Name' text input field. The styles.css code is here: body { background-color: white; } h1 { color: red; text-shadow: 3px 2px grey; font-family: Arial } p { color: black; font-family: Arial } input[type=text] { width: 20%; padding: 21px 20px; margin: 14px 0; box-sizing: border-box; font-size: 33; border: 2px solid red; border-radius: 4px; font-family: Arial } textarea[type=textarea] { width: 20%; padding: 21px 20px; margin: 14px 0; box-sizing: border-box; font-size: 33; border: 2px solid red; border-radius: 4px; font-family: Arial } forms.py (as shown above with the rendering of HTML) is below from django import forms class CommentForm(forms.Form): name = forms.CharField(max_length=20,widget=forms.TextInput(attrs={'placeholder':'Your Name Please'})) comment = forms.CharField(widget=forms.Textarea(attrs={'placeholder':'Your comment to the world'})) And finally, the sign.html page (with the html for the relevant page) is below {% load static %} <!DOCTYPE html> … -
How to filter objects using multiple-choice in many-to-many relations
In this simplified example, I have models named Movie and Genre, in many-to-many relationship. The template shows multiple-choice box where I can select multiple genres, which are returned to the view as an array, for example genres = ['Action', 'Comedy', 'Drama']. Now, I need to filter Movie object, which has exactly those three genres. I known that I can filter single choice with Movie.objects.filter(genre__name__exact = 'Action'). I known that I can use Movie.objects.filter(genre__name__in = ['Action', 'Comedy', 'Drama']), but that returns movies which have at least one of the genres from the array, I don't need that. What I need is a queryset of movies that has exactly ['Action', 'Comedy', 'Drama'], no more, no less. I also tried getting the genre queryset first: Genre.objects.filter(name__in = ['Action', 'Comedy', 'Drama']), and than using this queryset to filter Movie object, but I don't know if it's even possible. I had read the documentation on making queries, but didn't find the solution there. -
Django GenericIPAddressField
hey I have working on some project now I want to add IP address fields in every model ip_address = models.GenericIPAddressField() adding like this now when I migrate it I got an error like this if value and ':' in value: TypeError: argument of type 'int' is not iterable how can I fix this? -
How to convert List of Dictionary to Django Model class object with mapping?
I'm trying to perform raw query in django for faster operation rather than ORM specified. what i want to convert cursor result into the model class object of that result. cursor.execute("select * from X;") suppose i have a model class X(models.Model): a ... b ... I want to convert cursor to that model class of that django. -
How to delete an object using destroy function Django Rest Framework
I already managed to perform get one and get all requests , i'm now trying to delete and create new users through url . views.py : class EtudiantViewSet(viewsets.ModelViewSet): queryset=Etudiant.objects.all() serializer_class=EtudiantSerializer router.py : router=routers.DefaultRouter() router.register('etudiants',EtudiantViewSet) urls.py : urlpatterns = [ url(r'^admin/', admin.site.urls), path('api/',include(router.urls)),] models.py : class Etudiant(models.Model): id=models.IntegerField(primary_key=True) nom=models.CharField(max_length=20) prenom=models.CharField(max_length=20) cne=models.CharField(max_length=10) email=models.EmailField() tel=models.CharField(max_length=10) def __str__(self): return 'Nom : {} , Prénom : {}'.format(self.nom,self.prenom) serializers.py : class EtudiantSerializer(serializers.ModelSerializer): class Meta : model=Etudiant fields='__all__' Any recommendations ? -
Show data from database (python) in HTML
I want to show the RandomId which is saved in database in my HTML, but I am not sure how to do it. Anyone know how to do it? Here is my html </script> <button onclick="myFunction()"><input type="submit" value="Place Order"></button> <script> function myFunction() { alert("Order has been placed in the kitchen \n Your order ID is {{% random_id %}}") } </script> here is my views.py RandomId = request.POST.get("RandomId") RandomId = get_random_string(length=5) #get random string id #RandomId = request.POST.get("RandomId") customerOrder = CustomerOrder(Table_Num=Table_Num , Food=Food, Quantity=Quantity, Message=Message, RandomId=RandomId) #get data into the CustomerOrder db customerOrder.save() #save data into db random_id = CustomerOrder.objects.all() #order_summary = CustomerOrder.objects.filter(Table_Num = request.Table_Num) #order_summary = CustomerOrder.objects.filter(Table_Num = 15) return render(request, 'restaurants/customer_page.html', {'random_id': random_id}) #return customer page -
How to access multiple nested models in django?
I have multiple models with all going to the model Grade. My models are as below: class Grade(models.Model): grade = models.CharField(max_length=255, unique=True) class Student(models.Model): class Meta: unique_together = ("rollno", "grade") name = models.CharField(max_length=255) grade = models.ForeignKey(Grade,related_name='StudentList', on_delete=models.CASCADE) rollno = models.BigIntegerField(unique = True) class GradeTotal(models.Model): grade = models.ForeignKey(Grade, related_name='GradeMarks', on_delete=models.CASCADE) average = models.IntegerField() total = models.IntegerField() class StudentTotal(models.Model): rollno = models.ForeignKey(GradeTotal, related_name='StudentMarks', on_delete=models.CASCADE) marks = models.IntegerField() I am trying to get the average and total marks of the grade and which should also have a list of students' marks(might or might not have the data for all students in that grade) but should be displaying all the students. So the JSON payload would be like this: { "grade" : "ten", "GradeMarks": [ { "average": 42, "total": "574" , "StudentMarks": [ { "rollno": 1, "marks": 40 }, { "rollno": 2, "marks": 45 } ] } ] } I am sure about the first three models, but not sure if the fourth. For further clarification, I have also added the serialize: class GradeSerializet(serializers.ModelSerializer): StudentMarks = serializers.SlugRelatedField( many=True, read_only=True, slug_field='rollno' ) class Meta: model = GradeTotal fields = ('average', 'total', 'StudentMarks' ) class MultipleGradeSerializet(serializers.ModelSerializer): GradeMarks = GradeSerializet(many=True) grade = serializers.CharField() class Meta: model = … -
GeoDjango inspectdb with multiple databases
I'm trying to run inspectdb on a PostgreSQL DB with Postgis. To generate the model for a postgresql view, I found here that I should use the command: python manage.py inspectdb --database my_schema my_view> my_view_legacy.py But because of PostGIS, inspectdb also tries to access a view in another schema, which raises the following error when it encounters a field of type geometry in my_view: django.db.utils.ProgrammingError: relation "geometry_columns" does not exist LINE 1: SELECT "coord_dimension", "srid", "type" FROM "geometry_colu... This seems like a catch-22: if I specify the database name so that inspectdb knows which view to inspect, it cannot find find the geometry_columns view in the public schema. But if I don't specify any database name, it cannot find my_view in the first place. Is there any solution to this? My database schemas are defined as: DATABASES = { 'default': { }, 'public': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'OPTIONS': { 'options': '-c search_path=public' }, 'NAME': 'my_db', 'USER': secrets.USER, 'PASSWORD': secrets.PASSWORD, 'HOST': 'my.host.addr', 'PORT': '5432', }, 'my_schema': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'OPTIONS': { 'options': '-c search_path=my_schema' }, 'NAME': 'my_db', 'USER': secrets.USER, 'PASSWORD': secrets.PASSWORD, 'HOST': 'my.host.addr', 'PORT': '5432', }, } -
How to point to templates in django
I am new to code. I have this code that generates notifications every time an activity related to a given user is done. At the moment, the notifications are simply stored in a table. I want to send the same notification to user's email but I can't seem to find out how. This is my settings cofigurations: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['authors/apps/notifications/templates/', 'authors/apps/authentication/templates/'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'social_django.context_processors.backends', 'social_django.context_processors.login_redirect', ], }, },] And this is where my emails should be sent to their respective users: def email_notification(sender, instance, created, **kwargs): """ sends an email notification for notifications """ user = instance.recipient recipients = User.objects.filter(email=user) deactivation_link = "link.com" if created: for recipient in recipients: if recipient.email_notification is True: mail_helper.send_mail( subject="Author's Haven notifictions", to_addrs=recipient.email, multiple_alternatives=True, template_name='notifications.html', template_values={ 'username': recipient.username, 'optout_link': deactivation_link, 'description': instance.description } ) post_save.connect(email_notification, sender=Notification) This generates the notifications but does not send it to the user's email. It raises the error: TemplateDoesNotExist at /api/articles/ authors/apps/authentication/templates/emailing_template.html How do I get Django to point to the template instead of the endpoint? -
Skip function decorator of the parent class function when called from child class
Say I have two class A and B. When the test() function is called from child class B using super , it should skip the @validate decorator. How can I force the super method to skip the decorator of the parent class function when called from the child class? Is there any possibilty? class A: @validate def test(): pass Class B(A): @validate def test() super(B, self).test() pass -
Django channels 1.x how to authenticate user
I run a django server and am trying to create a channel for chatting. The client is a react-native application, with javascript backend. When the user connects to the server via websocket (or afterwards with a message, whatever is better), I want to be able to perform an authentication check, to see if the user is already in the database and get who this user is. I use default django auth accounts (django.contrib.auth.models). For authenticating the http requests I use django.contrib.auth.decorators.login_required and from the client I send an Authorization Header with the JWT token. How should I do the same for websocket requests? The recommended chat consumer uses channels.auth.channel_session_user_from_http. Is this the correct way for what I want? And how can I send the user's credentials (or token) from the client so that the server can check them? I saw a relevant SO question and the relevant documentation, but could not solve my problem. Any help would be appreciated. django version: 1.11.20 django-channels version: 1.1.8 -
django - AttributeError: 'NoneType' object has no attribute
I have a quiz which allows students to take a quiz and place bid and it stores the data into a database(the bid has a URL). But this does not have the option to update the bid. I tried to create a new button which has the same URL so that I can allow to retake the quiz but it throws AttributeError: 'NoneType' object has no attribute How can add this functionality to my app ? Here is the code: def take_quiz(request, pk): quiz = get_object_or_404(Quiz, pk=pk) supplier = request.user.supplier total_questions = quiz.questions.count() unanswered_questions = supplier.get_unanswered_questions(quiz) total_unanswered_questions = unanswered_questions.count() progress = 100 - round(((total_unanswered_questions - 1) / total_questions) * 100) question = unanswered_questions.first() if request.method == 'POST': form = TakeQuizForm(question=question, data=request.POST) if form.is_valid(): with transaction.atomic(): supplier_answer = form.save(commit=False) supplier_answer.supplier = supplier supplier_answer.save() if supplier.get_unanswered_questions(quiz).exists(): return redirect('suppliers:take_quiz', pk) else: correct_answers = supplier.quiz_answers.filter(answer__question__quiz=quiz, answer__is_correct=True).count() score = round((correct_answers / total_questions) * 100.0, 2) print("--------------------------------------------------> " + str(supplier_answer.least_bid)) least_bid = supplier_answer.least_bid TakenQuiz.objects.create(supplier=supplier, quiz=quiz, score=score,least_bid=least_bid) #least_bid=least_bid if score < 50.0: messages.warning(request, 'You have successfully placed a bid of %s' % (least_bid)) else: messages.warning(request, 'You have successfully placed a bid of %s' % (least_bid)) return redirect('suppliers:quiz_list') else: form = TakeQuizForm(question=question) return render(request, 'classroom/suppliers/take_quiz_form.html', { 'quiz': quiz, … -
how to use django_select2 in form
i have a ModelChoiceField and it's realy big so i want to use ModelSelect2Widget to filter the choices in my ModelChoiceField . i used this code but he didnt work i want like this https://www.drupal.org/files/project-images/select2.png this is my code class Ajout4 (forms.Form): client=forms.ModelChoiceField(queryset=Suivre.objects.all(),widget=ModelSelect2Widget(model=Suivre,search_fields=['numcniF'],dependent_fields={'numcniF': 'numcniF'},max_results=500,)) montant=forms.FloatField(required=True,widget=forms.NumberInput(attrs={'placeholder':'Paye MTN '})) myhtml <form method="post"> <div class="container"> <div>{% load crispy_forms_tags %} {% csrf_token %} {{con|crispy}} <button type="submit" class="btn btn-success" > SAVE</button> <button type="reset" class="btn btn-danger">RESET</button> -
Django,html template,for loop not working as expected
I am trying to apply a for loop to the following html (in a Django project) such that the 'Name' and the 'Comments' field are caused to repeat on the html view. When I insert the templating code, that is: {% for c in comments %} {% endfor %} on either side of the content i want to repeat, it simply makes the name and comments disappear altogether and does not have the desired result. The relevant parts of the file are below: index.html (the main html page) {% load static %} <!DOCTYPE html> <html> <head> <link rel="stylesheet" href="{% static 'guestbook/styles.css' %}"> </head> <body> <h1>The world's guestbook</h1> <p><a href="{% url 'sign' %}">Sign </a>the guestbook</p> {% for c in comments %} <h2>Name</h2> <p>This the message that the user leaves.</p> {% endfor %} </body> </html> views.py (in the guestbook app) from django.shortcuts import render from .models import Comment # Create your views here. def index(request): comments = Comment.objects.order_by('-date_added') context ={'comments': comments} #name=Name.objects.order_by('-date_added') return render(request,'guestbook/index.html') def sign(request): return render(request,'guestbook/sign.html') models.py file from django.db import models from django.utils import timezone # Create your models here. class Comment(models.Model): name=models.CharField(max_length=20) comment=models.TextField() date_added=models.DateTimeField(default=timezone.now) def __str__(self): return self.name I am working off a tutorial in which this is … -
How to create a field in django model using values of other fields?
I have this model called Order which save the information about the user and another model called OrderItem which save the products which the user had ordered. i have join the OrderItem model with Order using Tabular Inline. Now what i want is to calculate the total price by multiplying the price and product quantity(which are the fields of OrderItem model) and save the total price in Order model as shown in the picture. I have asked this question before but didn't get the satisfactory answer. from django.contrib import admin from .models import Order, OrderItem from pizza_app.models import UserTypes from django.db.models.signals import pre_save from django.db.models import Sum, F, FloatField class OrderItemInline(admin.TabularInline): model = OrderItem class OrderAdmin(admin.ModelAdmin): list_display = ['id','name','total' ,'mobile_no','address','status', 'created'] list_editable = ['status'] list_per_page = 10 list_filter = ['status'] readonly_fields= ['total'] search_fields = ('id','mobile_no','name',) inlines = [OrderItemInline] def get_form(self, request, obj=None, **kwargs): form = super(OrderAdmin,self).get_form(request, obj,**kwargs) form.base_fields['Assigned_to'].queryset = form.base_fields['Assigned_to'].queryset.filter(staff_status='Delivery Boy') return form admin.site.register(Order, OrderAdmin) from django.db import models from pizza_app.models import MenuVariant from django.urls import reverse from django.db.models import Sum, F, FloatField from pizza_app.models import UserTypes # from django.contrib.auth.models import User from django.db.models.signals import pre_save,post_save class Order(models.Model): name = models.CharField(max_length=60) email = models.EmailField(max_length=60,default=None,blank=True) mobile_no = models.CharField(max_length=13, default=None) address = …