Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Create a dynamic form (not only in number of items but structure) in Django
I am new to django and I am struggling to develop the following. I have a survey app in which an admin user can provide to create a new survey template a CSV with a variable number of questions and answers per question, wich may be True or False indistinctly. This is stored using these three different models: class Survey(models.Model): survey_name = models.CharField(max_length=50, unique=True) answer_key = models.CharField(max_length=250) score_key = models.CharField(max_length=250) date = models.DateTimeField(auto_now_add=True) class Question(models.Model): survey = models.ForeignKey(Survey, on_delete=models.CASCADE) text = models.CharField(max_length=250) class Answer(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) text = models.CharField(max_length=250) valid = models.BooleanField(default=False) I know how to retrieve the associated objects for a given survey in a view and show them a template, but not how to represent them in a form, since the number of questions and answers per question are not known beforehand. Also not sure how this would be read when processing the POST. Any hint would be much appreciated. Thanks! -
django admin site download to excel
I already install django-import-export, i dont get any error on exporting data to excel, but why is it when i open the excel file, some data is number? especially the foreignkey? this is my admin.py from import_export.admin import ExportActionMixin @admin.register(CustomerPurchaseOrder) class CustomerPurchaseOrderAdmin(ExportActionMixin, admin.ModelAdmin): list_filter = ("process", "deliverySchedule", "inputdate") list_display = ('profile', 'customer_Purchase_Order_Detail', 'process', 'deliverySchedule', 'deliveryDate', 'paymentmethod', 'requestedDate',) ordering = ('id','requestedDate') pass my models.py class CustomerPurchaseOrder(models.Model): profile = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True, blank=True, verbose_name="Client Account") customer_Purchase_Order_Detail = models.ForeignKey('CustomerPurchaseOrderDetail', on_delete=models.SET_NULL, null=True, blank=True, verbose_name="Customer Purchase Order") process = models.ForeignKey('Process', on_delete=models.SET_NULL, null=True, blank=True, verbose_name="Process") .... def __str__(self): suser = '{0.profile}' return suser.format(self) -
How can i access model method in django admin class
I've one proxy model like this. class Category(GenericCategory): class Meta: proxy = True verbose_name = "Category" verbose_name_plural = "Categories" @property def get_content_type(self): return ContentType.objects.get_for_model( self.__class__, for_concrete_model=False ) Now i want to access get_content_type method in django admin class so that i can filter data in django admin. -
Invalid block tag : 'boostrap_form', django.template.exceptions.TemplateSyntaxError
Getting this error when i'm trying to use bootstrap4 i've only copy and pasted the sections but i included the imports up the top. boostrap4 is also registered as an INSTALLED_APPS: in settings.py django.template.exceptions.TemplateSyntaxError: Invalid block tag on line 927: 'boostrap_form', expected 'endblock'. Did you forget to register or load this tag? {% extends 'base.html' %} {% load static %} {% load bootstrap4 %} {% block bodyblock %} <form method="post" class="form-control"> <div class="col-md-4"> <div class="form-group"> {% csrf_token %} {% boostrap_form form %} </div> </div> -
not receive error response for reservation API endpoint
I wrote the rest api end point for reservation. it checks availability of the room and if it isn't available respond with error. The point that the code runs and if statement check works well and no new object is created but I cannot see the response error. This is my views.py: class ReservationViewSet(viewsets.ModelViewSet): """Manage Reservation in database""" queryset = Reservation.objects.all() serializer_class= serializers.ReservationSerializer def get_queryset(self): """return a list of Reservations""" return self.queryset.order_by('-id') def perform_create(self, serializer): """create a new Reservation if available""" Room_ID = self.request.data.get('RoomID') Start_Date= self.request.data.get('StartDate') End_Date= self.request.data.get('EndDate') Check1 = Reservation.objects.filter(RoomID=Room_ID).filter(StartDate__gte=Start_Date).filter(StartDate__lte=End_Date) Check2 = Reservation.objects.filter(RoomID=Room_ID).filter(EndDate__gte=Start_Date, EndDate__lte=End_Date) Check3 = Reservation.objects.filter(RoomID=Room_ID).filter(StartDate__gte=Start_Date).filter(EndDate__gte=Start_Date).filter(StartDate__lte=End_Date).filter(EndDate__lte=End_Date) if (Check1 or Check2 or Check3): serializer.is_valid(raise_exception=True) print("it is not allowed") return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) else: serializer.save() this is urls.py: from django.urls import path, include from rest_framework.routers import DefaultRouter from reservation import views router = DefaultRouter() router.register('', views.ReservationViewSet) app_name='Reservatiom' urlpatterns=[ path('', include(router.urls)), ] This is my serializer.py from rest_framework import serializers from core.models import ListingOwner, Room, Reservation from room.serializers import RoomSerializer class ReservationSerializer(serializers.ModelSerializer): """"Serializer for making a new Reservation""" RoomID = serializers.PrimaryKeyRelatedField(queryset=Room.objects.all(),many=True) class Meta: model = Reservation fields=('id','ReserverName','StartDate', 'EndDate', 'RoomID' ) -
Django Create file in MEDIA_ROOT folder and save it to FileField
Currently I want to create a file under MEDIA_ROOT folder and save it to FileField. I searched on SO website, tried the method on django-how-to-create-a-file-and-save-it-to-a-models-filefield and other, but looks it saved absolute path on my db. My Model class Voice(models.Model): xxx other field textFile = models.FileField(null=True,blank=True,default=None,upload_to='text_file', unique=True) Update textFile field as following: @receiver(post_save, sender=Voice) def create_text(sender,**kwargs): xxx f = open(settings.MEDIA_ROOT + '/text_file/'+ text_file,'w') queryset = Voice.objects.all() queryset.filter(pk=voice.pk).update(textFile=File(f)) f.close() And I find it save something like this on db: "textFile": "http://127.0.0.1:8000/media/Users/usersxxx/Documents/xxx/media/text_file/t5" while not: "http://127.0.0.1:8000/media/text_file/t5", -
Display the form for all foreign key data as text field
I have created this model: class LinePipeRate(models.Model): dia = models.ForeignKey(Diameter, on_delete=models.CASCADE) method = models.ForeignKey(Method,related_name='line_pipe_rate', on_delete=models.CASCADE,null=True,blank=True,) currency = models.ForeignKey(Currency, on_delete=models.CASCADE) linepipe_rate = models.FloatField(default=0,null=True,blank=True) Following is my Form: class LinePipeRateForm(forms.Form): currency = forms.ModelChoiceField(queryset=Currency.objects.all()) dia= forms.IntegerField() rate = forms.IntegerField() I want to take user input for all the diameters in single form so, In the template, I have displayed form as follows: <table> <tr> <td><label for="{{ wizard.form.currency.id_for_label }}">Currency </label>{{wizard.form.currency}}</td> </tr> </table> <table> <thead> <tr> <th>Diameter in inch</th> <th>Rate</th> </tr> </thead> {% for dia in diameter %} <tr> <td><input type="text" id="{{ wizard.form.dia.id_for_label }}" name="dia" value={{dia.dia}} readonly="readonly"></td> <td>{{ wizard.form.rate }}</td> </tr> {% endfor %} </table> This is the format in which I want to display the form, but I am not able to save the data in the model. Please help me. -
Temporary MEDIA_ROOT for testing not working
For the purpose of testing user media uploads, I have created a temporary MEDIA_ROOT in my test module so that the development directory doesn't become polluted with mock images. I have stumbled upon this and how Django happens to achieve the same task of creating/destroying a temporary MEDIA_ROOT: https://github.com/django/django/blob/master/tests/file_uploads/tests.py#L26 When the tests are ran however, I get the following error \test_models.py", line 17, in <module> MEDIA_ROOT = mkdtemp(prefix="media/") File \Python\Python37\lib\tempfile.py", line 366, in mkdtemp _os.mkdir(file, 0o700) FileNotFoundError: [WinError 3] The system cannot find the path specified: 'C:\\..\\..\\..\\..\\Temp\\media/0_axhu0o' How can I get the test to pass so that path of image file is stored relative to the temporary MEDIA_ROOT with that directory having the same name of media/? tests.py MEDIA_ROOT = mkdtemp(prefix="media/") @override_settings(MEDIA_ROOT=MEDIA_ROOT) class TestPhotoModel(TestCase): @classmethod def setUpData(self): os.makedirs(MEDIA_ROOT) user = User.objects.create_user("Testuser") test_image = SimpleUploadedFile( "test_image.jpg", content=b"", content_type="image/jpeg" ) freezer = freeze_time("2020-12-31") freezer.start() data = { "source": test_image, "title": "Test Image", "upload_date": datetime.date.today, "likes": 0, "photographer": user } self.photo_instance = Photo.objects.create(**data) def test_photo_count(self): self.assertEqual(Photo.objects.count(), 1) def test_image_upload_path(self): self.assertEqual( self.photo_instance.source.path, "media/uploads/2020/12/31/test_image.jpg" ) @classmethod def tearDownClass(cls): rmtree(MEDIA_ROOT) super().tearDownClass() -
UNIQUE constraint failed, when pressing submit button. (Django)
For some reason when I press the submit button to save a UserRegisterForm object I get an error: UNIQUE constraint failed, even though the info does submit to the database. It is extra odd because when I press the enter key to submit the data, the program functions perfectly fine. I am watching a tutorial and the code is copied verbatim. I would appreciate any help, thanks! views.py: def register(request): 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}) Register.html: {% extends "blog/base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Join Today</legend> {{ form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Sign Up</button> </div> </form> <div class="border-top pt-3"> <small class="text-muted"> Already Have An Account? <a class="ml-2" href="#">Sign In</a> </small> </div> </div> {% endblock content %} The tutorial I am following(Demonstrated around 31:29): https://www.youtube.com/watch?v=q4jPR-M0TAQ&list=PL-osiE80TeTtoQCKZ03TU5fNfx2UY6U4p&index=6. -
how can i convert manytomanyfield dropdown into input field?
i am using two forms for updating book and lesson name too. the {{book_update}} is working fine but {{lesson_form_list}} it's not working as a required it is empty []. how do i use {{lesson_form_list}} as a input field, when i try to apply my code it's blank. i want to make a small variation in the existing method that is instdad of dropdown i want to introduce throug input field. models.py class Book(models.Model): title = models.CharField(max_length=10) created = models.DateTimeField(auto_now_add=True) lesson = models.ManyToManyField(Lesson) forms.py class BookForm(forms.ModelForm): class Meta: model = Book fields = ['title', 'lesson'] class LessonForm(forms.ModelForm): result_values = forms.CharField(max_length=10) class Meta: model = Lesson fields = [ 'name', 'result_values', 'expected_values' ] views.py def book_update_form(request, pk): book = get_object_or_404(Book, pk=pk) b_form = BookForm(request.POST or None, instance=book) l_form = [LessonForm(request.POST or None, prefix=str( lesson.pk), instance=lesson) for lesson in book.lesson.all()] if request.POST and b_form.is_valid() and all([lf.is_valid() for lf in l_form]): b_form.save() for lf in l_form: lesson_form = lf.save() return redirect('dashboard') context = { 'book_update': b_form, 'lesson_form_list': l_form } return render(request, 'patient/report.html', context) update_form.html <div class=" form-group"> <label for="id_title">book</label> {{book_update}} </div> <div class=" form-group"> <label for="id_lesson">Lessons</label> {{lesson_form_list}} </div> -
how to re deploy updates to elastic bean stalk, issue with allowed hosts django
It seems like eb deploy is the solution. But notice this error: Invalid HTTP_HOST header: 'hiddenforstackoverflow'. You may need to add 'hiddenforstackoverflow' to ALLOWED_HOSTS. however, I go to my allowed hosts in my django settings. ALLOWED_HOSTS = ['hiddenforstackoverflow'] the HTTP_HOST header is the same as the one django is complaining about. I run eb deploy all day and nothing changes. Is there a cache or something? -
DJANGO get objects in sql like join
Context: I'm forcing my self to learn django, I already wrote a small php based website, so I'm basically porting over the pages and functions to learn how django works. I have 2 models from django.db import models class Site(models.Model): name = models.CharField(max_length=50, unique=True) def __str__(self): return self.name class Combo(models.Model): username = models.CharField(max_length=50) password = models.CharField(max_length=50) dead = models.BooleanField(default=False) timestamp = models.DateTimeField(auto_now_add=True) siteID = models.ForeignKey(Site, on_delete=models.PROTECT) class Meta: unique_together = ('username','password','siteID') def __str__(self): return f"{self.username}:{self.password}@{self.siteID.name}" When creating a view, I want to get the Combo objects, but I want to sort them first by site name, then username. I tried to create the view, but get errors about what fields I can order by Cannot resolve keyword 'Site' into field. Choices are: dead, id, password, siteID, siteID_id, timestamp, username def current(request): current = Combo.objects.filter(dead=False).order_by('Site__name','username') return render(request, 'passwords/current.html',{'current':current}) Since I'm not necissarily entering the sites into the database in alphabetical order, ordering by siteID wouldn't be useful. Looking for some help to figure out how to return back the list of Combo objects ordered by the Site name object then the username. -
Adding new pages in Django from existing data
I am trying to simply add a new 'blog' page in Django, which should replicate the home page. The home page is working fine, and if I view the URLs for my app, it looks like the following: urlpatterns = [ path('', views.PostList.as_view(), name='home'), path('<slug:slug>/', views.PostDetail.as_view(), name='post_detail'), ] In my understanding of Django, I could add a 'blog' page by adding the following: urlpatterns = [ path('', views.PostList.as_view(), name='home'), path('<slug:slug>/', views.PostDetail.as_view(), name='post_detail'), path('blog/', views.PostList.as_view(), name='blog'), #ADDED LINE ] However going to my http://127.0.0.1:8000/blog/ page returns a 404 error. With Django debugging enabled, I get the following message: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/blog/ Raised by: main_site_app.views.PostDetail From what I can observe, there is nothing additional that the index page has that the blog doesn't. Is there a step I'm missing here that is preventing the /blog/ page from showing up? -
How can i export data from Django to use excel as a calculator to later show the results in my Django website?
I have created a form using Django, and i would like to use the input data from this form in an excel template that i have, this template has many complicated formulas and way too many at that. I would like to export the input data of the form do all the calculations using the excel sheet and then later import the results in my Django website. i have tried using xlutils.copy to edit the file with the new data but by doing this it eliminates all formulas. How would i be able to do this? I am also new at Django so i'm not exactly sure where to put the command to export the data. I would be extremely grateful if someone could help me. from django.db import models from django.contrib.auth.models import User from django.urls import reverse from django.shortcuts import redirect import sys; sys.path import pandas as pd import numpy as np from openpyxl import load_workbook # Create your models here. class Pregunta(models.Model): genero = (('Hombre', 'Hombre'), ('Mujer', 'Mujer')) res = (('Verdadero', '1'), ('Falso', '2'), ('Blanco','3')) nombre = models.CharField(max_length=255, null= True) edad = models.IntegerField( null=True, blank=True) fecha = models.DateField(null= True) sexo = models.CharField(choices = genero,max_length=6, null= True) estado = … -
Exception Value: '<' not supported between instances of 'NoneType' and 'datetime.datetime'
I am trying to validate that the DateTime of an object cannot be earlier than yesterday. No matter what I do, I keep getting the same TypeError. Django Version: 3.0.5 Exception Type: TypeError Exception Value: '<' not supported between instances of 'NoneType' and 'datetime.datetime' Python Version: 3.8.2 models.py class Visit(BaseModel): start_utc = models.DateTimeField('Visit Start') end_utc = models.DateTimeField('Visit End') def clean(self, *args, **kwargs): super(Visit, self).clean() if self.start_utc < timezone.now() - timedelta(1): raise ValidationError("Visits cannot start in the past!") if not self.end_utc > self.start_utc: raise ValidationError("Visits cannot end before they have started!") forms.py class VisitForm(forms.ModelForm): start_utc = forms.DateTimeField(widget=forms.widgets.DateTimeInput(attrs={'type': 'datetime-local'})) end_utc = forms.DateTimeField(widget=forms.widgets.DateTimeInput(attrs={'type': 'datetime-local'})) -
Save items from Form in a list in Django
I'm trying to compare names inserted in an InlineForm before saving them. But I'm having some issues trying to save the names into a list and then compare them. Here is what I've tried to do. form.py class ColabForm(forms.ModelForm): class Meta: model = Colaboradores fields = '__all__' colaborador_projeto = forms.CharField(label="Colaborador do Projeto", widget=forms.TextInput( attrs={ 'class': 'form-control col-8', 'maxlength': '200', } )) def clean(self): colaborador_projeto = self.cleaned_data.get('colaborador_projeto') lista_erros = {} verifica_nome(colaborador_projeto) if lista_erros is not None: for erro in lista_erros: mensagem_erro = lista_erros[erro] self.add_error(erro, mensagem_erro) return self.cleaned_data validation.py def verifica_nome(colaborador_projeto): lista = colaborador_projeto.split() nomes = ''.join(lista) lista_nome = [] nome = '' for i in range(len(nomes)): nome += nomes[i] if i == (len(nomes)-1): lista_nome.append(str(nome)) Instead of getting a list with the names in different possitions, all the names are saved on list[0]. How can I fix it? -
Getting Error: Unsupported lookup 'id' for DecimalField or join on the field not permitted
I'm trying to get a DecimalField in Django from the database by using the ORM, so I can populate a field on my form. I'd like to do something like this: SELECT trainer_price FROM Trainer WHERE id=3). I'm getting this error: Unsupported lookup 'id' for DecimalField or join on the field not permitted. and can't figure out why my query is not working. This is what I've tried: price = Trainer.objects.filter(trainer_price__id=3) price = Trainer.objects.filter(trainer_price__pk=3) I've also referenced this StackOverflow article: How to filter GTE, LTE on Float or Decimal via Django ORM But am still getting the error mentioned above. Here's my full code for my views.py: def train(request): trainer_form = Trainer(request.POST) price = Trainer.objects.filter(trainer_price__id=3) context = {'trainer_form':trainer_form, 'price':price} return render(request, "register/trainer_form.html", context) Any ideas on what I'm doing wrong? Any help would be great! -
BS4 returning AttributeError: 'NoneType' object has no attribute 'text' sometimes, how to solve this?
I wrote a piece that tries to get some data from yahoo finance. However, first attempt it failed somewhere at the start after being able to retrieve stock data (price and change in price). It gave the NoneType error. Then I ran it again, and it actually was able to retrieve suddenly that data and continued to retrieve more and failed somewhere halfway with the same error. I find it weird, since that attribute text is present in the html. Especially weird that it is able to find it in the second attempt without adjustments. Also, it is all on the same page, so it is not that I need to wait for some. This is the error: price = soup_ticker.find('span', class_='Trsdu(0.3s) Fw(b) Fz(36px) Mb(-4px) D(ib)').text AttributeError: 'NoneType' object has no attribute 'text' This is the specific html: <span class="Trsdu(0.3s) Fw(b) Fz(36px) Mb(-4px) D(ib)" data-reactid="32">22.12</span> This is my Code. Mind that im a beginner and this is all for educational purposes. I know there are probably a million ways to do things better than I have done below to achieve the same. Thank you for your help in advance and for your knowledge! from django.core.management.base import BaseCommand from urllib.request import … -
Image will not upload from a form in django. Image will upload if entered from admin panel but not from form
the image will not upload if done thru the form. if the image is uploaded thru the admin interface it works properly.. after several hours of researching the docs and google I cannot figure out whats wrong if anyone has any clue I would be greatly appreciative model class Event(models.Model): TYPE = [ ('CYCLING','cycling'), ('STAIR CLIMB','stair climb'), ('RUNNING','running'), ] id = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False ) event_name = models.CharField('Event Name', max_length=100) event_location = models.CharField('Event Location', max_length=100) event_date = models.DateField('Event Date') event_description = models.TextField('Event Description') event_type = models.CharField('Event Type', max_length=30, choices=TYPE, default='CYCLING') event_img = models.ImageField( upload_to="eventImg/", blank=True, null=True ) def __str__(self): return self.event_name def get_absolute_url(self): return reverse('event-detail',args=[str(self.id)]) form.py class AddEventForm(forms.ModelForm): class Meta: model = Event fields = ('event_name','event_date','event_location','event_type','event_description','event_img') template {% extends '_base.html' %} {% load materializecss %} {% block title %} Add Event{% endblock title %} {% block content %} <div class="container" > <h1>Add Event </h1><i class = 'material-icons large'>pedal_bike</i><i class = 'material-icons large blue-text'>directions_walking</i><i class = 'material-icons small green-text'> directions_running</i> </i> <form method = 'POST' enctype="multipart/form-data"> {% csrf_token %} {{form|materializecss}} <button type = 'submit' class = 'btn waves-effect waves-light amber lighten-2 black-text hoverable'>Add Event <i class = 'material-icons right'>send</i></button> </form> </div> {% endblock content %} urls.py from django.contrib import admin … -
RadioSelect() get values of inputs
I want to pass RadioSelect() label, help text, name, choices and values through JSON. I managed to pass every of them but not values. How can I get values of each input field? I've read the Django docs and did research on google but didn't find any answer. Views.py: class ArticleUpdateView(UpdateView): model = User1 template_name = None def post(self, request, *args, **kwargs): ... def get(self, request, *args, **kwargs): form = BotForm(request.POST or None) self.object = self.get_object() for field in form.fields: # Delete HTML tags radio_inputs = [ strip_tags(html_inputs).replace('\n ', '') for html_inputs in form[field] ] # return unique id for each input and label id_for_label = [ form[field].auto_id + '_' + str(id) for id in range(len(radio_inputs)) ] # Make a dictionary from two above choices = [ {'id': id_for_label[i], 'label': radio_inputs[i]} for i in range(len(radio_inputs)) ] data = { 'label': form[field].label, 'help_text': form[field].help_text, 'name': form[field].name, 'choices': choices, } return JsonResponse(data, safe=False) Models.py: class User1(models.Model): types1 = ( ('a', 'some text'), ('b', 'some text1'), ('c', 'some text2'), ('d', 'some text3'), ) types2 = ( ('a', 'some text'), ('b', 'some text1'), ('c', 'some text2'), ('d', 'some text3'), ) types3 = ( ('a', 'some text'), ('b', 'some text1'), ('c', 'some text2'), ('d', 'some … -
Django : How to extend page slug with keep data model working? .../slug/ and .../slug/review/
I was wondering is there is a way extend page slug with keep data model working? .../slug/ and .../slug/review/ Assume I got a model called: Group(model.Model): creator = ... invitee = ... is_active = ... is_delivered = ... Rating(models.model): relatedto = models.ForeignKey(Group...) I create a group with a slug. This group is dedicated to 2 users only. Users can chat on the main page. I've created some UpdateView (is_active or is_delivered) with different form to complete some part of the main model. .../slug/activation/ Question: I want to create another model Rating related to Group. The goal is: to give a review to user of Group with a form (using ex. form.instance.creator = ...) to get the data easily) to keep the access only to creator and invitee. What kind of class I can use in my views.py? I've tried with UpdateView but with a form which is not the main model that's does not work. -
Output in JSON Format Django Model
I have 2 Django Models :- Userprofile model which has the user's name and timezone and Activity period which has its time of activity class UserProfile(models.Model): real_name = models.CharField(max_length=100) timezone = models.CharField(max_length=100) class ActivityPeriod(models.Model): start_time = models.DateTimeField() end_time = models.DateTimeField() I have to return the data from the database in this format { "ok": true, "members": [{ "id": "W012A3CDE", "real_name": "Egon Spengler", "tz": "America/Los_Angeles", "activity_periods": [{ "start_time": "Feb 1 2020 1:33PM", "end_time": "Feb 1 2020 1:54PM" }, { "start_time": "Mar 1 2020 11:11AM", "end_time": "Mar 1 2020 2:00PM" }, { "start_time": "Mar 16 2020 5:33PM", "end_time": "Mar 16 2020 8:02PM" } ] }, { "id": "W07QCRPA4", "real_name": "Glinda Southgood", "tz": "Asia/Kolkata", "activity_periods": [{ "start_time": "Feb 1 2020 1:33PM", "end_time": "Feb 1 2020 1:54PM" }, { "start_time": "Mar 1 2020 11:11AM", "end_time": "Mar 1 2020 2:00PM" }, { "start_time": "Mar 16 2020 5:33PM", "end_time": "Mar 16 2020 8:02PM" } ] } ] } But I am getting like this , The two models dont have the desired realtion I want [ { "model": "myapp.userprofile", "pk": 10, "fields": { "real_name": "Brittney Moore", "timezone": "Africa/Kampala" } }, { "model": "myapp.userprofile", "pk": 11, "fields": { "real_name": "Brett Jones", "timezone": "Atlantic/Reykjavik" } }, { "model": … -
Django admin site cannot login
I followed this this tutorial and everything worked fine, until I created a superuser and tried to enter the admin site. I used the correct username and password but cannot enter. I searched around and found old answers, saying you need to adjust the authentication_backends, e.g: AUTHENTICATION_BACKENDS = ('project.apps.account.backend.EmailAuthenticationBackend', ) But I dont have this line of code in my settings.py. This is my settings.py: """ Django settings for mysite project. Generated by 'django-admin startproject' using Django 3.1.1. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'polls.apps.PollsConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'mysite.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], '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', ], }, }, ] WSGI_APPLICATION = 'mysite.wsgi.application' # Database # … -
Django ManyToManyField showing empty list in form template?
i am using two form for update book title and lesson name too. the {{book_update}} is work fine but {{lesson_form_list}} it's getting empty list. how to use {{lesson_form_list}}as input field, when i try to use as form {{ lesson_form_list }} i am getting empty list[]` in html form.. models.py class Book(models.Model): title = models.CharField(max_length=10) created = models.DateTimeField(auto_now_add=True) lesson = models.ManyToManyField(Lesson) views.py def book_update_form(request, pk): book = get_object_or_404(Book, pk=pk) b_form = BookForm(request.POST or None, instance=book) l_form = [LessonForm(request.POST or None, prefix=str( lesson.pk), instance=lesson) for lesson in book.lesson.all()] if request.POST and b_form.is_valid() and all([lf.is_valid() for lf in l_form]): b_form.save() for lf in l_form: lesson_form = lf.save() return redirect('dashboard') context = { 'book_update': b_form, 'lesson_form_list': l_form } return render(request, 'patient/report.html', context) update_form.html <div class=" form-group"> <label for="id_lesson">Lessons</label> {{book_update}} </div> <div class=" form-group"> <label for="id_lesson">Lessons</label> {{lesson_form_list}} </div> -
DJANGO SUBSCRIPTION APPLICATION + SALEO INTEGRATION
I want to build a django subscription app that uses stripe billing. Later on, I want to integrate my saleor application with the django API. Can someone tell me the sequence of steps I need to do? I am new to this and would appreciate the help!