Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I fill up a form field from views.py in Django?
I am using a function to record the time between which the page is loaded and the user submits the data. In that form, I have created a hidden field so that the admin can see it. However, I am unable to implement my idea since I don't understand how I can submit the time to the form from views.py. If someone can suggest an easier and simpler alternative methods to achieve what I am trying to do, that would be very helpful to me as well. My code is as follows. models.py class Responses(models.Model): question1 = models.TextField() question2 = models.TextField() question3 = models.TextField() timespent1 = models.TextField() forms.py class Question1Form(forms.ModelForm): question1 = forms.CharField() timespent1 = forms.TimeField(widget=forms.HiddenInput()) class Meta: model = Responses fields = ('question1','timespent1') views.py def qone(request): if request.method =="GET": starttime = my_timer() elif request.method == "POST": form = Question1Form(request.POST) if form.is_valid(): endtime = my_timer() timespentstr = '{0} seconds'.format(endtime-starttime) #Do something to set timespent1 field = timespentstr here form = form.save() else: form = Question1Form return render(request,'question1.html',{'form':form}) -
How to fix 'str' object is not callable in django
Hi Everyone I made A Blog but when i delete post i get this error i'm using django latest version: TypeError at /post/(?P3\d+)/remove/ 'str' object is not callable' Here Is My Views.py class PostDeleteView(LoginRequiredMixin,DeleteView): success_url = reverse_lazy('post_list') model = Post Here is my app Urls.py from django.urls import path from blog import views urlpatterns = [ path('',views.PostListView.as_view(),name='post_list'), path('about/',views.AboutView.as_view(),name='about'), path('register/',views.user_register,name='user_register'), path('post/(?P<pk>\d+)',views.PostDetailView.as_view(),name='post_detail'), path('post/new/',views.CreatePostView.as_view(),name='post_new'), path('post/(?P<pk>\d+)/edit/',views.PostUpdateView.as_view(),name='post_edit'), This line i think error is path('post/(?P<pk>\d+)/remove/',views.PostDeleteView.as_view(),name='post_remove'), path('drafts/',views.PostDraftListView.as_view(),name='post_draft_list'), path('post/(?P<pk>\d+)/comment/',views.add_comment_to_post,name='add_comment_to_post'), path('comment/(?P<pk>\d+)/approve/',views.comment_approve,name='comment_approve'), path('comment/(?P<pk>\d+)/remove/',views.comment_remove,name='comment_remove'), path('post/(?P<pk>\d+)/publish/',views.post_publish,name='post_publish'), ] -
replacing django_background_task with APScheduler in Django?
Now I made code that removes temp folder after 5 seconds when users download the file with django_background_task library. I have to replace it with APScheduler library because heroku only supports APScheduler. But I have no idea how to schedule jobs that runs after 5 seconds when I call it. Here is the code. @background(schedule=5) def task_delete_zipfile(filePath): if os.path.exists(filePath): shutil.rmtree(filePath) logging.info("successfully deleted") else: logging.info("unable to delete") zipdir = condown(idx)#returns directory after creating the temp directory if os.path.exists(zipdir): with open(zipdir, 'rb') as fh: response = HttpResponse(fh.read(), content_type="multipart/form-data") response['Content-Disposition'] = 'inline; filename*=UTF-8\'\'%s' % urllib.parse.quote(os.path.basename(zipdir).encode('utf-8')) task_delete_zipfile(os.path.dirname(zipdir)) return response raise Http404 Thanks in advance! -
How to load a comment form in DetailView?
I was able to load the comments that were added through the admin page but I am not able to make a form in the DetailView itself I have tried adding a form in the detailview template but I still don't see the form in the site #views.py class MessageDetailView(DetailView): model = Message template_name = "messaging/detail.html" #queryset = Message.objects.all() def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['comments'] = Comment.objects.filter(message=self.object) return context #detail.html <form method="POST"> {% csrf_token %} <h3>Write a New Comment</h3> <div class="messagebox"> {{ form|crispy }} <button class="btn" type="submit"> Post Comment </button> </div> </form> #forms.py class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ("comment") #models.py class Comment(models.Model): message = models.ForeignKey(Message,on_delete=models.CASCADE) comment = models.TextField(max_length=50) date_posted = models.DateTimeField(default=timezone.now) def __str__(self): return "Comment on {}".format(str(self.date_posted)) The comments loaded in the site, but the form didn't load, any way to solve this problem? Please provide some code in the answer instead of just linking me to a documentary. -
How to write correct test with pytest-django?
I am getting started with pytest. I try test my ListView with predefined data, but response.context_data['object_list'] is empty. What wrong? This is my code: from http import HTTPStatus from django.test import RequestFactory from django.urls import reverse_lazy from mixer.backend.django import mixer import pytest from career.constants import THREE_FIVE_YEARS from career.constants import WITHOUT_EXPERIENCE from career.models import Employment from career.models import Schedule from career.models import Vacancy from career.views import VacancyList pytestmark = pytest.mark.django_db(transaction=True) class TestVacancyView: """Testing vacancy views.""" list_url = 'vacancy_list' list_path = reverse_lazy(list_url) factory = RequestFactory() def test_list_get(self, client): first_schedule = Schedule.objects.first() last_schedule = Schedule.objects.last() employment_first = Employment.objects.first() employment_last = Employment.objects.last() mixer.blend( Vacancy, city='New York', salary_max=30000, experience=WITHOUT_EXPERIENCE, schedule=first_schedule, employment=employment_first ) mixer.blend( Vacancy, city='London', salary_max=40000, experience=THREE_FIVE_YEARS, schedule=first_schedule, employment=employment_first ) mixer.blend( Vacancy, city='New York', salary_max=50000, experience=THREE_FIVE_YEARS, schedule=last_schedule, employment=employment_last ) request = self.factory.get(self.list_path) response = VacancyList.as_view()(request) assert response.context_data['object_list'].count() == 3 I expected 3 records in database, but the actual output is 2. -
Django - Adding a part of a string onto a new line not working correctly
In my Django project, If the user makes a mistake when signing up, then an error is sent to my template and then displayed. Some of my error messages I send to the user are a bit lengthy, and therefore I want to start a new line within the text. I attempt to add \n within my text, however a new line isn't started. Here's my code: views.py: return render(request, 'users/signup.html', {'error': 'Username field must be \n a minimum of 5 characters'}) signup.html: {% if error %} <span class="errorspansignup"> {{ error }} </span> {% endif %} The text I pass as error stays all on one line. Does anybody know what the issue is? Thank you. -
Error occured in django when i run a command `python manage.py runserver`.after i changed python version
everyone here in stackoverflow. I had successfully completed few django projects few month ago. Now, due to some reason i changed the python version. And when i try to run old django projects it throws the error like following (myDjangoEnv) E:\django_project\thirdpolehandicraft\myDjangoEnv\thirdpolehandicraft>python manage.py runserver Traceback (most recent call last): File "manage.py", line 8, in <module> from django.core.management import execute_from_command_line File "E:\django_project\thirdpolehandicraft\myDjangoEnv\lib\site-packages\django\__init__.py", line 1, in <module> from django.utils.version import get_version File "E:\django_project\thirdpolehandicraft\myDjangoEnv\lib\site-packages\django\utils\version.py", line 1, in <module> import datetime ModuleNotFoundError: No module named 'datetime' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 14, in <module> ) from exc ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? Actually when i create new project and run it works fine. But when i activate old virtualenv and try to run the server then above error occurs. Even I did python uninstall completely and installed fresh python again but did'nt work for me. Any body know how to solve this? Thanks in advance! -
PermissionError: [Errno 13] Permission denied: 'C:\\Users\\...\\AppData\\Local\\Temp\\tmp24xoaa7g'
I am having a weird problem with tests regarding testing with temporary images and compressing images in models.py and I've been stuck for about 7 hours now. There seems to be a problem with permissions: ERROR: test_has_light_images (realestate.tests.test_view_listing.RealestateListingViewTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\Users\Storm\Envs\btre\lib\site-packages\django\test\utils.py", line 373, in inner return func(*args, **kwargs) File "C:\Users\Storm\Dev\btre_project\realestate\tests\test_view_listing.py", line 72, in test_has_light_images create_listing(title='listing_sample', address='sample', realtor_num=1, city='sample', state='sample', zipcode='1234', price='555555', bedrooms='1', bathrooms='1', garage='1', sqft='123', lot_size='123', image_sample=image_sample.name) File "C:\Users\Storm\Dev\btre_project\realestate\tests\test_view_listing.py", line 37, in create_listing return Listing.objects.create(title=title, address=address, realtor=realtor, city=city, state=state, zipcode=zipcode, price=price, bedrooms=bedrooms, bathrooms=bathrooms, garage=garage, sqft=sqft, lot_size=lot_size, photo_main=image_sample, photo_1=image_sample, photo_2=image_sample, photo_3=image_sample, photo_4=image_sample, photo_5=image_sample, photo_6=image_sample) File "C:\Users\Storm\Envs\btre\lib\site-packages\django\db\models\manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\Storm\Envs\btre\lib\site-packages\django\db\models\query.py", line 422, in create obj.save(force_insert=True, using=self.db) File "C:\Users\Storm\Dev\btre_project\realestate\models.py", line 69, in save new_image = compress(self.photo_main) File "C:\Users\Storm\Dev\btre_project\realestate\models.py", line 11, in compress im = Image.open(image) File "C:\Users\Storm\Envs\btre\lib\site-packages\PIL\Image.py", line 2774, in open fp.seek(0) File "C:\Users\Storm\Envs\btre\lib\site-packages\django\core\files\utils.py", line 20, in <lambda> seek = property(lambda self: self.file.seek) File "C:\Users\Storm\Envs\btre\lib\site-packages\django\db\models\fields\files.py", line 43, in _get_file self._file = self.storage.open(self.name, 'rb') File "C:\Users\Storm\Envs\btre\lib\site-packages\django\core\files\storage.py", line 36, in open return self._open(name, mode) File "C:\Users\Storm\Envs\btre\lib\site-packages\django\core\files\storage.py", line 224, in _open return File(open(self.path(name), mode)) PermissionError: [Errno 13] Permission denied: 'C:\\Users\\Storm\\AppData\\Local\\Temp\\tmp24xoaa7g' test.py from django.test import TestCase from django.urls import reverse, resolve from django.utils import timezone … -
django 'set' object is not reversible
When I use the passed parameters, I always report an error, but If change this { % url , this error will be gone. please help me solve the problem. views.py is: def mmmm(request): return render(request, 'test3.html') def gettime(request, year, day, month): return HttpResponse("time is %s-%s-%s" % (year, month, day)) urls.py is: app_name = "four" urlpatterns = [ re_path(r'mmmm', views.mmmm, name='mmmm'), re_path(r'gettime/(?P<year>\d+)/(?P<month>\d+)/(?P<day>\d+)/$', views.gettime, name='gettime'), ] test2.html is: <a href="{% url 'mmmm' %}">mmmmm</a><br> <a href="{% url 'gettime' year=2019 month=12 day=18 %}">cmdb/userinfo/tom/tomnickname/10</a><br> this error is : Error during template rendering In template /Users/jumporange/PycharmProjects/HelloDjango/templates/test2.html, error at line 15 'set' object is not reversible 5 <title>Get student</title> 6 </head> 7 <body> 8 <ul>{% for student in students %} 9 <li>{{ student.s_name }}</li> 10 {% endfor %} 11 </ul> 12 {#<a href="/FOUR/index">mmm</a>#} 13 14 {#<a href="{% url 'mmmm' %}">mmmmm</a><br>#} 15 <a href="{% url 'gettime' year=2019 month=12 day=18 %}">cmdb/userinfo/tom/tomnickname/10</a><br> 16 </body> 17 </html> -
can retrieve data from a search feature in my django project
i don't know what exactly the isssue is but in my blood bank management when ever i search for o postive and the desired location i'll get the result but when i tried to retrieve Ab positive blood group with a particular location it says there is no particular donor to that given location even though there is a data with that given location views.py def detail(request): blood_type = request.POST['blood_group'] city = str(request.POST['city']).capitalize() for i in DonarDetail.objects.all(): i.refresh() i.save() list2 = DonarDetail.objects.all().filter( blood_group=blood_type, city=city, number_month=-1, ) | DonarDetail.objects.all().filter( blood_group=blood_type, city=city, number_month__gt=2, ) number = len(list2) print(number) if number > 0: return render(request, 'login/details.html', {'list': list2, 'number': number}) else: error = 1 return render(request, 'login/check.html', {'error': error}) models.py class DonarDetail(models.Model): Male = 'Male' Female = 'Female' choice = (('Male', 'Male'), ('Female', 'Female'), ) choice1 = (('O Positive', 'O Positive'), ('O Negative', 'O Negative'), ('A Positive', 'A Positive'), ('A Negative', 'A Negative'), ('B Positive', 'B Positive'), ('B Negative', 'B Negative'), ('AB Negative', 'AB Negative'), ('AB Positive', 'AB Positive'), ) first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20, blank=True) name = models.CharField(max_length=50, default=' ') id_no = models.CharField(max_length=20, unique=True) gender = models.CharField(max_length=20, choices=choice, default='Male') age = models.IntegerField(validators=[MinValueValidator(18)]) blood_group = models.CharField(max_length=20, choices=choice1, default='O Positive') email = models.EmailField(blank=True) … -
Password Reset issue with Django 2.2.5
I am trying to figure out an issue I'm having with what happens after submitting the password reset form supplied by django.contrib.auth.urls. When hitting the button to request the submit button an email is sent properly to the email associated with the user account, but a 505 error page is displayed. In looking at the error log the error given is: Reverse for 'password_reset_done' not found. 'password_reset_done' is not a valid view function or pattern name. In myproject/urls.py I have the following line as part of the urlspattern: path('accounts/', include('accounts.urls', namespace = 'accounts')) In accounts/urls.py I have the following lines as part of the urlspattern: path('', include('django.contrib.auth.urls')) I think the issue is with django attempting to use the equivalent of url 'password_reset_done' instead of url 'accounts:password_reset_done'. Any help in tracking this down would be appreciated. -
I have a problem to run the manage.py with runserver_plus, the error is in the sintaxis in ```from exc```
my proble is in the manage.py when i try to run the sudo python manage.py runserver_plus --cert-file i serch a similar problems, but i can solve the problem this is the code of manage.py #!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main(): os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'necesitoayuda.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': main() -
Pulling several Django models together into a single list
I have a database with four related tables: project, unit, unit_equipment, and equipment. A project can have many units; a unit can have many related equipment entries. A single unit can only belong to one project, but there is a many-to-many between equipment and unit (hence the unit_equipment bridge table in the DB). I'm using Django and trying to create a view (or a list?) that shows all 3 models on the same page, together. So it would list all projects, all units, and all equipment. Ideally, the display would be like this: Project --------- Unit ------------- Equipment Project 1 first_unit some_equipment1, some_equipment2 Project 1 second_unit more_equipment1, more_equipment2 Project 2 another_unit some_equipment1, more_equipment1 Project 2 and_another_unit some_equipment2, more_equipment2 but at this point I'd also be happy with just having a separate line for each piece of equipment, if comma-separating them is a pain. I am very new to Django, and although it seems straightforward to create a form where I can add a new project, and add related unit and equipment data (using the TabularInline class), I cannot for the life of me figure out how to bring this data together and just display it. I just want a "master … -
Checking a value of single cell on uploaded excel file on Django via openpyxl
I am currently taking an excel file as an input from Django. From the uploaded excel, I would like to check a value in one cell and decide on what to do with the entire workbook. But my syntax for load_workbook must be wrong as I am getting 'stat: path should be string, bytes, os.PathLike or integer, not UploadFileForm' What would be the simplest way to interpret the uploaded file as an excel file and check a value of the single cell? From the upload function, if self.request.method == 'POST': form = UploadFileForm(self.request.POST, self.request.FILES) if form.is_valid(): # edit workbook = load_workbook(filename=form, read_only=True) uploadable(workbook) I cannot change the part above the edit tag as it is being used by many different working functions. The snippet of the uploadable function: def uploadable(wb = None): firstws = wb[0] if firstws['X1'] == 1: return render_to_response('check/wrongfile.html') -
Server Error (500) | Django + Nginx & Gunicorn. No Nginx error log or Django debug output
Here is my settings.py: """ Django settings for real_estate_platform project. Generated by 'django-admin startproject' using Django 2.2.6. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ """ 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 = '' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'listings', 'django_cleanup', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'real_estate_platform.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', 'django.template.context_processors.media', ], }, }, ] WSGI_APPLICATION = 'real_estate_platform.wsgi.application' # Database # https://docs.djangoproject.com/en/2.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'db', 'USER': 'dbuser', 'PASSWORD': 'password', 'HOST': 'localhost', 'PORT': '' } } # 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', }, ] … -
Is it possible to fill a form in a test?
I want to test a form. It is working, but the test doesn't. One field of this form is popolated by a javascript function. I can use selenium to do so, but I don't want because it's giving problems and also I want isolate the test. So I'm calling the form in my test, then I'm creating the choices (this is what javascript should do), then I'm setting the fields values. My models.py: class Name(models.Model): name = models.CharField(_('nome'), max_length=50, default='') namelanguage = models.ForeignKey( NameLanguage, related_name='%(app_label)s_%(class)s_language', verbose_name=_('linguaggio'), on_delete=models.PROTECT) nametype = models.ForeignKey( NameType, related_name='%(app_label)s_%(class)s_tipo', verbose_name=_('tipo'), on_delete=models.PROTECT) gender = models.ForeignKey( Gender, related_name='%(app_label)s_%(class)s_gender', verbose_name=_('sesso'), on_delete=models.PROTECT, blank=True, null=True) usato = models.PositiveSmallIntegerField(_('usato'), default=0) approved = models.BooleanField(null=True, blank=True, default=False) def save(self, *args, **kwargs): self.name = format_for_save_name(self.name) to_save = check_gender_name(self) if not to_save: return else: super(Name, self).save(*args, **kwargs) def format_for_save_name(name): myname = name.lower().strip() if myname[0] not in "abcdefghijklmnopqrstuvwxyz#": myname = '#' + myname return myname My form.py: class NameForm(forms.ModelForm): class Meta: model = Name fields = ['namelanguage', 'nametype', 'gender', 'name', 'usato', 'approved'] widgets = { 'gender': forms.RadioSelect(), 'usato': forms.HiddenInput(), 'approved': forms.HiddenInput(), } My test_form.py: def test_form_validation(self): maschio = Gender.objects.create(name_en='Male', name_it='Maschio') nome = NameType.objects.create(name_en='Name', name_it='Nome') romani = NameLanguage.objects.create( name_en='Romans', name_it='Romani') romani.sintassi.add(nome) form = NameForm() form.fields['nametype'].disabled = False form.fields['nametype'].choices = … -
How to use List field in django models
I am maintaining a simple table with three columns: Course name, register and delete. Following is the screenshot of the table. Currently, when I click on register, I am changing the color of that row to dark and then changing register to unregister. template html file: Fist I get a text input i.e the course name <form class="form-inline my-2 my-lg-0" method="POST"> {% csrf_token %} <input class="form-control mr-sm-2" type="search" placeholder="Add Item" aria-label="Search" name="item"> <button class="btn btn-outline-secondary my-2 my-sm-0" type="submit">Add to List</button> </form> Then I display the table {% if all_items %} <table class="table table-bordered"> {% for things in all_items %} {% if things.completed %} <tr class="table-secondary"> <td><a href="{% url 'edit' things.id %}">{{ things.item}}</a></td> <td><center><a href="{% url 'unregister' things.id %}">unregister</a></center></td> <td><center><a href="{% url 'delete' things.id %}">Delete</a></center></td> </tr> {% else %} <tr> <td><a href="{% url 'edit' things.id %}">{{ things.item}}</a></td> <td><center><a href="{% url 'register' things.id %}">register</a></center></td> <td><center><a href="{% url 'delete' things.id %}">Delete</a></center></td> </tr> {% endif %} {% endfor %} </table> {% endif %} views.py: from django.shortcuts import render,redirect from .models import List from .forms import ListForm def Link2(request): if request.method=='POST': form=ListForm(request.POST or None) if form.is_valid(): form.save() all_items=List.objects.all return render(request, 'Link2.html', {'all_items':all_items}) else: all_items=List.objects.all return render(request, 'Link2.html', {'all_items':all_items}) def register(request,list_id): item=List.objects.get(pk=list_id) item.completed=True item.save() return redirect('Link2') … -
Django server does not run properly when launched using os.startfile()
i've created a django server and created a shortcut that navigates through the initial setup it works perfectly when i run it normally by double clicking, but not when i launch it using python i created a function in tkinter that gets invoked when the button is clicked under which: os.startfile ("C:\server.lnk") command is given. when i click the button initial the server boots up, but navigated to a page show this error: enter image description here -
Django Tempus Dominus TimePicker does not return the instance of time when updating an object
I have a model, a form and a couple of views to add a new object and to update an object. Sending the form when adding works perfectly, and when I try to update an object (using an instance and the same form) the correct input for date shows, but time shows no input and I see warnings in the console about it, can anyone help me make sense of it? I feel like I've tried everything, this is my first time trying date and time pickers. I've simplified what I mean below. model.py: from django.db import models class MyModel(models.Model): date = models.DateField() time = models.TimeField() forms.py: from django import forms from .models import MyModel from tempus_dominus.widgets import DatePicker, TimePicker class MyModelForm(forms.ModelForm): date = forms.DateField(label="Start date", input_formats=['%d/%m/%Y'], widget=DatePicker(options={'format': 'DD/MM/YYYY', }, attrs={'autocomplete': 'off'})) time = forms.TimeField(label="Time (24 hour)",input_formats=['%H:%M'], widget=TimePicker(options={'format': 'HH:mm'}, attrs={'autocomplete': 'off'})) class Meta: model = MyModel fields = ('date', 'time') views.py def create_object_view(request): """View that creates a model entry""" if request.method == 'POST': object_form = MyModelForm(request.POST) if object_form.is_valid(): object_form.save() return redirect('wherever') else: object_form = MyModelForm) return render(request, 'create_object.html', {'object_form': object_form}) def update_object_view(request, object_id): """View that updates instance of model entry""" object = get_object_or_404(MyModel, pk=object_id) if request.method == 'POST': update_object_form = … -
How can I fix User and Models issue?
I am creating a project and I have 2 issues. In models.py I have: from django.db import models from children.models import Child from django.contrib.auth.models import User class OrderLineItem(models.Model): order= models.ForeignKey("Order", null=False, on_delete=models.CASCADE, related_name="order") child = models.ForeignKey(Child, null=False, on_delete=models.CASCADE) donation = models.IntegerField(blank=False) def __str__(self): return "{0}-{1}".format( self.donation, self.child.name) class Order(models.Model): full_name = models.ForeignKey(User, blank=False, on_delete=models.CASCADE) phone_number = models.CharField(max_length=20, blank=False) country = models.CharField(max_length=40, blank=False) postcode = models.CharField(max_length=20, blank=True) town_or_city = models.CharField(max_length=40, blank=False) street_address1 = models.CharField(max_length=40, blank=False) street_address2 = models.CharField(max_length=40, blank=True) date = models.DateField() orderlineitem = models.ForeignKey(OrderLineItem, on_delete=models.CASCADE, related_name="orderlineitem") def __str__(self): return "{0}-{1}-{2}".format(self.id, self.date, self.full_name) In the html I have: {% if orders %} <h3>Your donations history: </h3> {% for order in orders %} <div class="history"> <h4>Order number: {{order.id}}</h4> <ul class="history-list"> <li scope="row">Date of your order: {{ order.date }}</li> <li scope="row">Child: {{ order.child }}</li> <li scope="row">Donation: {{ order.donation }} €</li> </ul> </div> {% endfor %} {% else %} <h3>You have not made any donations yet. </h3> {% endif %} And I get an error: Traceback: File "/usr/local/lib/python3.6/dist-packages/django/db/backends/utils.py" in execute 64. return self.cursor.execute(sql, params) File "/usr/local/lib/python3.6/dist-packages/django/db/backends/sqlite3/base.py" in execute 328. return Database.Cursor.execute(self, query, params) The above exception (NOT NULL constraint failed: checkout_order.orderlineitem_id) was the direct cause of the following exception: File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/exception.py" in inner 41. … -
Nginx - how to serve protected video on a rendered page in Django, instead of a forced download?
I need a protected video file on a page rendered by Django. The file is protected, but it's not serving an html rendered page with the <video src="..."> as I'd expect, like netflix. Instead, all I get is a jumbled mess like this image. I know the internal redirect is serving the file, therefore it shows up like that, but I need it on a rendered page with the other html like netflix does.... What am I doing wrong?? Nginx conf file: location /secret_videos/ { internal; alias /home/username/path/to/secret/videos/; } Url: path('protected_video/', views.protected_video, name='protected_video'), View: def protected_video(request): .... if request.method =='POST': if some_var == 'the_correct_value': protected_uri = '/secret_videos/secret-vid-1.mp4' response = render(request, 'template.html', {'some_var ': True, 'protected_uri': protected_uri}) response['X-Accel-Redirect'] = protected_uri return response return render(request, 'template.html', {}) Template, but it's not rendering html, only the image above: <video width="75%" height="auto" controls> <source src="{{ protected_uri }}" type="video/mp4" /> Your browser doesn't support the mp4 video format. </video> -
Link To Config File And Use That Info To Link To Another Config File In Django View
I was wondering if it was possible to link to two config files at the same time in a django view (context)? So I have my main config.py file in my main app folder and another one is stored at themes/default/config.py to store info for that theme so I want to call that configs "THEME_PATH" and use that to link to the themes config.py file to use in the template. main config.py: SITE_NAME = 'Site Title' THEME_PATH = 'themes/' SITE_THEME = 'default' themes/default/config.py: # Homepage HOMEPAGE_TITLE = 'Home' HOMEPAGE_DESCRIPION = 'Welcome to our site!' HOMEPAGE_KEYWORDS = '' # Forums FORUM_TITLE = 'Forums' FORUM_HEADER_TITLE = 'Welcome To Our Site' FORUM_HEADER_TEXT = 'Welcome to the forums a place to talk about anything.' FORUM_DESCRIPION = 'This is our forum' FORUM_KEYWORDS = '' views: from django.shortcuts import render, import app.config def forums_home_view(request): # ... context = { 'site_name': app.config.SITE_NAME, 'forum_title': app.config.THEME_PATH.SITE_THEME.config.FORUM_TITLE, 'forum_description': app.config.THEME_PATH.SITE_THEME.FORUM_DESCRIPION, 'forum_header_text': app.config.THEME_PATH.SITE_THEME.FORUM_HEADER_TEXT, 'forum_keywords': app.config.THEME_PATH.SITE_THEME.FORUM_KEYWORDS, } return render(request, f"{app.config.SITE_THEME}/forum_home.html", context) I tried doing it like app.config.THEME_PATH.SITE_THEME but that didn't work also tried a few others way and also didn't work so any help will be great -
Django: No module named 'psycopg2' when launching migrations to heroku
I am new to django and I created a website and now I am in the deployment phase, all is well run until launching migrating from the database to the server. I'll show you everything I've done since the beginning structure of my project OC_project8/ pur_beurre/ catalog/ dumps/ catalog.json ... # other classic file media/ pur_beurre/ static/ .gitignore ... # other classic file static/ templates/ users/ manage.py Procfile venv/ requirements.txt/ .gitignore/ All command was run in a virtual environement, for exemple: (venv) ~/OC_project8/pur_beurre$ sudo apt-get install python-psycopg2 I did all the necessary steps before runing the command git push heroku master (git commit, heroku create my-app ...) if you need more detail on these steps tell me. After runing the command git push heroku master I had this error: .... remote: Collecting pkg-resources==0.0.0 (from -r /tmp/build_cac68f54540915062647a425c52dc61b/requirements.txt (line 11)) remote: Could not find a version that satisfies the requirement pkg-resources==0.0.0 (from -r/tmp/build_cac68f54540915062647a425c52dc61b/requirements.txt (line 11)) (from versions: ) remote: No matching distribution found for pkg-resources==0.0.0 (from -r /tmp/build_cac68f54540915062647a425c52dc61b/requirements.txt (line 11)) remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push failed remote: Verifying deploy... remote: remote: ! Push rejected to pur-beurre-oc8. remote: To https://git.heroku.com/pur-beurre-oc8.git ! [remote rejected] master -> … -
Saving ManytoMany fields in Django with multiple forms
I am trying to do the following in 3 forms that are processed at once: 1. Save the subject line for an email (this works) 2. Save the email content. (this works) 3. Save the email title (works) and save the relationship to the subject line and to the email content (not working). I have read through every page I could which had to do with errors. I have tried it a variety of different ways, but they all haven't worked for me. View.py: def email_subject_create_view(request): if request.method == 'POST': email_subject_form = EmailSubjectForm(request.POST) email_content_form = EmailContentForm(request.POST) email_form = EmailForm(request.POST) if email_subject_form.is_valid() and email_content_form.is_valid() and email_form.is_valid() : subject = email_subject_form.save(commit=False) subject.time_created = datetime.datetime.now() contractor = Contractor.objects.get(user_id=request.user.id) subject.save() email_subject_form.save_m2m() content = email_content_form.save(commit=False) content.time_created = datetime.datetime.now() content.save() email_content_form.save_m2m() email = email_form.save(commit=False) email.time_created = datetime.datetime.now() correct_subject = EmailSubject.objects.get(pk=subject.id) # this is what I want to do. email.email_core_contents is a M2M field email.email_core_contents = subject.id email.save() context = { 'email_subject_form': EmailSubjectForm(), 'email_content_form': EmailContentForm(), 'email_form': EmailForm(), } return render(request, 'advertise/email_subject_create.html', context) I have tried: email.email_core_contents = EmailSubject.objects.get(pk=subject.id) email.email_core_contents.set(subject) email.email_core_contents.set(pk=subject.id) I have also tried it without the .save_m2m() portions of code. -
Visual Studio Code switching terminals when debugging. Code only runs successfully once with debugger
I am trying to debug Django code with Visual Studio Code on windows 10. When I run the debugger for the first time, my code compiles successfully and nothing goes wrong. If I change something in the code, and rerun the debugger I get a giant slew of commands on my Python Debug console run into the same error report I ran into before (from the first run even with new code without any user interaction on my webapp). Some notes: It seems very consistent. If I close visual studio code and rerun it-- my code runs fine... for one run. Closing the python debug console, it reruns fine on my default terminal--powershell.