Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django recurrent model lookup
I have a recurrent Category model (each category could have a parent Category), I also have Product model with ForeignKey to "core category" as below. Is there any possibility to query all Products within top level categories (not core)? For example, my Categories Tree is: ---Sales ---Crm (core) ---Marketing Automation (core) ---AI ---BOTS (core) ---NLP (core) I want to query all product in "Sales" or "AI" Models: class Category(models.Model): name = models.CharField(max_length=255) link = models.URLField(max_length=255, null=True, blank=True) core = models.BooleanField() main = models.BooleanField() parent = models.ForeignKey('self', on_delete=models.SET_NULL, null=True, default=None) def __str__(self): return self.name class Product(models.Model): name = models.CharField(max_length=255) link = models.URLField(max_length=255, null=True, blank=True) category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True, default=None) def __str__(self): return self.name Thanks for your help! -
Django photologue not displaying template
I've been trying to get photologue working, following the tutorial in the documentation here, but run into a problem when it tries to load the template. I have added the apps needed to my INSTALLED_APPS in settings.py and added the line to urls.py as per the documentation. When I try to access /photologue it redirects to /photologue/gallery which is fine, but then gives a TemplateDoesNotExist error. The template it is unable to find is base.html - I have seen a lot of Django apps use templates that start with a line {% extends "base.html" %}, and it always results in an error saying base.html cannot be found. I don't have a views.py or anything I can check. Photologue is meant to come installed with it's own templates, and somewhat work out of the box, so I'm not sure what is causing the error here. Python version is 3.6.6 I'm not sure what other information to include to help troubleshoot this. -
Put request 403 error django restframework
I am creating a web application with react-js using redux and back-end with python django with django rest framework. for authentication I am using JWT. The problem I am facing is when sending request from front-end getting error as 403. I have checked the backend side all the configuration are set but still getting this error. Please check the below code. Model: class StatusQuerySet(models.QuerySet): pass class StatusManager(models.Manager): def get_queryset(self): return StatusQuerySet(self.model,using=self._db) class Apptype(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) appType = models.CharField(max_length=50) objects = StatusManager() def __str__(self): return self.appType Serializer: class AppTypeSeriializer(serializers.ModelSerializer): class Meta: model = Apptype fields = [ 'user', 'id', 'appType' ] read_only_fields = ['user','id'] views class AppTypeStatusAPIDetailView( mixins.UpdateModelMixin, mixins.DestroyModelMixin, generics.RetrieveAPIView): lookup_field = 'id' permission_classes = [permissions.IsAuthenticatedOrReadOnly] serializer_class = AppTypeSeriializer queryset = Apptype.objects.all() def put(self,request, *args, **kwargs): print("Value of = ",request.data.get("appType")) return self.update(request, *args, **kwargs) def patch(self,request, *args, **kwargs): return self.update(request, *args, **kwargs) def delete(self,request, *args, **kwargs): return self.destroy(request, *args, **kwargs) URL urlpatterns = [ url(r'^appType/$',AppTypeStatusView.as_view()), url(r'^appType/(?P<id>\d+)/$',AppTypeStatusAPIDetailView.as_view()), ] Permissions REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.SessionAuthentication', 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ) } JWT_AUTH = { 'JWT_ENCODE_HANDLER': 'rest_framework_jwt.utils.jwt_encode_handler', 'JWT_DECODE_HANDLER': 'rest_framework_jwt.utils.jwt_decode_handler', 'JWT_PAYLOAD_HANDLER': 'rest_framework_jwt.utils.jwt_payload_handler', 'JWT_PAYLOAD_GET_USER_ID_HANDLER': 'rest_framework_jwt.utils.jwt_get_user_id_from_payload_handler', 'JWT_RESPONSE_PAYLOAD_HANDLER': 'rest_framework_jwt.utils.jwt_response_payload_handler', 'JWT_ALLOW_REFRESH': True, 'JWT_REFRESH_EXPIRATION_DELTA': datetime.timedelta(days=7), 'JWT_AUTH_HEADER_PREFIX': 'JWT', 'JWT_AUTH_COOKIE': None, } Front-end code when action triggers. export … -
Django Custom models.Manager using Foreign Related table columns
I want the custom query manager function to be executed based on percentage rate provided by Client and return rate based on currency column in foreign Rate model. What will be the best way accessing foreign Rate model column currency values only referenced in Client Model? models.py: class Company(models.Model): name = ... def __str__(self): return self.name class Rate(models.Model): company = models.ForeignKey(Company) currency = ... name = ... def __str__(self): return self.name + " " + self.currency class ClientManager(models.Manager): def res_currency(self, percentage): """ Returns a QuerySet of modified rates annotated with their rates from the given percentage. This can then be filtered. Usage: Client.objects.res_currency(percentage).filter(rate__lt=1000).count() """ currency = Client.objects.select_related('base_rate').values('base_rate__currency') Expression = percentage * F(currency) return self.get_queryset()\ .annotate(rate=Expression) class Client(models.Model): name = ... company = models.ForeignKey(Company) base_rate = models.ForeignKey(Rate) objects = ClientManager() def __str__(self): return self.name -
Nested foreign key serializer in django not working
Part of models.py: class FoodCuisine(models.Model): cuisine = models.CharField(max_length=64) def __str__(self): return self.cuisine class CuisineTypes(models.Model): cuisine_types = models.CharField(max_length=64) cuisine = models.ForeignKey(FoodCuisine, on_delete=models.CASCADE) def __str__(self): return self.cuisine_types class Meta: ordering = ('cuisine_types',) class Food(models.Model): name = models.CharField(max_length=192) veg = models.BooleanField(default=0) cuisine_type = models.ForeignKey(CuisineTypes, on_delete=models.CASCADE) def __str__(self): return self.name def _cuisine(self): return self.cuisine_type.cuisine serializers.py: class FoodSerializer(serializers.ModelSerializer): class Meta: model = Food fields = ('name', 'veg') class CuisineTypesSerializer(serializers.ModelSerializer): foods = FoodSerializer(many=True, read_only=True) class Meta: model = CuisineTypes fields = ('cuisine_types', 'foods') class FoodCuisineSerializer(serializers.ModelSerializer): cuisine_type = CuisineTypesSerializer(many=True, read_only=True) class Meta: model = FoodCuisine fields = ('cuisine', 'cuisine_type') I want the FoodCuisineSerializer to return a nested list which will have all the food items categorized by their respective cuisine types and their cuisines. The categorization is straight forward, having a list of cuisines in the first level, cuisine types in the second and food items in the third level. Problem is that FoodCuisineSerializer only returns the first level only i.e. only the list of cuisines are shown. But I want the full nested list of food items as given in the previous paragraph. -
Custom throttling problems
i have: class Phone(models.Model): code = models.CharField(max_length=5) verification = models.UUIDField(default=uuid.uuid4, unique=True) In my viewset I must limit the number of requests to my endpoint from device by his verification. class MyViewSet(viewsets.GenericViewSet): permission_classes = (permissions.AllowAny,) throttle_classes = (UserPhoneThrottle,) serializer_class_map = { ..., 'verify': serializers.VerifyCodeSerializer, } I try to write my custom throttle: class UserPhoneThrottle(throttling.SimpleRateThrottle): def get_cache_key(self, request, view): verification_id = request.data.get('verification_id') if not verification_id: return None else: return self.cache_format % { 'scope': self.scope, 'ident': verification_id } In my settings: REST_FRAMEWORK = { 'DEFAULT_THROTTLE_CLASSES': ( 'app.throttling.UserPhoneThrottle', ), 'DEFAULT_THROTTLE_RATES': { ...? } } I ask to help or assist correctly to finish the given logic and to prompt what is this an error: django.core.exceptions.ImproperlyConfigured: You must set either .scope or .rate for 'UserPhoneThrottle' throttle I will be very grateful for the help. Thank you!) -
How do you validate a formset with a dynamically updating Choicefield?
I am using formset_factory to manage a couple identical forms on my page. In each form, there is a pair of chained dropdowns. DropdownA has an onchange event that request options for dropdownB (AJAX). This all works fine but when I go to submit my forms via a POST request, they all fail the forms.is_valid() check. Printing the errors of the submitted formset reveals why: [{'DropdownB ': ['Select a valid choice. Like is not one of the available choices.']}, {'DropdownB ': ['Select a valid choice. < is not one of the available choices.']}] There are two errors, one for each form. They are both complaining that the choice sent for DropdownB is not one of the available ('Like' and '<' respectfully). Now, because I want to only populate DropdownB with certain choices based on what DropdownA selected, I purposefully defined DropdownB (a choicefield) with 0 choices. DropdownB = () DropdownB = forms.ChoiceField(choices=op_choices, required=False) How do I specify to the server what the valid choices are BASED ON what DropdownA's value is? -
Get next and previous object from QuerySet by object
I have and object and QuerySet which contains this object. I need to get next and previous object of this QuerySet. How can I do that? I could get next this way: next = False for o in QuerySet: if next: return o if o==object: next = True but I think it's very slow and unefficient approach on huge QuerySets. Do you know a better solution? -
IIS and SQL Server Windows authentication in a django application
I am trying to run a django website which connects to a SQL Server, using IIS with Windows authentication. IIS server and SQL server are on different machines under the same domain i.e., iis_machine.example.com and sql_machine.example.com What I'm trying to achieve: Impersonate the remote user accessing the django website hosted on IIS, so his Windows credentials are passed to SQL Server for authentication. What I tried so far: Added this to my web.config file for impersonation <system.web> <identity impersonate="true" /> </system.web> Enabled Windows authentication and set up Application Pool (django_web) for django website as shown below This is what my Authentication for django website looks like in IIS This is what my Application Pool for django website looks like in IIS Added IIS APPPOOL\django_web to SQL Server Security\Logins Result: When I access the django website, IIS prompts the user for his Windows credentials and I can successfully login If user tries to access SQL Server after logging in Case a. IIS, SQL Server are on the different machines: SQL server authentication fails with "Login failed for user 'domain\MACHINENAME$' Case b. IIS, SQL Server are on the same machine, SQL server authentication is successful but authentication credentials used are IIS APPPOOL\django_web … -
django custom model fields
Im trying to create my own custom model field following this guide https://docs.djangoproject.com/en/2.1/howto/custom-model-fields/ class Hand: """A hand of cards (bridge style)""" def __init__(self, north, east, south, west): # Input parameters are lists of cards ('Ah', '9s', etc.) self.north = north self.east = east self.south = south self.west = west # ... (other possibly useful methods omitted) ... next step is(we assume the hand attribute on the model is an instance of Hand) example = MyModel.objects.get(pk=1) print(example.hand.north) new_hand = Hand(north, east, south, west) example.hand = new_hand example.save() "we assume the hand attribute on the model is an instance of Hand" Can someone provide example please? -
return render sends to correct location but no data until page reload?
I have a timeclock app for employees to check-in/check-out with which works ok, however when you're on the user-activity page and either check in or check out once it submits the form it sends you back to the user-activity.html page, but no data is loaded in the table and its not loading data from the view. Once you refresh the page the data is there again but I'm not sure why this is happening. I'll attach 2 images, one before the checkin/checkout button is pressed, and one after and here is my view. Thanks for any help you can give class ActivityView(LoginRequiredMixin, View): def get(self, request, *args, **kwargs): context = {} toggle = UserActivity.objects.current(request.user) user_data = UserActivity.objects.filter(user=request.user).order_by('-timestamp') current_users = UserActivity.objects.order_by('user', '-timestamp').distinct('user') context['toggle'] = toggle context['user_data'] = user_data context['current_users'] = current_users return render(request, "administration/timesheets/user-activity.html", context) def post(self, request, *args, **kwargs): context = {} toggle = UserActivity.objects.toggle(request.user) context['toggle'] = toggle return render(request, "administration/timesheets/user-activity.html", context) -
Django CASE WHEN with 'in' lookup
I have an a model: class First(models.Model): first = models.IntegerField() second = models.IntegerField() And in my FirstView I have a complicated filters in get_queryset method. def get_queryset(self): CASE_FIRST = 1 CASE_SECOND = 2 return self.queryset.filter(~Q(first__in=[CASE_FIRST, CASE_SECOND]) | # this line is ok Q(second=Case( When(first=CASE_FIRST, then=(1, 2, 3))), When(first=CASE_SECOND, then=(3, 4, 5, 6)) ) ) But this code is crashes with that exception: File "/home/path/to/project/venv/lib/python3.6/site-packages/rest_framework/viewsets.py", line 103, in view return self.dispatch(request, *args, **kwargs) File "/home/path/to/project/venv/lib/python3.6/site-packages/rest_framework/views.py", line 483, in dispatch response = self.handle_exception(exc) File "/home/path/to/project/venv/lib/python3.6/site-packages/rest_framework/views.py", line 443, in handle_exception self.raise_uncaught_exception(exc) File "/home/path/to/project/venv/lib/python3.6/site-packages/rest_framework/views.py", line 480, in dispatch response = handler(request, *args, **kwargs) File "/home/path/to/project/venv/lib/python3.6/site-packages/rest_framework/mixins.py", line 42, in list page = self.paginate_queryset(queryset) File "/home/path/to/project/venv/lib/python3.6/site-packages/rest_framework/generics.py", line 173, in paginate_queryset return self.paginator.paginate_queryset(queryset, self.request, view=self) File "/home/path/to/project/core/paginators.py", line 18, in paginate_queryset self.count = queryset.count() File "/home/path/to/project/venv/lib/python3.6/site-packages/django/db/models/query.py", line 387, in count return self.query.get_count(using=self.db) File "/home/path/to/project/venv/lib/python3.6/site-packages/django/db/models/sql/query.py", line 491, in get_count number = obj.get_aggregation(using, ['__count'])['__count'] File "/home/path/to/project/venv/lib/python3.6/site-packages/django/db/models/sql/query.py", line 476, in get_aggregation result = compiler.execute_sql(SINGLE) File "/home/path/to/project/venv/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1063, in execute_sql cursor.execute(sql, params) File "/home/path/to/project/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 68, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "/home/path/to/project/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 77, in _execute_with_wrappers return executor(sql, params, many, context) File "/home/path/to/project/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "/home/path/to/project/venv/lib/python3.6/site-packages/django/db/utils.py", line 89, in __exit__ raise … -
Django URL pattern doesn't work
I have my urls.py included like this: urlpatterns = [ path('files/', include('files.urls')), ] then, in files/urls.py, I put this: urlpatterns = [ path('', views.index, name='index'), path(r'(?P<name>[a-z]+)', views.check, name='check') ] So, I assume that when example.com/files works, so should example.com/files/somename, but it doesn't: Using the URLconf defined in example.urls, Django tried these URL patterns, in this order: [name='index'] files/ [name='index'] files/ (?P<name>[a-z]+) [name='check'] The current path, files/somename, didn't match any of these. What am I missing here? -
How can I query that which student is registered in which course? Also which Teacher is teaching which courses
Here are my models. This is my model and I want to query which students are registered in which courses and which teacher is teaching them. from __future__ import unicode_literals from django.db import models from django.utils.encoding import python_2_unicode_compatible from django.utils import timezone class Teacher(models.Model): teacher_name = models.CharField(max_length=200) def __str__(self): return self.teacher_name class Student(models.Model): student_name = models.CharField(max_length=200) rollnum = models.IntegerField(max_length=6) def __str__(self): return "%s, %s" (self.student_name,self.rollnum) class Course(models.Model): course_name = models.CharField(max_length=200) course_code = models.CharField(max_length=50) def __str__(self): return "%s, %s" (self.course_name,self.course_code) class Attendance(models.Model): is_present = models.BooleanField(default=True) student_id = models.ForeignKey(Student, on_delete=models.CASCADE) course_id = models.ForeignKey(Course,on_delete=models.CASCADE) date = models.DateTimeField(auto_now_add=True) -
Django Rest Framework - Front End Choices
I am trying to figure out how DRF meshes with front ends. I've been looking for tutorials that use the typical template views as normally done with django but i cant find any. I CAN find lots of tutorials and documentation with DRF using REACT JS and Angular JS as a front-end. Could someone please explain why this is the case and why there are no tutorials using the typical html templates? is it a matter of convenience, efficiency, lack of options, or something else? All insight and advice is appreciated. -
AJAX function not receiving return data from a function it calls
This is a bit difficult to explain, because I'm not sure what's happening. In my code base for this Django web project, I have a custom list class that manages several LI elements. The class has a 'find' method that returns the DOM element of the matching string. Next, I have an AJAX query that makes a server-side python call to process data and calls my response function. I have my python scripts running an analysis for each item in my list, so it's making subsequent AJAX calls. The response function for my AJAX is calling the 'find' method from my list object passing in text data AJAX receives from my python script. The 'find' method is executing successfully and return correct results (or rather "trying" to return the results). It returns something successfully on the first item, but every item after that is 'undefined'. My console logs in the 'find' method give me the correct return object before returning it, but the logs immediately after calling 'find' give me something 'undefined.' Is this a scoping issue with AJAX trying to call it repeatedly? /* This is a large class, so I've omitted irrelevant members to the question. */ class … -
Override `render_FOO` for a related field
I have a table like that: import django_tables2 as tables from .models import MyModel class MyTable(tables.Table): class Meta: model = MyModel fields = ['myfield', 'relatedtable.otherfield'] How can I override render_<column_name> or value_<colum_name>? Is it even possible? I tried following approaches, but none of them worked: Override attributes in __init__() class MyTable(tables.Table): class Meta: model = MyModel fields = ['myfield', 'relatedtable.otherfield'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.columns['relatedtable.otherfield'].render = myrenderfnc # and/or self.columns['relatedtable.otherfield'].column.render = myrenderfnc Custom column class MyColumn(tables.Column): def render(self, record): return getattr(record, 'relatedtable.otherfield') class MyTable(tables.Table): class Meta: model = MyModel fields = ['myfield'] otherfield = MyColumn() 'Renaming' column class MyTable(tables.Table): class Meta: model = MyModel fields = ['myfield'] def __init__(self, *args, **kwargs): exclude = ['relatedtable.otherfield'] extra_columns = [('otherfield', self.base_columns['relatedtable.otherfield')] super().__init__(*args, exclude=exclude, extra_columns=extra_columns, **kwargs) self.columns['relatedtable.otherfield'].render = myrenderfnc # and/or self.columns['relatedtable.otherfield'].column.render = myrenderfnc -
Django - POST - save multiple items in queryset
I'm not sure if the title is correctly describing the issue. If you have a more descriptive title, please edit the title. I have a following dynamically added input fields: The first two rows is the first object, second row is the second object, and so on.... I am trying to save these dynamically added elements to DB by customizing post() method. Using my current version of overriding post() method: if 'bha' in request.POST: bha_form = BHA_Form(request.POST, instance= #some_kwargs...) print(request.POST) it prints the following queryset: <QueryDict: {'csrfmiddlewaretoken': [# foo_token], 'item_description': ['aaaaaaaaa', 'bbbbbbbbb'], 'num_of_jts': ['aaaaaaaaaaa', 'bbbbbbbbb'], 'length': ['aaaaaaaaaaaa', 'bbbbbbbbbb'], 'cum_length': ['aaaaaaaaaaaaa', 'bbbbbbbbbbbbbb'], 'outer_d': ['aaaaaaaaaaaaa', 'bbbbbbbbbbbbbbb'], 'inner_d': ['', ''], 'drift_d': ['', ''], 'od_cplg': ['', ''], 'top_thread': ['', ''], 'air_wght': ['', ''], 'make': ['', ''], 'sn': ['', ''], 'bha_component': ['Submit']}> As you can see, each input fields have 2 values in a form of list, because there are two objects present on the Front-End. If I just use bha_form.save(), it will save only the last value in a queryset list. This is not what I want. I want to use something like get_or_create() method to create new objects for each dynamically added elements, or edit objects if they are already present in DB … -
How to get request params in Django admin custom column?
I need to keep information about filtering and searching in Django admin change page. So when user filters by "?away_team__id__exact=267821", I need to append this query to change page url. Let's say we filtered objects by query above. This is the url of change list: http://127.0.0.1:8000/matches/match/?away_team__id__exact=267821 I want to make change column which redirects user to change page of the current object and appends query to the url so instead: http://127.0.0.1:8000/matches/match/2009/change/ The url will be: http://127.0.0.1:8000/matches/match/2009/change/?away_team__id__exact=267821 The problem is that I couldn't access request in the custom column method. I tried to do it using template language but without success, I get: http://127.0.0.1:8000/matches/match/1996/change/?{{%20request.GET.urlencode%20}} This is the method: def change(self,obj): return mark_safe(f"""<a class="changelink" href="{reverse("admin:matches_match_change",args=(obj.pk,))}"""+"?{{ request.GET.urlencode }}\""+"><span class='icon'>Zmeniť</span></a>") Do you know how to do that? EDIT This is because I need to create a NEXT and PREVIOUS buttons in change object page so user can step directly to the next object. -
Django multiple foreign key, Same related name
I would like to create a model(1) with multiple foreign keys to the same other model(2). I want these foreign keys to have the same related_name because each foreign key will point to difference instances of model(2), because I need one reversed relation for all foreign keys. Maybe an example will be more explicit : class Parent(Model): name = models.CharField(max_length=100) class Child(Model): name = models.CharField(max_length=100) father = models.ForeignKey(Parent, related_name='children') mother = models.ForeignKey(Parent, related_name='children') How can I do that ? I already know an ugly way to do so : class Parent(Model): name = models.CharField(max_length=100) @property def children(self): # Pick the existing one in fields 'children_1' or 'children_2' class Child(Model): name = models.CharField(max_length=100) father = models.ForeignKey(Parent, related_name='children_1') mother = models.ForeignKey(Parent, related_name='children_2') -
Django REST framework get selected values from complicated json
I have complicated json, I want to get only part of information from it and store it to db. Are serializers (Django REST framework) way to go? Consider something like following: {"top_level":{"detail1":"info1", "detail2":"info2", "detail3":{"deeper_detail1":"deeper_info1", "deeper_detail2":"deeper_info2"}}} For example I would have Car model: class Car(models.Model): car_type = models.CharField(max_length=20) car_state = models.CharField(max_length=20) The 'car_type' should get value from 'detail2' (that is info2), 'car_state' should get value from 'deeper_detail2' (that would be deeper_info2). Only idea I got is this: class CarSerializer(serializers.ModelSerializer) class Meta: model = Car fields = ('car_type', 'car_state') def get_car_type(self, obj): return obj["top_object"]["detail2"] def get_car_state(self, obj): return obj["top_object"]["detail3"]["deeper_detail2"] It seems django doesn't agree with me so I wonder if this is the right path to begin with. Can I do something like that with serializers in Django REST framework? -
Django; How to redirect after confirm window
I'm working on Django project. I'm creating a delete function and I'm wondering how I can redirect to a page with ajax. My current views.py is this. def delete_post(request, pk): if request.method == 'DELETE': post = get_object_or_404(Post, id=pk) post.delete() #redirect to a page js function deletePost(post) { if (confirm("Are you sure?")) { var $post = $(post) var id = $post.data('id') $.ajax({ url:'/posts/delete/' + id, method: 'DELETE', beforeSend: function(xhr) { xhr.setRequestHeader('X-CSRFToken', csrf_token) } }) } } Seems like HttpResponseRedirect doesn't work with ajax. Anyone who can give me tips? or I want to know the way to do this without ajax if it's possible. -
Python Django NameError: name 'datetime' is not defined
After typing on my command line in the app's directory: python manage.py runserver I get this error: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "C:\Users\Paulo\Coding\Python\lib\site-packages\django\core\management\__init__.py", line 371, in execute_from_command_line utility.execute() File "C:\Users\Paulo\Coding\Python\lib\site-packages\django\core\management\__init__.py", line 347, in execute django.setup() File "C:\Users\Paulo\Coding\Python\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Paulo\Coding\Python\lib\site-packages\django\apps\registry.py", line 112, in populate app_config.import_models() File "C:\Users\Paulo\Coding\Python\lib\site-packages\django\apps\config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "C:\Users\Paulo\Coding\Python\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\Paulo\Coding\Django projects\Project 1\freezer\models.py", line 5, in <module> class Item(models.Model): File "C:\Users\Paulo\Coding\Django projects\Project 1\freezer\models.py", line 31, in Item added_date = models.DateField("date added", default=datetime.date.today) NameError: name 'datetime' is not defined This similarly titled question did not help me. I have from datetime import date in my models.py. I am running python 3.6.5 and Django 2.0.4. I put this app online a while ago, it is still working and models.py is identical. I'm confused as to what I've done wrong. Could it be linked … -
Django form not saving or emailing as it should
I've built a simple form that should send an email on form submit, as well as save to a table in the database. I've done this by following different tutorials, as I am still learning Django. At the moment, it should be configured to output the email to the console rather than actually send an email, as per the tutorial I followed. I don't get any errors and the console shows a HTTP 200 error code when the form is posted, so it seems to be working, btu since nothing is saved and no email is printed to the console, I'm not sure what is going on. My models.py: from __future__ import unicode_literals from django.db import models from multiselectfield import MultiSelectField class Booking(models.Model): timeslot = ( ('EM', 'Early Morning'), ('LM', 'Late Morning'), ('EA', 'Early Afternoon'), ('LA', 'Late Afternoon'), ) services = ( ('gutters', 'Gutter Cleaning'), ('windows', 'Window Cleaning'), ('decks', 'Deck Staining'), ('painting', 'Painting'), ) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) email = models.CharField(max_length=30) phone = models.CharField(max_length=30) booking_time = models.CharField(max_length=1, choices=timeslot) selected_services = MultiSelectField(choices=services) The relevant part of my views.py: def booking_new(request): form_class = BookingForm # new logic! if request.method == 'POST': form = form_class(data=request.POST) if form.is_valid(): first_name = request.POST.get( 'first_name' … -
Django class-based ListView vs function-based list_view
So I'm trying to wrap my head around the following issue. The Class-based view for customer_list works like a charm, it show a list of all customers residing in the customer tabel. However, the function based view, which should do exactly the same returns empty. Maybe there's something I'm missing but I just want to know how both views differ and when to use what. If there's someone who could explain what I'm missing? urls.py from django.conf.urls import url, include from . import views # Function based view url(r'^all_customers/$', views.customer_list, name='all_customers'), # Class based view url(r'^all_customers/$', views.customer_list.as_view(),name='all_customers'), views.py from django.views import generic from django.shortcuts import render from .models import Customer # Function based view def customer_list(request): customers = Customer.objects.all() return render(request, 'all_customers.html', {'customers': customers}) # Class based view class CustomerList(generic.ListView): model = Customer template_name = 'all_customers.html' models.py from django.db import models class Customer(models.Model): first_name = models.CharField(max_length=200) prefix = models.CharField(max_length=8, null=True, blank=True) last_name = models.CharField(max_length=200) {% for customer in customer_list %} <tr> <td>{{customer.pk}}</td> <td> {% if customer.prefix %} {{customer.first_name}} {{customer.prefix}} {{customer.last_name}} {% else %} {{customer.first_name}} {{customer.last_name}} {% endif %} </td> </tr> {% endfor %}