Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
JavaScript doesn't work with elements from forms.py
I have a JavaScript function witch takes form's input and display an autocomplete box. The script recognizes the input but it does nothing (I've test the function with other file in witch I manually created the form, it works properly using only html and js). I can't find out the problem when I create the form using forms.py form.py ... class SearchForm(forms.ModelForm): class Meta: model = city fields =[ 'city_name', ] widgets = { 'city_name': forms.TextInput(attrs={'class': 'from_input', 'id':'ct_input'}),} template.html <form ...> <div> {{ form.city_name }} </div> </form> script.js cities = ["city1","city2"] function autocomplete(inp, arr) { var currentFocus; inp.addEventListener("input", function(e) { var a, b, i, val = this.value; closeAllLists(); if (!val) { return false;} currentFocus = -1; a = document.createElement("DIV"); a.setAttribute("id", this.id + "choices-list"); a.setAttribute("class", "choices_form"); this.parentNode.appendChild(a); for (i = 0; i < arr.length; i++) { if (arr[i].substr(0, val.length).toUpperCase() == val.toUpperCase()) { b = document.createElement("DIV"); b.innerHTML = "<strong>" + arr[i].substr(0, val.length) + "</strong>"; b.innerHTML += arr[i].substr(val.length); b.innerHTML += "<input type='hidden' value='" + arr[i] + "'>"; b.addEventListener("click", function(e) { inp.value = this.getElementsByTagName("input")[0].value; closeAllLists(); }); a.appendChild(b); } } }); inp.addEventListener("keydown", function(e) { var x = document.getElementById(this.id + "choices-list"); if (x) x = x.getElementsByTagName("div"); if (e.keyCode == 40) { currentFocus++; addActive(x); } else if … -
¿Puedo hacer que carguen mis static files en DEBUG = False, en mi proyecto django sin tener que hacerlo servidor web? ¿y de que forma?
Quiero que carguen los static files de mi proyecto en django pero no quiero pasarlo a un servidor web aún, ¿hay manera de cargar los static en DEBUG = False? -
Keeping data in the form after the search
I have got a form to filter the items on my site, but when I enter the data to filter and press search, then I got the results, but the data that I put in my form disappear. Is there a way to save the data and display it in the form after the search? views.py that handles the filtering of the data def HomeView(request): item_list = Item.objects.all() item_list = item_list.annotate( current_price=Coalesce('discount_price', 'price')) category_list = Category.objects.all() query = request.GET.get('q') if query: item_list = item_list.filter(title__icontains=query) cat = request.GET.get('cat') if cat: item_list = item_list.filter(category__pk=cat) price_from = request.GET.get('price_from') price_to = request.GET.get('price_to') if price_from: item_list = item_list.filter(current_price__gte=price_from) if price_to: item_list = item_list.filter(current_price__lte=price_to) paginator = Paginator(item_list, 10) page = request.GET.get('page') try: items = paginator.page(page) except PageNotAnInteger: items = paginator.page(1) except EmptyPage: items = paginator.page(paginator.num_pages) context = { 'items': items, 'category': category_list } return render(request, "home.html", context) form in the html template: <form method="GET" action="."> <div class="form-group col-md-4"> <label for="category">Category</label> <select id="cat" class="form-control" name="cat"> <option value="" selected>Choose...</option> <option value="" href="/home">All</option> {% for cat in category %} <option value="{{ cat.pk }}">{{ cat }}</option> {% endfor %} </select> </div> <div class="input-group"> <input class="form-control py-2 border-right-0 border" type="search" name="q" placeholder="Brand.."> <span class="input-group-append"> <div class="input-group-text bg-transparent"> <i class="fa fa-search"></i> </div> … -
get_or_create fails for unique_together for decimals
I have the following model: class LocationPoint(models.Model): latitude = models.DecimalField(max_digits=9, decimal_places=6) longitude = models.DecimalField(max_digits=9, decimal_places=6) class Meta: unique_together = ( ('latitude', 'longitude',), ) Interactor: class GetOrCreateLocationPoint(object): def exec(self, latitude: Decimal, longitude: Decimal) -> LocationPoint: point, _ = LocationPoint.objects.get_or_create( latitude=latitude, longitude=longitude, defaults={ 'latitude': latitude, 'longitude': longitude, }, ) return point And test: class GetOrCreateLocationPointTest(TestCase): # from django.test import TestCase __get_or_create_location_point: GetOrCreateLocationPoint def setUp(self) -> None: self.__get_or_create_location_point = GetOrCreateLocationPoint() def test_create_duplicate(self): point1 = self.__get_or_create_location_point.exec(Decimal(10.5), Decimal(5.01)) self.__get_or_create_location_point.exec(Decimal(13.4), Decimal(1.5343)) point3 = self.__get_or_create_location_point.exec(Decimal(10.5), Decimal(5.01)) self.assertEqual(point1.pk, point3.pk) I get an error while executing point3 = self.__get_or_create_location_point.exec(Decimal(10.5), Decimal(5.01)): django.db.utils.IntegrityError: duplicate key value violates unique constraint "geo_locationpoint_latitude_longitude_08fb2a82_uniq" DETAIL: Key (latitude, longitude)=(10.500000, 5.010000) already exists. However, if in debugger I see that self.model.DoesNotExist is thrown in get_or_create. What's wrong? Django 3.0.3, PostgreSQL 12. -
Django {{ form.as_p }} not rendering
I'm trying to utilize Django forms.ModelForm function. However, I can not get it to render in the browser (Firefox and Chrome tested). In both browser inspection of code, the table\form does not show and there is no error coming from Django at all. The only thing that shows from the html file is the "Save button" Is there something I am missing here? In Models.py from django.db import models class Product_sell_create(models.Model): product_product_sell = models.CharField(max_length=120) product_price_sell = models.DecimalField(decimal_places=2, max_digits=500) product_volume_sell = models.DecimalField(decimal_places=2, max_digits=500) product_location_sell = models.CharField(max_length=120) product_description_sell = models.TextField(blank=False, null=False) Forms.py from django import forms from .models import Product_sell_create class ProductName(forms.ModelForm): class Meta: model = Product_sell_create fields = [ 'product_product_sell', 'product_volume_sell', 'product_price_sell', 'product_location_sell', 'product_description_sell' ] Views.py from django.shortcuts import render from .forms import ProductName def products_create_view(request): form = ProductName(request.POST or None) if form.is_valid(): form.save() form = ProductName() context = { 'form': form } return render(request, "sell.html", context) sell.html {% include 'navbar.html' %} <h1> Upper test</h1> <form> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Save" /> </form> <h1> TEST </h1> {% block content %} {% endblock %} -
I'm unable to access Django Admin site
I'm unable to login to the Django Admin site. Below are the excerpts from the error for your kind reference: Environment: Request Method: GET Request URL: http://127.0.0.1:8000/admin/login/?next=/admin/ Django Version: 3.0.3 Python Version: 3.8.0 Installed Applications: [. . . 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.sites', . . . ] Exception Type: DoesNotExist at /admin/login/ Exception Value: Site matching query does not exist. I did try the steps listed below: $> python manage.py shell >>> from django.contrib.sites.models import Site >>> site = Site() >>> site.domain = 'example.com' >>> site.name = 'example.com' >>> site.save() It didn't help, got the following error: . . sqlite3.IntegrityError: UNIQUE constraint failed: django_site.domain . . django.db.utils.IntegrityError: UNIQUE constraint failed: django_site.domain . . I would be really thankful if anyone could please help me fix this issue. -
How many users can Sqlite can handle , Django
I have a Django application, which I have hosted on pythonanywhere. For the database, I have used SQLite(default). So I want to know how many users my applications can handle? And what if two user register form or make post at same time, will my application will crash? -
How can I, using django, successfully send json data to a postgres database after receiving this data from an API call?
I am fairly new to django, I have recently built an app that makes API calls. home -> this view asks user for the url. User gives url and clicks submit, on submit sends this url to new view and handles call in "request" request -> receives url, process' call and brings back json data and prints data on screen. As of now this data just gets printed but is not saved in any way. During the printing of the data I need it to send the data to a postgres db so I can refer to it later. The table is built and is connected to django framework and can accept data. What functions or commands, using python and django's framework can make this successful? I know this is a very broad statement I am new to using stackoverflow and do not know what is required of me. Thanks in advance -
CSRF Token Fails When Attempting To Serve Django App On A Subdomain
I am successfully configured two Django apps on these domains respectively: http://omerselcuk.engineer http://visions.omerselcuk.engineer They both work well on GET requests, but while the first (main domain) works with POST requests, the second (subdomain) does not. I can verify I have included {% csrf_token %} correctly, because I cannot even log in to admin panel. (Admin panel is accessible but not loginable.) They both accessible publicly and second Django app's DEBUG is on for you to test yourself if you want. To clarify, when I serve second one on the main domain but in a different port, it works just as expected. -
Why is my djang-carrot queue always closing?
I use django-carrot with rabbitmq and have a task I schedule to run once every day. However, every so often, it just stops working, does not execute the task and I need to restart the daemon and then suddenly it works again. The error log is simply: default-consumer-5 2020-01-30 16:45:17,104 INFO:: Channel opened default-consumer-5 2020-01-30 16:45:17,104 INFO:: Exchange declared default-consumer-5 2020-01-30 16:45:17,104 INFO:: Queue bound default-consumer-5 2020-01-30 16:45:17,104 INFO:: Starting consumer default-consumer-5 MainThread 2020-01-30 16:47:44,548 INFO:: Stopping MainThread 2020-01-30 16:47:44,548 WARNING:: Shutdown received. Cancelling the channel MainThread 2020-01-30 16:47:44,553 INFO:: Closing the channel Has anyone else had this problem? If so, what is happening and how can I solve it? -
How to create user base on data from form?
forms.py ''' class AddUserForm(forms.Form): username = forms.CharField(label='Login', min_length=1) password = forms.CharField(label='Password', widget=forms.PasswordInput) repeat_password = forms.CharField(label='Repeat password', widget=forms.PasswordInput) name = forms.CharField(label="First name", min_length=1, validators=[check_first_upper_letter_validator]) surname = forms.CharField(label="Last name",validators=[check_first_upper_letter_validator]) email = forms.CharField(validators=[EmailValidator()]) ''' views.py ''' class AddUserView(View): def get(self, request): form = AddUserForm() return render(request, 'exercises/form.html', {'form': form}) def post(self, request): form = AddUserForm(request.POST) if form.is_valid(): user = User.objects.create_user(username=...., email=....., password=....) user.save() return HttpResponse("OK") else: return render(request, 'exercises/form.html', {'form': form}) ''' How to get data from form for username, email etc.? -
Django user-specific variable not updating in backend
I have a set a pre-existing teams that the user can join [team1, team2, team3] at /jointeam, and that will show up on /home. My issue is that the variable 'user_team' from Profile stays 'None', even after the user successfully joins a team. In other words, if I enter 'team1' on /jointeam , I'd like it to assign it to user.profile.user_group Thanks in advance, appreciate your input! Here is my code: Models.py #used to create a team class TeamCreation(models.Model): team_name = models.CharField(max_length=100, default=None, unique=True) [...] def __str__(self): return self.team_name #user-specific class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) user_team = models.CharField(max_length=30, null=True) [...] def __str__(self): return f'{self.user.username} Profile' def save(self, *args, **kwargs): super(Profile, self).save(*args, **kwargs) #model to join a team class Join(models.Model): team_name = models.CharField(max_length=100, default=None, unique=False) def __str__(self): return self.team_name Forms.py class UserUpdateForm(forms.ModelForm): email = forms.EmailField() class Meta: model = User fields = ['username','email'] class TeamCreationForm(forms.ModelForm): class Meta: model = TeamCreation fields=['team_name'] class JoinForm(forms.ModelForm): class Meta: model = Join fields=['team_name'] views.py - users [...] @login_required def join_team(request): form_class = JoinForm form_join = form_class(request.POST or None) user = request.user if request.method=='POST': if form_join.is_valid(): newJoin = form_join.save(commit=False) if not TeamCreation.objects.filter(team_name=newJoin.team_name).exists(): print("nope") return redirect('dashboard') messages.error("Team doesn't exist or incorrect key") else: print("exist") group_name=newJoin.team_name user.profile.user_team=group_name … -
How to access request.user from Form in Django
I want to create a select box form. I'm planning to take the user values of ManyToManyField and make it a select box. But I don't know how to access the value of request.user in the form. How can I access request.user? class AddForm(forms.Form): cp_list = MyModel.objects.filter(cp_list__in=str(request.user.id)) # for c in cp_list: # c.code code = forms.CharField( # widget=forms.Select ... ) -
Difference between using slug_url_kwargs and pk_url_kwargs for get_object()
Difference between using slug_url_kwargs and pk_url_kwargs for get_object() When would i use one over the other? from django.urls import path from books.views import AuthorDetailView urlpatterns = [ #... path('authors/<int:param>/', AuthorDetailView.as_view(), name='author-detail'), ] For the above example, would pk_url_kwargs = 'param' be sufficient? When would i use the slug? -
Python DRF, DETAIL: Key (" ")=(1) is duplicated Error
I'm trying to run this code in django shell: >>> from TwoLocationsTrian.models import PostGDT1AndUAV >>> from TwoLocationsTrian.serializers import PostGDT1AndUAVSerializer >>> serializer = PostGDT1AndUAVSerializer() >>> print(repr(serializer)) which gave me this error: Traceback (most recent call last): File "<console>", line 1, in <module> File "/home/yovel/PycharmProjects/trialdjango/triangulation/env/lib/python3.6/site-packages/rest_framework/serializers.py", line 537, in __repr__ return representation.serializer_repr(self, indent=1) File "/home/yovel/PycharmProjects/trialdjango/triangulation/env/lib/python3.6/site-packages/rest_framework/utils/representation.py", line 77, in serializer_repr fields = serializer.fields File "/home/yovel/PycharmProjects/trialdjango/triangulation/env/lib/python3.6/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/yovel/PycharmProjects/trialdjango/triangulation/env/lib/python3.6/site-packages/rest_framework/serializers.py", line 363, in fields for key, value in self.get_fields().items(): File "/home/yovel/PycharmProjects/trialdjango/triangulation/env/lib/python3.6/site-packages/rest_framework/serializers.py", line 1063, in get_fields source, info, model, depth File "/home/yovel/PycharmProjects/trialdjango/triangulation/env/lib/python3.6/site-packages/rest_framework/serializers.py", line 1208, in build_field return self.build_unknown_field(field_name, model_class) File "/home/yovel/PycharmProjects/trialdjango/triangulation/env/lib/python3.6/site-packages/rest_framework/serializers.py", line 1325, in build_unknown_field (field_name, model_class.__name__) django.core.exceptions.ImproperlyConfigured: Field name `latitude_gdt` is not valid for model `PostGDT1AndUAV`. So, I tried to change the fields in the model: # The updated model. from django.db import models class PostGDT1AndUAV(models.Model): """ POST user's GDT1 and UAV locations. """ latitude_gdt = models.FloatField(verbose_name='LatitudeGDT1', unique=False, max_length=255, blank=False, help_text="Enter the location's Latitude, first when extracting from Google Maps.", default=0) longitude_gdt = models.FloatField(verbose_name='LongitudeOfGDT1', unique=False, max_length=255, blank=False, help_text="Enter the location's Longitude, second when extracting from Google " "Maps.", default=0) latitude_uav = models.FloatField(verbose_name='LatitudeOfUAV', unique=False, max_length=255, blank=False, help_text="Enter the location's Longitude, second when extracting from Google " "Maps.", default=0) longitude_uav … -
Error when searching for title and price at the same time
I have got a filter form, where I can filter the content by category, title and the price. I am able to search the items by the category and price or category and title at the same time, but I am getting an error when I am trying to filter by using price and the title. Here's the error, that I am getting after filtering by price and the title: FieldError at / Cannot resolve keyword 'current_price' into field. Choices are: category, description, discount_price, id, image, label, orderitem, price, slug, title views.py def HomeView(request): item_list = Item.objects.all() item_list = item_list.annotate(current_price=Coalesce('discount_price', 'price')) category_list = Category.objects.all() query = request.GET.get('q') if query: item_list = Item.objects.filter(title__icontains=query) cat = request.GET.get('cat') if cat: item_list = item_list.filter(category__pk=cat) price_from = request.GET.get('price_from') price_to = request.GET.get('price_to') if price_from: item_list = item_list.filter(current_price__gte=price_from) if price_to: item_list = item_list.filter(current_price__lte=price_to) paginator = Paginator(item_list, 10) page = request.GET.get('page') try: items = paginator.page(page) except PageNotAnInteger: items = paginator.page(1) except EmptyPage: items = paginator.page(paginator.num_pages) context = { 'items': items, 'category': category_list } return render(request, "home.html", context) html: <form method="GET" action="."> <div class="form-group col-md-4"> <label for="category">Category</label> <select id="cat" class="form-control" name="cat"> <option value="" selected>Choose...</option> <option value="" href="/home">All</option> {% for cat in category %} <option value="{{ cat.pk }}">{{ cat }}</option> … -
Como usar/gerenciar vários bancos de dados com o Django Rest
Estou usando um banco de dados local do MongoDB Compass, mas pode ser qualquer banco de dados, minhas settings.py contem essas informações para configurar o banco de dados: DATABASE_ROUTERS = ['manager.router.DatabaseAppsRouter'] DATABASE_APPS_MAPPING = {'banco1': 'DB1', 'banco2':'DB2', 'banco2':'DB3' } DATABASES = { 'default': {}, 'DB1': { 'NAME': 'DB1', 'ENGINE': 'djongo', }, 'DB2': { 'NAME': 'DB1', 'ENGINE': 'djongo', }, 'DB3': { 'NAME': 'DB1', 'ENGINE': 'djongo', }, } Meu models.py está assim: nome1 = models.CharField('TAG', max_length=100,blank=True) texto1 = models.TextField('Ordem de Manutenção', blank=True) data1 = models.DateField('Data de teste', default=datetime.date.today, blank=True) class Meta: app_label = 'banco1' def __unicode__(self): return self.nome1 class Exemplo2(models.Model): nome2 = models.CharField('TAG', max_length=100,blank=True) texto2 = models.TextField('Ordem de Manutenção', blank=True) data2 = models.DateField('Data de teste', default=datetime.date.today, blank=True) class Meta: app_label = 'banco2' def __unicode__(self): return self.nome2 class Exemplo3(models.Model): nome3 = models.CharField('TAG', max_length=100,blank=True) texto3 = models.TextField('Ordem de Manutenção', blank=True) data3 = models.DateField('Data de teste', default=datetime.date.today, blank=True) class Meta: app_label = 'banco3' def __unicode__(self): return self.nome3 Gostaria de utilizar essas diferentes informações destes diferentes banco de dados, em um unico endpoint. Não sei como eu poderia configurar minha views.py, mas imagino que deve ser algo do tipo: from rest_framework.response import Response from .models import * from .serializers import * class Varios_exemplosview(generics.ListAPIView): serializer_class = Exemplo1Serializer queryset … -
Calculate some value based on one of the django model and update 700k objects at once
In my django app I have a model: class Entry(BaseModel): event_name = models.CharField(_('Event name'), max_length=256, null=True, blank=True) slug = models.SlugField(null=True, blank=True, max_length=512) def save(self, *args, **kwargs): if not self.slug: self.slug = self.get_slug() super().save(*args, **kwargs) def get_slug(self): add = 1 slug = None if not self.slug and self.event_name: init_slug = slugify.slugify(self.event_name) slug_available = Entry.objects.filter(slug=init_slug).count() == 0 if slug_available: slug = init_slug else: while not slug_available: check_slug = '{}-{}'.format(init_slug, add) slug_available = Entry.objects.filter(slug=check_slug).count() == 0 if slug_available: slug = check_slug else: add += 1 return slug def make_slug(self): if not self.slug: slug = self.get_slug() self.slug = slug self.save() slug field is empty by default, and now I want to update 700k+ rows with empty slug with new value. I was doing it by querying the database: qs = Entry.objects.filter(slug__isnull=True) and then I was updating items in loop one by one: for entry in qs: entry.make_slug() but I am looking for more efficient way to do it. Do you know any simple solution? -
Angular and Django: SecurityError: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported
I am working with Angular and Django. In angular I am generating reports with jspdf and html2canvas, for this I am loading images stored in Django and at the moment of wanting to generate the pdf I generate the error mentioned in the title. In Django I have added corsheaders and given the permissions to be able to access from Angular: enter image description here The Angular function to generate the pdf: enter image description here Reviewing pages suggested adding the crossOrigin = "anonymous" but this has not worked for me -
Django user logs for tracking user actions on a website
I am currently working on a django web app and there are around 4 sub web pages with different functionalities on each page. Every user who uses the application has to login via Gmail. so, all the users data is present. Now, how can i actually track all the actions of user actions, for example - When a user visits a sub webpage and click on a link (or) widget (or) button click (or) filtering etc..? -
how to fix [WinError 2] The system cannot find the file specified in django
I ma trying to convert html page to pdf file but it dont work properly and show the error fileNotFound error My setting is: STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static_files')] STATIC_ROOT = os.path.join(BASE_DIR, 'static', 'statics') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'static', 'medias') WKHTMLTOPDF_CMD_OPTIONS = { 'quiet': True, } if os.name != 'nt': WKHTMLTOPDF_CMD = '/usr/local/bin/wkhtmltopdf' else: WKHTMLTOPDF_DEBUG = True **My view is: ** class MyPDFView(View): config = pdfkit.configuration(wkhtmltopdf='C:/Program Files/wkhtmltopdf/bin/wkhtmltopdf.exe') template=get_template('employee/addcon.html') # the template def get(self, request): data = {"form":contractForm()} response = PDFTemplateResponse(request=request, template=self.template, filename="hello.pdf", context= data, show_content_in_browser=False, cmd_options={'margin-top': 10, "zoom":1, "viewport-size" :"1366 x 513", 'javascript-delay':1000, 'footer-center' :'[page]/[topage]', "no-stop-slow-scripts":True}, ) return response and My Url is: urlpatterns = [ path('pdf/', views.MyPDFView.as_view(), name='pdf'), ] and It shows the error: [WinError 2] The system cannot find the file specified -
send django channels 2 messages to an individual user who might have more than one browser tab or device connected
I want to send Channels2 messages to an individual user who might have more than one browser tab or device connected. How can I do that. In documents it is said that "group_send" structure can be used. how can i implement that? Is there a sample code for this? Best Regards. Levent -
Built in django loggers dont work behind gunicorn
I'm running a django app behind gunicorn and I have a logging configuration in my settings.py. For some reason all django-related logs (logs that automatically logged by django's built in logger) are not logged anymore now that I'm using gunicorn. Only explicit calls to logging.info() in my code work. What do I need to change so that django's loggers also work? This is my logging config: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'standard': { 'format': '[%(asctime)s] {%(module)s} [%(levelname)s] - %(message)s', 'datefmt': '%d-%m-%Y %H:%M:%S' }, }, 'handlers': { 'default': { 'level': 'INFO', 'class': 'logging.handlers.RotatingFileHandler', 'filename': 'logs/info.log', 'maxBytes': 1024*1024*5, # 5 MB 'backupCount': 5, 'formatter': 'standard', }, 'console': { 'level': 'INFO', 'class': 'logging.StreamHandler', 'formatter': 'standard', }, 'loki': { 'level': 'INFO', 'class': 'logging_loki.LokiHandler', 'url': f'http://{LOKI_HOST}:3100/loki/api/v1/push', 'tags': {'app': 'django', 'env': ENV}, 'version': '1', } }, 'loggers': { '': { 'handlers': ['default', 'console', 'loki'], 'level': 'INFO', 'propagate': True, }, 'django': { 'handlers': ['default', 'debug', 'console', 'loki'], 'level': 'INFO', 'propagate': False } } } -
Django send data to Database: NOT NULL constraint failed: sms_post.author_id
I am new to django, I migrated my models, the database is working fine, i can see the data that I added by the manage.py shell. But I cant add Data from my webApp. When I wrote text on the fields and press the submit button it gave me this error NOT NULL constraint failed: sms_post.author_id Thanks for helping.. models.py files from django.db import models from django.contrib.auth.models import User THE_GENDER = [ ("Monsieur", "Monsieur"), ("Madame", "Madame") ] class Post(models.Model): name = models.CharField(max_length=100) email = models.CharField(max_length=100) gender = models.CharField(max_length=8, choices=THE_GENDER) number = models.CharField(max_length=100) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.name forms.py files from django import forms from .models import Post from crispy_forms.helper import FormHelper class post_form(forms.ModelForm): def __init__(self, *args, **kwargs): super(post_form, self).__init__(*args, **kwargs) self.helper = FormHelper(self) class Meta: model = Post fields = ["name", "email", "gender", "number"] views.py files from django.shortcuts import render from django.http import HttpResponse from .forms import post_form from django.contrib.auth.decorators import login_required @login_required def home(request): form = post_form(request.POST or None) if form.is_valid(): form.save() context = { "form": form } return render(request, "sms/home.html", context) -
why nginX server error (500) for django application?
this is the my settings.py file import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 't8%5^$plkjtbt6bm3zngoh*5-8(e#xb_sw)9kd&!_=67)#49mk' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'app1.apps.App1Config', ] 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 = 'main_jntu.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, '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', ], }, }, ] WSGI_APPLICATION = 'main_jntu.wsgi.application' # Database # https://docs.djangoproject.com/en/2.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/2.2/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.2/howto/static-files/ STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static/') this is my gunicorn.conf 2020-02-12 16:59:53 +0000] …