Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
images in Django project only visible when img src=/media/... not with img src='127.0.0.1/media
Hi I'm following a tutorial series on youtube and I'm near the end of the first video but have run into some difficulties. https://www.youtube.com/watch?v=RG_Y7lIDXPM The code can be found here https://github.com/justdjango/django-react-boilerplate Basically the admin page allows the user to create a dummy item with an image. This image is saved with a path of the server IP and the image name. 127.0.0.1/media/image.type It successfully stores it into the media folder. But when I try to use this stored image on the client side with {item.image} it uses the server IP and image name. But on the client side for some reason it doesn't grab the image file. Instead only '/media/image.type' seems to successfully get the file. This seems like a problem because when the website goes live I would need to use a server IP for accessing and storing the image. Otherwise I'd use a regex or string trim to get rid of the IP part of the image source to get it to work. Pretty sure my media folder is set up correctly. STATIC_URL = '/static/' MEDIA_URL = '/media/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'build/static')] STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_ROOT = os.path.join(BASE_DIR, 'media') My Image call inside ProductList.js <Item.Group divided> {data.map(item … -
Passing data from React frontend to Django Backend
I have a completed react app and I have a textarea and button in it and I want the textarea text to be passed to the django backend when the button is pressed. In my folder, I have a React UI, Django project, along with a Django app inside of that project. I know I have to use the django REST framework but I dont know how to pass the text from the React UI to the backend of Django. -
Passing Sensitive Data
Teachers have access to a list of their Students classes. On this page (one page per Student) the Teachers can mark a checkbox as completed if the Student completes that class. This is done with ajax. I'm passing the current Students id by making it a value on the checkbox. This is not good as a malicious Teacher could inspect the page and change the Students id in the checkbox element (so they could be on Student 111's page and change the field in the checkbox to 112 and mark that other Students class as complete. How can I prevent them from doing this? I know I can get current users data in POST or using a token, but the Student whose checkbox is being changed isn't the current user, current user is a Teacher and he is making changes to one of his Students. The url is something like this: /website/teacher/student111/classes/. def post_form_api(request): data = {} if request.method == "POST": class_id = request.POST.get("class_id") student_id = request.POST.get("student_id") student_class_data_entry = get_object_or_404(StudentClassData, student_id=student_id, class_id=class_id) form = StudentClassDataForm(request.POST, instance=student_class_data_entry) [.. other logic .] if form.is_valid(): form.save() data = {'result' : True} if request.is_ajax(): return JsonResponse(data) else: return HttpResponseBadRequest() (value says which of the … -
Django - display OneToOneField field in other model django admin view
I have a OneToOneField between a Vehicle model and a Person model. I would like to view the assigned_person field (using its dropdown functionality) in Person's admin view. The idea is that if I view a Person, I can change the assigned_person value and have it affect Vehicle assigned_person. enter image description here enter image description here models.py: class Vehicle(models.Model): ... assigned_person = models.OneToOneField('Person', related_name='person', on_delete=models.CASCADE, blank=True, null=True) class Person(models.Model): ... -
Linking two models in Django REST framework
I am setting up a Django REST application where peopple can review restaurants. So far I have those models: class RestaurantId(models.Model): maps_id = models.CharField(max_length=140, unique=True) adress = models.CharField(max_length=240) name = models.CharField(max_length=140) class RestaurantReview(models.Model): review_author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) restaurant_id = models.ForeignKey(RestaurantId, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class StarterPics(models.Model): restaurant_review_id = models.OneToOneField(RestaurantReview, on_delete=models.CASCADE) pics_author = models.ForeignKey(User, on_delete=models.CASCADE) restaurant_id = models.ForeignKey(RestaurantId, on_delete=models.CASCADE) name_1 = models.CharField(max_length=40) picture_1 = models.ImageField() I have set up permissions as well so only the review_author can update his reviews and 'pics_author' can update his pictures. But my issue is that any User can post in StarterPics even if it's not the author of the review. What I need is my StarterPics model to be linked to the RestaurantReview model so review_author and pics_author as well as restaurant_id and restaurant_id has to match. -
How do I request my files in Django's Class Based Views?
My code : class CoderCreateView(CreateView): model = Answer fields = ['result'] context_object_name = 'answer' template_name = "coder/coder_form.html" def get_success_url(self): question = self.object.question return reverse('coder:detail', kwargs={'pk': question.id}) def form_valid(self, form): question = Question.objects.get(id=self.kwargs['qid']) form.instance.question = question form.instance.is_correct = compare.compare( solution= self.request.FILES[(question.solution)], result = self.request.FILES[(form.instance.result)]) return super().form_valid(form) My error : My question : How do I resolve this error and request the files I want to use the code above, I'm pretty sure there's something slightly wrong with my code that I'm quite not able to figure out yet. Looking for a canonical answer. -
Method Not Allowed (POST): /experience/create-review/
I'm trying to create a view that would add a review to a specific product in my Django app but I keep getting a 405 error Method Not Allowed. 2 of us tried to solve this but couldn't achieve anything.. Here's what we've been trying so far: Models.py; class Review(models.Model): user = models.ForeignKey(UserProfile) product = models.ForeignKey(Product) review = models.TextField() is_positive = models.BooleanField() timestamp = models.DateTimeField(auto_now_add=True) class Meta: unique_together = (('user', 'product'),) def __str__(self): return '{}'.format(self.review) Views.py; class ReviewCreate(LoginRequiredMixin, UserOnlyMixin, CreateView): model = Review fields = ['user', 'product', 'review', 'is_positive'] template = "product.html" def get_success_url(self): kwargs = {'slug': self.object.product.slug} url = reverse_lazy("experience", kwargs=kwargs) return url Urls.py (no duplicates found); url(r'^experience/(?P<slug>[\w-]+)/$', ProductView.as_view(), name='experience'), url(r'^experience/create-review/$', ReviewCreate.as_view(), name='add-review'), url(r'^reservation/(?P<slug>[\w-]+)/$', BookingView.as_view(), name='booking'), and in the template product.html; <form action="{% url 'add-review' %}" class="writearev-form" method="post"> {% csrf_token %} <input type="hidden" name="product" value="{{ object.pk }}"> <input type="hidden" name="user" value="{{ user.userprofile.pk }}"> <label class="control control--radio control-one"> <input value="true" id="chkTrue" type="radio" name="is_positive">Avis positif <div class="control__indicator"></div> </label> <label class="control control--radio control-two"> <input value="false" id="chkFalse" type="radio" name="is_positive">Avis négatif <div class="control__indicator"></div> </label> <textarea name="review" for="writearev-label" type="textarea" class="input-writearev" placeholder="Rédiger votre avis.."></textarea> <button type="submit" class="btn-writearev">Publier</button> </form> How can this be fixed? Please help -
Django: Replace foreign key attribute name (as well as column name) “_id” suffix with “_code” or other suffix
My question is closely related to this question, yet subtly different. Given the following Django models: class Country(models.Model): code = models.CharField(primary_key=True) class Person(models.Model): country = models.ForeignKey(Country, on_delete=models.CASCADE) Note that I have specified a custom primary key field on Country called code. The Country class should have no id field or attribute. This is working fine. And of course I want the Person class's foreign key to Country to use the code field. That is also working fine. So far so good. However, I also really want the underlying column name in the Person table to be exactly country_code. NOT country_id. So I added the db_column field argument: class Person(models.Model): country = models.ForeignKey( Country, on_delete=models.CASCADE, db_column='country_code', ) Now the column name is correctly named country_code instead of country_id. So far so good. Now. In my python code, I want to be able to access a country via a person in the normal way: person = Person.objects.get(...) country = person.country BUT, I want to be able to access the country code via a person directly like so: person = Person.objects.get(...) country_code = person.country_code And I also want to be able to create Person objects with the country_code argument, not country_id: person = … -
My label keeps on getting into my django form field, how do I fix it?
I have been following up on a django tutorial based around building an e-commerce site. I am currently working on the checkout page for the e-commerce website; I am making use of django forms but the label I attach to my form field keeps getting into the field and when you type into form field it creates this murky text that is very unpleasant. I can't just fix it and it is driving mad, please can someone help me check it out ? Sorry if my presentation is a bit off, I am not used to stackoverflow. checkout.html <div class="md-form mb-5"> {{ form.street_address }} <label for= "address" class =""><b>Address</b></label> <!-- <label for="address" class="">Address</label>--> </div> <!--address-2--> <div class="md-form mb-5"> <!-- <input type="text" id="address-2" class="form-control" placeholder="Apartment or suite">--> {{ form.apartment_address }} <label for = "address2" class =''><b>Address 2</b></la from django import forms from django_countries.fields import CountryField from django_countries.widgets import CountrySelectWidget PAYMENT_OPTIONS = ( ('S', 'Stripe'), ('P', 'PayPal'), ) class CheckoutForm(forms.Form): street_address = forms.CharField(widget=forms.TextInput(attrs={ 'placeholder': '1234 main st.', 'class': 'form-control', 'id': 'address', 'name': 'address' } )) apartment_address = forms.CharField(widget=forms.TextInput(attrs={ 'placeholder': 'Apartment or Suite', 'class': 'form-control', 'id': 'address2', 'name': 'address2' } ), required=False) country = CountryField(blank_label='(select country)').formfield(widget=CountrySelectWidget(attrs= { 'class': 'custom-select d-block w-100' })) zip … -
How to dynamically add a user type form to a user profile form in django?
I am a beginner user to django and I have created a custom user model. I am using the crispy form helper to create my forms. I have a standard user form that requires the user to select a user_type for validation. How do I bind the user_type to the user and render a new form based off the user_type selection and save/post the data. Or is there a better or simpler way to achieve the same outcome. Any help would be greatly appreciated. Thanks models.py class User(AbstractBaseUser): USER_TYPE_CHOICES = ( (User_Type1, 'is_usertype1'), (User_Type2, 'is_usertype2'), (User_Type3, 'is_usertype3'), (User_Type4, 'is_usertype4'), (User_Type5, 'is_usertype5'), (User_Type6, 'is_usertype6'), (User_Type7, 'is_usertype7'), (Superuser, 'is_superuser'), ) user = settings.AUTH_USER_MODEL email = models.EmailField(verbose_name='email',max_length=60, unique=True) username = models.CharField(max_length=30, unique=True) date_joined = models.DateTimeField(_('date joined'), auto_now_add=True, blank=False) last_login = models.DateTimeField(_('last login'), auto_now_add=True, blank=False) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_director = models.BooleanField(default=False) is_usertype1 = models.BooleanField(default=False) is_usertype2 = models.BooleanField(default=False) is_usertype3 = models.BooleanField(default=False) is_usertype4 = models.BooleanField(default=False) is_usertype5= models.BooleanField(default=False) is_usertype6 = models.BooleanField(default=False) is_usertype7 = models.BooleanField(default=False) password = models.CharField(_('password'), max_length=128) password_2 = models.CharField(_('password_2'), max_length=128) first_name = models.CharField(max_length=200, default='please enter your first name', null=True) last_name = models.CharField(max_length=200, default='please enter your last name', null=True) date_of_birth = models.DateField(null=True) user_type = models.CharField(UserType, default='User_Type1', choices=USER_TYPE_CHOICES) … -
TypeError at /login login() missing 1 required positional argument: 'User'
i am getting error "TypeError at /login login() missing 1 required positional argument: 'User'" i am new to django. trying to create a login page. this is my views.py from django.shortcuts import render,redirect from .models import profile from django.contrib.auth.models import User from django.contrib import messages from django.contrib.auth import authenticate def index(request): return render(request,'index.html',) def login(request,User): if request.method=='POST': username= request.POST.get('username') password = request.POST.get('password') user=authenticate(username=username,password=password) if user is not None: user.login(request,user) return render(request,'welcome.html',) else: messages.info(request , 'invalid credentials') return render(request,'login.html') else: return render(request,'welcome.html') this is my urls.py from django.urls import path from . import views urlpatterns=[ path('',views.index,name='index'), path('login',views.login,name='login'), path('register',views.register,name="Login now") ] -
Hosting a Django api with waitress
I am trying to host my API with waitress. I created a script (runserver) in my top-level directory with the code from waitress import serve from server.wsgi import application if __name__ == '__main__': serve(application, host ='localhost',port='8000') my wsgi.py file has the code import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'server.settings') application = get_wsgi_application() My current dilemma is in my runserver.py it says application is an unresolved reference. -
saving forms via TemplateView
I am trying to save forms via Post by TemplateView, but when def Post calls, forms are not saved. using inline formset . Book Title is saved by Author,1 author can have multiple books . Codes below are what I am using: This is the view , Posting content of Inlineformset , if it is get , shows the form , if it is post it must save the data . #view.py from django.shortcuts import render # Create your views here. from django.views.generic import TemplateView,UpdateView from django.forms import inlineformset_factory from .models import Author,Book from django.shortcuts import redirect class BookView(TemplateView): template_name ="index.html" def get(self, request, *args, **kwargs): return self.render_preview(request) def post(self,request,*args,**kwargs): return self.save_book(request) def save_book(self,request,**kwargs): BookFormSet = inlineformset_factory(Author, Book, fields=('title',),can_delete=False) author = Author.objects.get(name='John') formset = BookFormSet(instance=author) if formset.is_valid(): formset.save() return redirect('/') context = super(BookView, self).get_context_data(**kwargs) context['formset'] = formset return self.render_to_response(context) def render_preview(self, request, **kwargs): BookFormSet = inlineformset_factory(Author, Book, fields=('title',),can_delete=False) author = Author.objects.get(name='John') formset = BookFormSet(instance=author) context = super(BookView, self).get_context_data(**kwargs) context['formset'] = formset return self.render_to_response(context) #Models This is the models.py # Create your models here. from django.db import models class Author(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Book(models.Model): author = models.ForeignKey(Author, on_delete=models.CASCADE) title = models.CharField(max_length=100) def __str__(self): return self.title index.html … -
ValueError: Field 'id' expected a number but got ' '
I'm doing chained dropdown everything works but im stuck on this error. I was trying to fix it by deleting the migrations and running them again as suggested in other simmilar question but i got no result. thanks in advance the error Internal Server Error: /load-courses/ Traceback (most recent call last): File "C:\Users\Komputer\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\fields\__init__.py", line 1772, in get_prep_value return int(value) ValueError: invalid literal for int() with base 10: '' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\Komputer\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\Komputer\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\Komputer\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "H:\PULPIR\Desktop\Nowy folder (8)\testowyDrop\drop\views.py", line 17, in load_courses courses = Course.objects.filter(programming_id=programming_id).order_by('name') File "C:\Users\Komputer\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\Komputer\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\query.py", line 904, in filter return self._filter_or_exclude(False, *args, **kwargs) File "C:\Users\Komputer\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\query.py", line 923, in _filter_or_exclude clone.query.add_q(Q(*args, **kwargs)) File "C:\Users\Komputer\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\sql\query.py", line 1350, in add_q clause, _ = self._add_q(q_object, self.used_aliases) File "C:\Users\Komputer\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\sql\query.py", line 1377, in _add_q child_clause, needed_inner = self.build_filter( File "C:\Users\Komputer\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\sql\query.py", line 1311, in build_filter condition = self.build_lookup(lookups, col, value) File "C:\Users\Komputer\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\sql\query.py", line 1165, in build_lookup lookup = lookup_class(lhs, rhs) File "C:\Users\Komputer\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\lookups.py", line 22, in … -
Failing to load static files Django
I tried everything that is available from YouTube to reading the Django documentation to loading static files but still nothing I will send picture showing all that I did from your settings to even trying to inject the static files to the templates but nothing. Can you please help me resolve this Second picture below Third picture below -
DRF with Djoser - How to remove the domain from ACTIVATION_URL?
I am creating an app that is powered by DRF on the backend. I am trying to set up the ACTIVATION_URL for the djoser settings to point to my front end app which is on a separate domain. The problem is Django keeps inserting my local host domain in front of the url so I cant customize it to point to my front end. I currently have it set up to link to the backend but i want to change that. How can I change this without messing up the domain settings for my backend? My settings.py file: """ Django settings for config project. Generated by 'django-admin startproject' using Django 3.0.8. For more information on this file, see https://docs.djangoproject.com/en/3.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.0/ref/settings/ """ import os import environ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) env = environ.Env() environ.Env.read_env() # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = env("SECRET_KEY") # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ["*"] CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_METHODS = [ … -
Newlines in textarea are doubled in number when saved
I am working on a Django wiki app. The user can enter markdown text in a textarea to either create or edit an entry. Whenever this happens though, the number of newlines between text are doubled. For example if the user entered 4 newlines in the textarea, the saved markdown file will have 8 newlines. ''' # in views.py class ContentForm(forms.Form): content = forms.CharField( required=True, widget=forms.Textarea, label="Contents") def edit(request, title): if request.method == 'POST': save_entry(title, request.POST['content']) return HttpResponseRedirect(reverse('entry', args=(title,))) else: # get_entry returns markdown text for a title content = get_entry(title) form = ContentForm(request.POST or None, initial={'content': content}) return render(request, "encyclopedia/edit.html", { "title": title, "content": content, "form": form }) # in edit.html <h1>Edit {{ title }}</h1> <form action="{% url 'edit' title %}" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Save Changes"> </form> ''' In this case I used a textarea widget, but before this I had just used the textarea html tag and that was not working either. To create a new page as well, I am not using a widget and that is doing the same thing too. -
Django: Replace foreign key column name "_id" suffix with "_code" or other suffix
My question is closely related to this question, yet subtly different. Given the following Django models: class Country(models.Model): code = models.CharField(primary_key=True) class Person(models.Model): country = models.ForeignKey(Country, on_delete=models.CASCADE) Note that I have specified a custom primary key field on Country called code. The Country class should have no id field or attribute. This is working fine. And of course I want the Person class's foreign key to Country to use the code field. That is also working fine. So far so good. However, I also really want the underlying column name in the Person table to be exactly country_code. NOT country_id. I know this is non-standard. I don't care. It's my table and that's what I want. So in my python code, I should be able to access a country via a person in the normal way: person = Person.objects.get(...) country = person.country AND, I should be able to access the country code via a person directly like so: person = Person.objects.get(...) country_code = person.country_code There should be no person.country_id attribute or field. Only person.country and person.country_code. And yes, I want that field/attribute to be called exactly person.country_code, NOT person.country_id even if it holds the same value. That's the exact name … -
How can I create a hierarchical JSON from Django model?
My goal is to use d3js for a Django app to make a hierarchical tree of supervisors and employees. To do that, I understand that I need a hierarchy of JSON data (as seen in this example). My model contains data regarding employees and their supervisor: class people(models.Model): namelast = models.CharField(max_length=100, verbose_name='Last Name') namefirst = models.CharField(max_length=100, verbose_name='First Name') position = models.CharField(max_length=100) supervisor = models.ForeignKey('self', blank=True, null=True, on_delete=models.SET_NULL, verbose_name='Supervisor') def __str__(self): return "%s %s" % (self.namefirst, self.namelast) A supervisor will have multiple "children," and those children may or may not be supervisors with more "children." I've tried looping through the model objects, but haven't been able to come up with something hierarchical. The closest I've gotten is: data = {} for s in supervisors: data['name'] = str(people.objects.get(pk=s)) children = people.objects.filter(supervisor=s) cdict = {} for c in children: cdict.update({'name':str(c)}) data.update({'children':cdict}) But that isn't hierarchical, and the last line overwrites prior children. Any advice on how I can prepare a Django model like this for use with d3js? -
How to do a spatial lookup in Django without point?
I have two models house and county: class house(models.Model): lon = models.FloatField() lat = models.FloatField() class county(models.Model): geometry = MultiPolygonField() How do I get a QuerySet with all the houses in a given county? I know if I had a point instead of lat/long I could do something like: house.objects.filter(point__intersects=county_geometry) But now that I do not have a point, how do I go about it? Thank you -
My code will make the program think the user input nothing at all. How can I keep the values?
I have those input fields, and I want them to clear out once the user hits Send. The code below kind of works, as the fields clear out once the user hit Send. <form method="post"> {% csrf_token %} {{ form.as_p }} <button onClick="form.reset()" type="submit">Send</button> </form> But, my code will make the program think the user input nothing at all. How can I clear the fields, and keep the values? -
How to create a simple quiz with Django?
I am a newbie and trying to understand and develop a simple quiz. The questions have to be shown on the exact order. Also, those texts can be hardcode. No problem. This application will be used to measure how employees are growing on the company. I already had made the register, login, and logout… I never worked with this kind of form of Django. Can someone help me to a form, model, and view syntax for those simple questions? I am using Bootstrap... QUESTION 1 Text (…) [ ] YES [ ] NO QUESTION 2 Text (…) [ ] YES [ ] NO QUESTION 3 Text (…) [ ] YES [ ] NO QUESTION 4 Text (…) [ ] YES [ ] NO QUESTION 5 Text (…) [ ] YES [ ] NO QUESTION 6 Text …. USER ENTER PERCENTAGE. QUESTION 7 Text …. USER ENTER INTEGER. QUESTION 8 Text …. USER ENTER INTEGER QUESTION 9 Text (…) [ ] YES [ ] NO QUESTION 10 Text (…) [ ] YES [ ] NO QUESTION 11 Text (…) [ ] YES [ ] NO Thanks for all the support. -
Django - can't add ints records to ints in dictionaries?
This has to be my misunderstanding - I'm looking to learn here. Any help is appreciated. I'm getting a type error when trying to add integers looping over a set of Django Object Records, and I have no idea why. I've got a database full of date-stamped values. I want to sum the values of appropriate fields together to get a daily total, while acknowledging that there won't be records for each day for each product. E.g. : Product A has sales on May 11, 12, and 14 Product B has sales on May 6, 11, 14 and 19 What I want to end up with is an array of sequential sales totals that I can then graph. For this graph I don't care about the date, I want the trend. I already have that working for individual products, but am trying to make it work with total sales for collections of products. I feel like this is pretty standard stuff. My records look something like this: Data_Record: product_id | product_family | datetime | daily_sales | daily_profit Current Solution product_family_totals = {} for Data_Record in Records_From_Table: if Data_Record.product_family not in product_family_totals.keys(): product_family_total[Data_Record.product_family] = {} if Data_Record.date not in product_family_totals[Data_record.product_family]: product_family_total[Data_record.product_family][Data_Record.date] … -
Django DatePicker option
Just sharing something I found in another post that I thought would be helpful to anyone developing using django and wanting to use a datepicker for date fields. There are a lot of posts recommending different widgets. I thought this solution was clean and simple and does not require any additional settings. Simply add the code shown in your forms.py where needed. (Works with crispy forms) Thank you to Austin (https://stackoverflow.com/users/1296649/austin) It is taken from Django 1.8 & Django Crispy Forms: Is there a simple, easy way of implementing a Date Picker? "Not an answer for a crispy forms but newer browsers will put in a date picker for you as long as the input has an attribute type of date. This falls into the category of minimal development effort." date_field = forms.DateField( widget=forms.TextInput( attrs={'type': 'date'} ) ) -
Exception has occurred: ImproperlyConfigured
I have this error when try to debug the code: Exception has occurred: ImproperlyConfigured Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. File "C:\PyProjects\InstaDriver\users_app\views.py", line 2, in from django.contrib.auth.forms import UserCreationForm The error stop my code like this: enter image description here