Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
uwsgi arrange django on the server, and uwsgi load the static, but the SVG not display
I use UWSGI to proxy static resources. SVG images load successfully and return 200 but do not display. django admin django admin cosole I go directly to the SVG link and only return the SVG code. But my browser can load SVG pictures. open SVG link on browser -
Updating Form.intial does not change intial value in Django template
Goal I want to retain the query when a search result renders. Here is an example where the search bar contains stackoverflow on the results page. Failed Solutions These are minimal code examples # search_results.html <form action="/search" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Search"> </form> # views.py ... class SearchView(TemplateView): """Search view""" def get_context_data(self. **kwargs): context = super().get_context(**kwargs) user_query = self.request.GET.get('q', None) form.initial = {'user_query': user_query} return context The first time I search in the browser, the template renders as expected. If I search foo the following is rendered <form action="/search" method="post"> <input type="text" value="foo" name="search"> <input type="submit" value="Search"> </form> But searching a second time doesn't change the string in the search bar. If I search bar after searching foo, the search bar's value does NOT change to bar as expected. <form action="/search" method="post"> <input type="text" value="foo" name="search"> <input type="submit" value="Search"> </form> What am I doing wrong? Below is the form code. # forms.py from django import forms class SearchBar(forms.Form): user_query = forms.CharField() -
How to remove some unused feature in cloned django project?
I'm currently working in a deployed django project (django-rest-framework), but for now, my leader want to clone that project into a new one, the clone project just keep some feature in original, and remove all the unnecessary. So I wondering how to remove some model or part of model without blow up the project? -
Django displays form-error messages by default when visiting a url
Good day. I'm trying to override basic authentication with custom one. Whenever i visit user/login/ url i get error messages displaied. urls.py app_name = 'user' urlpatterns = [ path('user/login/', LoginView.as_view( template_name='registration/login.html', authentication_form=LoginForm), name='login'), path('user/', include(urls)), ] forms.py class LoginForm(AuthenticationForm): def __init__(self, *args, **kwargs): super(LoginForm, self).__init__(args, kwargs) username = forms.EmailField(widget=forms.TextInput( attrs={'class': 'form-control', 'placeholder': 'Email address', 'type': 'email', 'id': 'inputEmail'} ), label='') password = forms.CharField(widget=forms.PasswordInput( attrs={'class': 'form-control', 'placeholder': 'Password', 'type': 'password', 'id': 'inputPassword'} ), label='') login.html <div class="container text-center"> <h1 class="h3 mb-3 font-weight-normal">Sign-in</h1> <form action="." method="post" class="form-signin"> {{ form.as_p }} {% csrf_token %} <input type="hidden" value="{{ next }}"> <input type="submit" value="Login" class="btn btn-primary"> </form> </div> -
django version 1.8 'ForeignKey' object has no attribute
In my models.py I have 3 classes Project Finding FindingType Relationship between entities: Project can have 0 to N Finding. Each Finding has one Finding type. class Project(models.Model): completed_date = models.DateField(blank=True, null=True) .. and some other attributes class RA_Finding_type(models.Model): finding_title = models.CharField(max_length=40) finding_desc = models.TextField() remediation_desc = models.TextField() trc_control_number = models.TextField() display = models.BooleanField(blank=True) class RA_Finding(models.Model): project = models.ForeignKey(Project) if (not project.completed_date): # Error here. finding_type = models.ForeignKey(RA_Finding_type, limit_choices_to={'display': True},verbose_name='Weakness Type') else: finding_type = models.ForeignKey(RA_Finding_type, limit_choices_to={'display': False},verbose_name='Weakness Type') ... other attributes I want to populate finding_type attribute based on closed date. This is primary for legacy data. When I try to do this, I get an error - 'ForeignKey' object has no attribute. Is there a way to achieve this in Django? Appreciate all help. -
Django KeyError when starting
I accidentally pulled an old git repo of my Django build ( It's running on a Heroku dyno ) and it had overwritten my entire local build, I managed to restore it back to the latest git repo which was previously working on my local build ( but not my Heroku dyno ) and the server now won't run locally or on my live build? Error from the shell: python manage.py runserver File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/johnnie/.local/lib/python3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/home/johnnie/.local/lib/python3.7/site-packages/django/core/management/__init__.py", line 345, in execute settings.INSTALLED_APPS File "/home/johnnie/.local/lib/python3.7/site-packages/django/conf/__init__.py", line 76, in __getattr__ self._setup(name) File "/home/johnnie/.local/lib/python3.7/site-packages/django/conf/__init__.py", line 63, in _setup self._wrapped = Settings(settings_module) File "/home/johnnie/.local/lib/python3.7/site-packages/django/conf/__init__.py", line 142, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/johnnie/myproject/myproject/mysite/mysite/settings.py", line 141, in <module> del DATABASES['default']['OPTIONS']['sslmode'] KeyError: 'OPTIONS' -
How do I format my MySql table to avoid a "Incorrect string value" error?
I'm using Python 3.7, Django 2.0 and Mysql 5.7, all set up through docker containers. I'm trying to insert the following seed data into one of my tables ... - model: address.state pk: 14970 fields: name: "Xocal\u0131" code: XCI country: 266 This results in the MySql error, "Could not load address.State(pk=14750): (1366, "Incorrect string value: '\xC4\x81n' for column 'name' at row 1")" web_1 | File "/usr/local/lib/python3.7/site-packages/MySQLdb/cursors.py", line 209, in execute web_1 | res = self._query(query) web_1 | File "/usr/local/lib/python3.7/site-packages/MySQLdb/cursors.py", line 315, in _query web_1 | db.query(q) web_1 | File "/usr/local/lib/python3.7/site-packages/MySQLdb/connections.py", line 239, in query web_1 | _mysql.connection.query(self, query) web_1 | django.db.utils.OperationalError: Problem installing fixture '/app/maps/fixtures/state_data.yaml': Could not load address.State(pk=14750): (1366, "Incorrect string value: '\\xC4\\x81n' for column 'name' at row 1") Below is my table description ... +---------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | address_state | CREATE TABLE `address_state` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(165) NOT NULL, `code` varchar(3) NOT NULL, `country_id` int(11) NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `address_state_name_country_id_a46a5987_uniq` (`name`,`country_id`), KEY `address_state_country_id_0a4efd43_fk_address_country_id` (`country_id`), CONSTRAINT `address_state_country_id_0a4efd43_fk_address_country_id` FOREIGN KEY (`country_id`) REFERENCES `address_country` (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 | +---------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ 1 row in set (0.00 sec) What can I do to format my table so that I can insert my value properly? The table was … -
Django Rest Framework request header based permission
I'm building a Django app with Django Rest Framework to host it on my organisation's domain. The domain implements a custom authentication protocol. When someone accesses the domain, say to app1.domainname.com, they are redirected to the organisation's login page (login.domainname.com) and they have to log in with their staff account. After the user is authenticated, the user is redirected back to their initial destination (app1.domain.com). The information of the user is then stored in some custom header fields of the HTTP request sent to the app. E.g. GET / HTTP/2 Content-Type: User-Agent: ... ... X-Username: johndoe1 X-Firstname: John X-Lastname: Doe X-Email: johndoe@domainname.com etc. I'm trying to implement custom permission for my REST API that looks for these fields in the headers, and then authorise the user based on their user information. This is what I'm currently having: from rest_framework.permissions import BasePermission allowed = ['johndoe1', 'dicksmith2', 'username3'] class CutomPerm(BasePermission): message = "You don't have permission to access this object" def has_object_permission(self, request, view, obj): print(request.headers) username = request.headers['X-Username'] return username in allowed But when I run the server, it seems like the custom headers are passed through to the backend. For some requests they are, but ultimately the user is not … -
RecursionError when trying to save image
I am attempting to create a model with an image input that is to be resized and hashed on save. However, I appear to to have created an infinite recursive call. I am basing the code for my resize_and_hash_image() method off of this answer to a previous question of mine. Is there a way I can save the image without calling self.instance.save()? Any help is appreciated. models.py import hashlib from base64 import b16encode from functools import partial from io import BytesIO from PIL import Image from django.db import models class Person(models.Model): prefix = models.CharField(blank=True, null=True, max_length=5) first_name = models.CharField(max_length=35) last_name = models.CharField(max_length=35) suffix = models.CharField(blank=True, null=True, max_length=5) image = models.ImageField(default=None, upload_to='people/') _image_hash = models.BinaryField(blank=True, null=True, default=None, max_length=16) bio = models.TextField() phone = models.CharField(max_length=10) email = models.EmailField() def __str__(self): return self.full_name def save(self, *args, **kwargs): if self.image: self.resize_and_hash_image() super().save(*args, **kwargs) def hash_file(self, file, block_size=65536): hasher = hashlib.md5() for buf in iter(partial(file.read, block_size), b''): hasher.update(buf) return hasher.digest() def resize_and_hash_image(self): img = Image.open(self.image).convert('RGB') width, height = img.size longest, shortest = 960, 720 if (width >= height and (width > longest or height > shortest)) or (height > width and (height > longest or width > shortest)): if width > height: if (height * … -
Django creation report
I need to create a report with graphs in django with data from the database. How will it be done? I have db in mysql. I need to create a report with graphs in django with data from the database. How will it be done? -
Django NOT NULL constraint failed: product_product.price
I am learning Django, and is following this online tutorial for creating forms. https://www.youtube.com/watch?v=6oOHlcHkX2U&list=PLEsfXFp6DpzTD1BD1aWNxS2Ep06vIkaeW&index=23. Upon rendering in browser, I receive NOT NULL constraint failed: product_product.price. In my models.py I have from django.db import models # Create your models here. class Product(models.Model): title = models.CharField(max_length = 200, null = False, blank = False) description = models.TextField(null = True, blank = True) price = models.DecimalField(decimal_places=0, max_digits = 10) active = models.BooleanField(default = True) def __str__(self): return self.title In my views.py under the same app I have from django.shortcuts import render from .forms import ProductForm # Create your views here. def productCreateView(request): form = ProductForm(request.POST or None) if form.is_valid: print('form is valid now to saving') print('\n\n') form.save() context = {'form' : form} return render(request, '../templates/product_create.html', context=context) I have tried to python manage.py makemigrations python manage.py migrate when I tried to modify my price in my models.py e.g. by stating price = models.DecimalField(decimal_places=0, max_digits = 10, blank = False, null = False) Each time it says that there is nothing to migrate. For the sake of learning, can anybody tell me what I am missing? My complete error messages looks like below [09/Mar/2020 23:24:41] "GET /create HTTP/1.1" 301 0 form is valid now to … -
Concurrent.futures.Executor.map() is only running fragments of passed function
I'm trying to make a Django application using Spotify's API with Spotipy. When a user logs in, I want to create models for the User, their playlists, and the tracks in the playlists. I did so successfully with the following code: import sys import spotipy import spotipy.util as util import json from .models import User, Track, Playlist #functionality for interacting with the Spotify API through spotipy class SpotifyServices(): scope = "user-library-read user-read-recently-played" username = "ratiugo" token = util.prompt_for_user_token( username, scope, client_id="", client_secret="", redirect_uri="http://localhost:8001/radio/home") spotify = spotipy.Spotify(auth=token) #create User model and Playlist models for each of the user's playlists, and Track objects for each track connected to a playlist def create_user_playlist_and_track_models(self): current_user = User.objects.create(username=self.spotify.current_user()["display_name"]) current_user.save() # create playlist objects for each playlist for playlist in self.spotify.current_user_playlists(limit=50)["items"]: image_url = self.spotify.playlist_cover_image(playlist["id"])[0]["url"] created_playlist = Playlist.objects.create( owner=current_user, name=playlist["name"], playlist_href=playlist["id"], image_url=image_url ) created_playlist.save() #create Track models for each track in playlist just created #get playlist track objects playlist_items = self.spotify.playlist_tracks(playlist["id"])["items"] #get each track from playlist track object for item in playlist_items: #filter 'none' items to prevent crashing if item["track"] is None: continue #if the track object exists, grab the audio features of the track else: audio_features = self.spotify.audio_features(item["track"]["id"]) #filter 'none' items to prevent crashing if audio_features[0] … -
Django model DateField attribute limit choices
background: So im trying to build a "Bill" model with the attributes Name (name of payee), Amount (how much $ to pay), and PayDate (when to pay the bill). What I am stuck on: I'm having some hard time trying to limit the PayDate input from 1 (first of the month) to 31 (last day of the month (Depending on the month)) This is my code for the model: from django.db import models # Create your models here. class Bill(models.Model) : Name = models.CharField(max_length=200, editable=True, blank=False) Amount = models.DecimalField(editable=True, blank=False, decimal_places=2, max_digits=6) PayDate = models.IntegerField( blank=False, editable=True) def __str__(self): return f"{self.Name} @ ${self.Amount} every {self.PayDate} of the month" I would love to get your suggestions on how to set the PayDate attribute. -
React frontend not receiving response from Django HttpResponse after successful request
I'm working on an application with a React frontend and Django backend. The frontend request is hitting the backend (and updating the db) but a response is not being returned to the frontend. I'm new to both Django and React so I haven't been able to debug it. React Frontend var csrftoken = Cookies.get('csrftoken') let headers = { "X-CSRFToken": csrftoken, "Content-Type": "application/x-www-form-urlencoded" }; const qs = require('qs'); axios.post('/api/thing/new/', qs.stringify({thing_text: thing.thing_text}), {'headers': headers}) .then((result) => { console.log(results) }); Django Backend class ThingForm(ModelForm): class Meta: model = Thing fields = ['thing_text'] def thing_create(request): form = ThingForm(request.POST or None) if form.is_valid(): form.save() return JsonResponse({'foo':'bar'}) I've also tried returning a response with return HttpResponse(status=204) to no avail. This is resulting in an error, Uncaught (in promise) ReferenceError: results is not defined Which I interpret as nothing being returned to the frontend (though I could be wrong). Again, I know the backend is receiving the request because a record is created in the db. Is there anything I should try to debug this? -
Django, get value of the ChoiceField form
I have a form which contain a choicefield of items on my database. My question is How can I get the selected value of my choicheField? forms.py class list_data(forms.Form): message = forms.CharField(widget=forms.Textarea) def __init__(self, author, *args, **kwargs): super(list_data, self).__init__(*args, **kwargs) self.fields['List'] = forms.ChoiceField( choices=[(o.id, str(o)) for o in List.objects.filter(author=author)] ) views.py def sms(request): form2 = list_data(author=request.user) if request.method == "POST": form2 = list_data(request.POST) if form2.is_valid(): choice = form2.cleaned_data["List"] print(choice) else: return render(request, "data_list/sms.html", {"form2": form2}) return render(request, "data_list/sms.html", {"form2": form2}) When I try to press the submit button it give me this error: int() argument must be a string, a bytes-like object or a number, not 'QueryDict' So I changed the form2 = list_data(request.POST) for form2 = list_data(author=request.user) the error is gone but it print nothing else. Thanks for helping -
Django: How to retrieve in an AJAX POST request the value of two different variables?
I'm trying to send to my Django view two values from two different dropdowns but it doesn't work. Only the first dropdown value is sent to the view. Let's say I have the following view: def MyView(request): if request.method == 'POST' and request.is_ajax: result_1 = request.POST.get('d1') print(result_1) result_2 = request.POST.get('d2') print(result_2) And this is the html code: <script type="text/javascript"> function dropdownChange () { var selectedRegion = $(".toChange option:selected").val(); $.ajax({ url: '/myApp/templates/', type: 'POST', data: {'d1': selectedRegion}, } }); } $(".toChange").change(dropdownChange); </script> <select name="d1" class="toChange"> <option val="1"> 1 </option> <option val="2"> 2 </option> </select> <select name="d2"> <option val="3"> 3 </option> <option val="4"> 4 </option> </select> When the dropdown d1 faces a change, I want both d1 and d2 values to be sent to my view. The value of d1 is properly captured but d2 (so result_2) shows "[]". How can I capture the two variables? -
File Upload with Model Forms: not getting the selected file
I am trying to follow https://simpleisbetterthancomplex.com/tutorial/2016/08/01/how-to-upload-files-with-django.html however I failing to find my error: models.py: class PurchaseOrderRequest(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, db_index=True) request_object = models.CharField(max_length=80) # Should be a ForeignKey later order_summary = models.CharField(max_length=80) vendor = models.CharField(max_length=80) currency = models.CharField(max_length=40, choices=CURRENCY_CHOICES, default="USD") quote = models.FileField(upload_to='uploads/po-quotes/%Y/%m') date_updated = models.DateTimeField(auto_now=True) date_uploaded = models.DateTimeField(auto_now_add=True) def __str__(self): return self.order_summary forms.py class PurchaseOrderRequestForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.layout = Layout( 'request_object', 'order_summary', Row( Column('vendor', css_class='form_group col-md-4 mb0'), Column('currency', css_class='form_group col-md-4 mb0'), Column('quote', css_class='form_group col-md-4 mb0'), css_class='form_row' ), Submit('submit', 'Request') ) class Meta: model = PurchaseOrderRequest fields = '__all__' labels = { 'order_summary': _('Summary of ordered goods'), 'quote': _('Quotation'), } help_texts = { 'order_summary': _('Example: Construction - Kitchen - Electrical Appliances'), } widgets = { } My challenge is the quote FileField. The HTML-template looks like this: po_request.html {% extends 'base.html' %} {% load crispy_forms_tags %} {% block title %} {% endblock title %} {% block content %} <h1>Request a Purchase Order</h1> <form method="post" enctype="multipart/form-data"> {% csrf_token %} {% crispy form %} </form> {% endblock content %} My Google-Fu indicated I need to add the enctype="multipart/form-data" option for FileFields to work. views.py def createRequest(request): if request.method == 'POST': form = PurchaseOrderRequestForm(request.POST, request.FILES) … -
Test login protected page with permissions in django (pytest)
I am trying to test a view which only shows a template thus far. To access the view the user needs the permission 'projects.can_view'. I am trying to create a user with this permission in the test db using a fixture, then I am trying to log a client in with the username and password of my user in the db. I try to visit the view but I get a 302 error (redirect to login view.) I can verify that I actually pass the permissions correctly: My fixture: @pytest.fixture() def create_users_with_permissions(): User = get_user_model() u = User.objects.create( username="test", password="pass", ) permission = Permission.objects.get(name='Can view project') u.user_permissions.add(permission) u = User.objects.get(username='test') print(u.has_perm('appname.view_project')) return u I query the user again to delete the permissions cache like explained in the doc (https://docs.djangoproject.com/en/3.0/topics/auth/default/). When I print out print(u.has_perm('appname.view_project')) it returns True. Thus I assume I have a user with this specific permission created. Now I pass the fixture to my test and log pytests client-fixture in: def test_xyz( self, client, create_users_with_permissions ): client.login( username=create_users_with_permissions.username, password=create_users_with_permissions.password ) url = reverse('urlforview') response = client.get(url) assert response.status_code == 200 This fails with error code: assert 302 == 200 If I create a superuser in the db and … -
Why am I getting the pylint error: Value 'self.body' is unsubscriptable?
I am trying to get the summary method the return the first 50 characters from the body. class Blog(models.Model): # Title for the Blog title = models.CharField(max_length=255) # Blog body body = models.TextField() def __str__(self): return self.title def summary(self): return self.body[:50] # I get the error here -
Django adding form dynamically but unable to save to DB
I’m dynamically adding a form to a Django formset using empty_form with Jquery. I can add as many forms as wanted, fill them, but when I record them using button, I got in my database only empty form. What am’I missing ? Following is the template : { % csrf_token%} ……….. My Ingredients {{ myformset.management_form }} {% for form in myformset.forms %} {{ form }} {% endfor %} {{ myformset.empty_form}} $('#add_more').click(function() { debugger; var form_idx = $('#id_ingredientsdelarecette_set-TOTAL_FORMS').val(); $('#form_set').append($('#empty_form').html().replace(/__prefix__/g, form_idx)); $('#id_ingredientsdelarecette_set-TOTAL_FORMS').val(parseInt(form_idx) + 1); }); Enregistre Recette -
Python-telegram-bot issue
I have deployed a telegram bot (with Django) on Heroku with python version 3.6.9 It worked well without any issues. After months I did some changes and while trying to deploy it again I get issues. Heroku doesn't support python 3.6.9 anymore. It supports 3.6.10 So I set up venv with python 3.6.10 and I'm still getting the same issue after running the server. Short issue: from .callbackcontext import CallbackContext File "/home/usr/bot-name/venv/lib/python3.6/site-packages/telegram/ext/callbackcontext.py" , line 21, in <module> from telegram import Update ImportError: cannot import name 'Update' from 'telegram' (/home/usr/bot-name/venv/lib/python3.6/site-packages/telegram/init.py) Also I have tried python 3.7.6 (it's also supported by Heroku) but I get the same issue after running the server: _python manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/local/lib/python3.7/threading.py", line 926, in _bootstrap_inner self.run() File "/usr/local/lib/python3.7/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/home/usr/bot-name/venv/lib/python3.7/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/home/usr/bot-name/venv/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "/home/usr/bot-name/venv/lib/python3.7/site-packages/django/utils/autoreload.py", line 77, in raise_last_exception raise _exception[1] File "/home/usr/bot-name/venv/lib/python3.7/site-packages/django/core/management/init.py", line 337, in execute autoreload.check_errors(django.setup)() File "/home/usr/bot-name/venv/lib/python3.7/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/home/usr/bot-name/venv/lib/python3.7/site-packages/django/init.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/usr/bot-name/venv/lib/python3.7/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/home/usr/bot-name/venv/lib/python3.7/site-packages/django/apps/config.py", line … -
Django/Python: Calculate DateTimeField() via variables
I am new to python and can't wrap my head around a solution for my simple issue for days now. I have an Event model which should allow the user to book a timeslot, room and event type that will be shown in a timetable. class Event(models.Model): title = models.CharField(max_length=200) description = models.TextField() start_time = models.DateTimeField() end_time = models.DateTimeField() get_date = models.DateTimeField() # set via form, has year and day start_time_choices = [('1', '07:30'), ('2', '07:45'), ('3', '08:00'), ('4', '08:15'), ('5', '08:30')] timeslots = models.TimeField( choices=start_time_choices, "%H:%M", default='1', null=True) room_choices = [('1', 'Room 1'), ('2', 'Room 2'), ('3', 'Room 3'), ('4', 'Room 4'), ('5', 'Room 5')] room = models.CharField( choices=room_choices, max_length=1, default='1', null=True) event_choices = [('1', 'Event A'), ('2', 'Event B')] # A is 15min long, B is 30min long events= models.CharField( choices=event_choices, max_length=1, default='1', null=True) Now I want to calculate the start_time and end_time for this event which is used for the calendar view Where do I put the following calculation? Directly in models.py? How do I handle proper date calculation? # this is not a real code @property def date_calc(self): start_date = get_date + timeslots # Year & Day + Hour & Min if events == "Event A": … -
Split django models.py into multiple files inside folder (Django 3.0.4)
I'm trying to split the models.py into multiple files inside a folder. what is the proper way to do that ? all the methods in the internet from 8 years ago and it's not working now. -
POST method is not working when i sumbiting form in django
I created feedback form using form module in django. i wrote the code for printing form data entered by user when sumbiting form.But when i sumbiting form post not working as a result user data is not printing . I am beginner in django.I tried lots to solve this.but i couldn't .please help me if anyone know what is my wrong in code forms.py from django import forms class feedbackForm(forms.Form): Name=forms.CharField() RollNo=forms.IntegerField() Email=forms.EmailField() feedback=forms.CharField(widget=forms.Textarea) views.py from django.shortcuts import render from .import forms def feedback_view(request): form=forms.feedbackForm() if request.method=='POST': form=forms.feedbackForm(request.POST) if form.is_valid(): print('form validation success and printing feeback info') print('student name :',form.cleaned_data['Name']) print('student RollNo:',form.cleaned_data['RollNo']) print('student Email :',form.cleaned_data['Email']) print('student feedback :',form.cleaned_data['feedback']) return render(request,'testapp/feedback.html',{'form':form}) urls.py from django.conf.urls import url from django.contrib import admin from testapp import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^feed/', views.feedback_view), ] feedback.html <!DOCTYPE html> {% load staticfiles %} <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <link rel="stylesheet" href="{%static "css/demo1001.css"%}"> <title></title> </head> <body> <div class="container" align=center> <h1>ShefJaz Student 2feedbackform </h1><br> <form method="post"> {{form.as_p}} {%csrf_token%} <button type="button" class="btn btn-primary">sumbit feedback</button> </form> </div> </body> </html> -
Is a defined app_name recommended in urls.py for Django 2?
I'm trying to figure out what the best practices are around writing urls.py files in my Django app. I'm updating an old project to Django 2, and I read in the update documentation that urls.py files should be properly namespaced. A bit of googling suggests to me to define app_name in my urls.py always, so you don't have to manually add the app_name to each url endpoint. Instead you can then access it like ("app_name:url_name"). In my project I have: avatar/urls.py tests/urls.py So in this case, I am not sure how to name them, but for now I've gone with app_name = "avatar" in avatar/urls.py and app_name = "avatar-tests" in tests/urls.py. Do these both need an app_name for proper namespacing? Is it best practice to always have a defined app_name per urls.py? I'm uncertain still if this is required or even recommended. If I've understood correctly, it's just for easier/logical access of the url, not strictly required, but recommended in the sense that it's easier to follow.