Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Exceptions: Django 1.8 with MSSQL Server 2017 offline
As I'm new to Django. I have installed Django = 1.8 version. I tried with MSSQL Server 2017 which is locally installed in standalone system. Apart from settings.py file I had not modified anything. It is showing ImproperlyConfigured: Django 1.11 is not supported even though i had used Django 1.8 version. Settings.py DATABASES = { 'default': { 'ENGINE': 'django_pyodbc', 'HOST': '127.0.0.1', 'NAME': 'demo2016', 'USER': '', 'PASSWORD': '', 'PORT': '', 'OPTIONS': { 'driver': 'ODBC Driver 13 for SQL Server', }, } } C:\Users\Vitriv-Desktop\Desktop\sqldjango>python manage.py migrate Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "C:\Users\Vitriv-Desktop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\__init__.py", line 364, in execute_from_command_line utility.execute() File "C:\Users\Vitriv-Desktop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\__init__.py", line 338, in execute django.setup() File "C:\Users\Vitriv-Desktop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Vitriv-Desktop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\apps\registry.py", line 108, in populate app_config.import_models() File "C:\Users\Vitriv-Desktop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\apps\config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "C:\Users\Vitriv-Desktop\AppData\Local\Programs\Python\Python36-32\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\Vitriv-Desktop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\auth\models.py", line 4, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "C:\Users\Vitriv-Desktop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\auth\base_user.py", line 52, … -
django messages for a successfully delete,add or edit item
I have started using django messages for creating items. It works great for creating adding a new item. but.. I want to have functions for each action - delete,create,edit ( I have different buttons for each) I have only post function.. it really confuse me when I try to create a message that the item has been deleted successfuly.. how can I know a delete was submitted and not post? since everything goes through post function. The PostEdit and Delete don't have the "request" that it requires for messages. So for now I h ave only messages.succuess that runs everytime I create a server. I want to have a different message for delete, edit, create and same for errors. Does anyone have a clue? index.html - {% if messages %} <ul class="messages"> {% for message in messages %} <div class="alert alert-success alert-dismissible fade show" role="alert"> <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li> <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> {% endfor %} </ul> {% endif %} views.py - # Create your views here. from django.shortcuts import render_to_response from django.shortcuts import get_object_or_404 from django.shortcuts import render, redirect from django.template import RequestContext from django.views.generic import TemplateView, … -
ModuleNotFoundError: No module named 'cart.forms'
Python3.6 Django project. views.py: from django.shortcuts import render, get_object_or_404 from .models import Category, Product from cart.forms import CartAddProductForm output: ModuleNotFoundError: No module named 'cart.forms' I already installed cart, but still have this error. -
How to get the object from a Django Rest Framework serializer init method?
I have my serializers code set up as follows: class ProductSerializer(serializers.ModelSerializer): """ * Serializes Products. """ def __init__(self, *args, **kwargs): print kwargs.pop('product_passed') super(ProductSerializer, self).__init__(*args, **kwargs) Now, this serializer is being called from a view using the code below: product_passed = self.get_object(pk) product_serializer = ProductSerializer(product_passed) What I want to do is call the product_passed from my serializer init method. How can I do this? Right now, my method does not work. -
Sorting a partially linked list in sql
I have declared a task-priority list in SQL like so: CREATE TABLE TaskList( id int not null primary key, execute_before int null, SomeData nvarchar(50) NOT NULL) I now want to select rows from this table such that the rows would be sorted by id, but any rows that "execute_before" a given row would be placed before such rows, again sorted by id. So, if the table contains data like this: id execute_before 1 null 2 null 3 2 4 3 5 2 6 null the result should be like so: id execute_before 1 null 4 3 3 2 5 2 2 null 6 null My target SQL server is PostgreSQL, but I'm using it through Django, so either of these solutions is fine. -
Django Rest framework not giving 403 error for unauthenticated user
I'm making an api with django normal view using Django restframework token, decorator and permissions like below @api_view(['GET']) @permission_classes((IsAuthenticated, )) def test(request, format=None): permission_classes = [IsAuthenticated] content = {"hello":"world"} return Response(content) It Always give me the result even if i didn't add a token to the header note that i added all the required settings my settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'myapp', 'rest_framework', 'rest_framework.authtoken', #'utils', 'schedule', ] # SWAGGER_SETTINGS = { # 'JSON_EDITOR': True, # } MIDDLEWARE_CLASSES = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.BasicAuthentication', 'rest_framework.authentication.TokenAuthentication', 'rest_framework.authentication.SessionAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), # 'DEFAULT_RENDERER_CLASSES': ( # 'rest_framework.renderers.JSONRenderer', # ), 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', 'PAGE_SIZE': 2, 'EXCEPTION_HANDLER': 'rest_framework.views.exception_handler' }REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.BasicAuthentication', 'rest_framework.authentication.TokenAuthentication', 'rest_framework.authentication.SessionAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), # 'DEFAULT_RENDERER_CLASSES': ( # 'rest_framework.renderers.JSONRenderer', # ), 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', 'PAGE_SIZE': 2, 'EXCEPTION_HANDLER': 'rest_framework.views.exception_handler' } As per the documentation it should give 403 status error since user is not authenticated but it is giving 200 response with normal data -
Django syndication function error
I'm trying to create a custom Django RSS feed using django syndication (actually using django wagtail feeds). I have an error which I think I've identified as stemming from a NoneType object which is returned by the get_object() function inside syndication/views.py. That function is called as part of class Feed() and looks like this: def get_object(self, request, *args, **kwargs): return None That function is called at line 36 but fails because get_object() returns a None object. Can anyone tell me why that might be? I'm missing something about the expected functioning of this. Thanks! -
worker_class egg:gunicorn#gevent VS gevent
I run website project with Django + Gunicorn + Gevent below WSGI. And I try to running command "gunicorn --config gunicorn.conf.py project.wsgi:application". In the gunicorn.conf.py where I set worker_class = 'egg:gunicorn#gevent' as document said(http://docs.gunicorn.org/en/19.0/settings.html). But this configuration file does not work! When I set worker_class = 'gevent' in gunicorn.conf.py which makes project work! Any can tell me What's the problem! Thks!! -
Processing Calculations With TemplateTag Returns None
I have a model Coper and a field that ask user to select whether they need to get price quotes dynamically or not. So if a user selects 'dynamic', the user will get the quote for the product and other charges. So I wrote a template tag that will take the id of the product, filter the currency of the seller and lookup for the rate in another model and finish up the quote. @register.filter(name='get_total_quote') def get_total_quote(value): tap = Coper.objects.get(pk=value) get_cnd = VAM.objects.get(money_code = tap.seller.profile.currency) ratex = get_cnd.money_rate if tap.margin_type == 'plus': percent = tap.margin_figure / 100 addup = ratex * percent total_amt = ratex + addup return total_amt if tap.margin_type == 'minus': percent = tap.margin_figure / 100 addup = ratex * percent total_namt = ratex - addup return total_namt Template {% load quote_filter %} {% for m in all_quotes %} {% if m.pricing == 'dynamic' %} {{m.id|get_total_quote }} {% else %} <p> Fixed price is $3500 </p> {% endif %} {% empty %} <p> No product yet. </p> {% endfor %} When I load the site, I got NONE as the price of the dynamic quote instead of the actual figure. What am I missing? -
How to create mysite.wsgi file?
I am following this tutorial http://uwsgi-docs.readthedocs.io/en/latest/tutorials/Django_and_nginx.html to setup django with nginx and uwsgi. But I am confused about this line: uwsgi --http :8000 --module mysite.wsgi In the tutorial there's nothing about mysite.wsgi file. What should be the content of this file? -
Fetching specific value for nested object in a queryset for serializing
I have two models in my django project which are Followup and User, every followup has a user instance mapped to it [actor field]. What happens is when I run this code I get the primary key for actors by default I need to get the first_name field which is in user model for all the rows fetched from followups result = Followup.objects.filter(lead_name = lead).only('lead_name','followup','comments','actor') plan = PlanType.objects.filter(lead_id = lead) response["followup"] = serializers.serialize('json', result) -
OperationalError during django migration postgres on large tables
Sometimes during migrations in django on big tables (>50 millions rows) i receive the following error: Traceback: Traceback (most recent call last): File "src/audit/manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.5/dist-packages/django/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.5/dist-packages/django/core/management/__init__.py", line 355, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.5/dist-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.5/dist-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.5/dist-packages/django/core/management/commands/migrate.py", line 204, in handle fake_initial=fake_initial, File "/usr/local/lib/python3.5/dist-packages/django/db/migrations/executor.py", line 115, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/usr/local/lib/python3.5/dist-packages/django/db/migrations/executor.py", line 145, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/usr/local/lib/python3.5/dist-packages/django/db/migrations/executor.py", line 244, in apply_migration state = migration.apply(state, schema_editor) File "/usr/local/lib/python3.5/dist-packages/django/db/migrations/migration.py", line 129, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/usr/local/lib/python3.5/dist-packages/django/db/migrations/operations/fields.py", line 86, in database_forwards field, File "/usr/local/lib/python3.5/dist-packages/django/db/backends/base/schema.py", line 439, in add_field self.execute(sql) File "/usr/local/lib/python3.5/dist-packages/django/db/backends/base/schema.py", line 120, in execute cursor.execute(sql, params) File "/usr/local/lib/python3.5/dist-packages/django/db/backends/utils.py", line 80, in execute return super(CursorDebugWrapper, self).execute(sql, params) File "/usr/local/lib/python3.5/dist-packages/django/db/backends/utils.py", line 65, in execute return self.cursor.execute(sql, params) File "/usr/local/lib/python3.5/dist-packages/django/db/utils.py", line 94, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "/usr/local/lib/python3.5/dist-packages/django/utils/six.py", line 685, in reraise raise value.with_traceback(tb) File "/usr/local/lib/python3.5/dist-packages/django/db/backends/utils.py", line 65, in execute return self.cursor.execute(sql, params) django.db.utils.OperationalError: server closed the connection unexpectedly This probably means the server terminated abnormally before or while processing the request. Can … -
Django - manytomany field with though and foreign key dont show user data why?
Im trying to get data from the user's model from another model, that is between the both to models. My main model is Team from there there's a members field that is a manytomany field where it's going through its own model called team memberships that has 3 fields where one is a relation to a user. Short saying: Calling model.Teams -> field.membersmanytomany -> model.TeamMembership -> field.userforeignkey -> model.users -> getting info But every time im trying it I don't get any info, why? My Models: Users model is standard from Django. class Team(models.Model): name = models.CharField(max_length=16) logo = models.ImageField(upload_to='teams/avatars', default='static/img/userpreload.png') background = models.ImageField(upload_to='teams/backgrounds', default='static/img/userpreload.png') description = models.TextField(blank=True) people_needed = models.PositiveSmallIntegerField() members = models.ManyToManyField(User, through='TeamMembership') accepts_applications = models.BooleanField() @property def teamleaders_listable(self): leaders = self.members.filter(teammembership__leader=True) return ", ".join(l.extendeduser.nickname for l in leaders) @property def multiple_teamleaders(self): if len(self.members.filter(teammembership__leader=True)) > 1: return True else: return False def __str__(self): return self.name class TeamMembership(models.Model): user = models.ForeignKey(User) team = models.ForeignKey(Team) leader = models.BooleanField() My View: def team(request, team_pk): requested_team = get_object_or_404(Team, pk=team_pk) feedback = FeedbackSupportForm() context = { 'requested_team': requested_team, 'feedback': feedback, } if requested_team.multiple_teamleaders: context["multiple_teamleaders"] = True if request.user.is_authenticated(): if requested_team.members.all().count() > 0: context['teamhasmembers'] = True logged_in_user = get_object_or_404(User, pk=request.user.pk) context['logged_in_user'] = logged_in_user return … -
Django: Why does this test fail?
I an new to Django and to Test Driven Devolopment as well. After working through the tutorials in the 1.11 official documentation I am starting my first app: wos_2017_2 This test fails and I cannot figure out why: import unittest from django.test import TestCase from django.test import Client from .models import * from .views import * class SimpleTest(unittest.TestCase): def test_index(self): client = Client() response = client.get('/') self.assertEqual(response.status_code, 200) FAIL: test_index (wos_2017_2.tests.SimpleTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/js/django/wos/wos_2017_2/tests.py", line 16, in test_index self.assertEqual(response.status_code, 200) AssertionError: 404 != 200 This link in the browser works without a problem: http://localhost:8000/wos_2017_2/ In the shell (run from the project root): >>> from django.test import Client >>> client = Client() >>> response = client.get('/') >>> response = client.get('wos_2017_2/index') Not Found: /wos_2017_2index >>> response = client.get('wos_2017_2/') Not Found: /wos_2017_2 >>> response = client.get('/wos_2017_2/') >>> response = client.get('/wos_2017_2/index/') Not Found: /wos_2017_2/index/ >>> response = client.get('/wos_2017_2/') >>> response.status_code 200 in wos_2017_1.urls.py: from . import views from django.conf.urls import url urlpatterns = [ url(r'^$', views.index, name='index'), ] -
Python hendrix : hx start command doesn't work / python run.py works
My problem is "hx start" command is not working. It displays the output "Ready and Listening on port 8000..." but the demo my_noodle (https://github.com/jMyles/hendrix-demo-django-nyc) is not working : a view is displayed but the websocket got a 404 error. However, when I do "python run.py" instead of hx start--dev, it works but I guess it's not a production way to start hendrix server. What do you think of that ? Is it normal ? How to make hx start commands working ? Is python run.py a good way to start a production server ? -
Experiencing TypeError (expected string or Unicode object, NoneType found) when saving a form instance to request.session
I'm running into trouble trying to save an instance of a form class in Django's request.session dictionary. I get TypeError: expected string or Unicode object, NoneType found. The whole traceback being: File "/home/myuser/.virtualenvs/myenv/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 187, in get_response response = middleware_method(request, response) File "/home/myuser/.virtualenvs/myenv/local/lib/python2.7/site-packages/newrelic-2.56.0.42/newrelic/hooks/framework_django.py", line 331, in wrapper return wrapped(*args, **kwargs) File "/home/myuser/.virtualenvs/myenv/local/lib/python2.7/site-packages/user_sessions/middleware.py", line 46, in process_response request.session.save() File "/home/myuser/.virtualenvs/myenv/local/lib/python2.7/site-packages/user_sessions/backends/db.py", line 73, in save session_data=self.encode(self._get_session(no_load=must_create)), File "/home/myuser/.virtualenvs/myenv/local/lib/python2.7/site-packages/django/contrib/sessions/backends/base.py", line 86, in encode pickled = pickle.dumps(session_dict, pickle.HIGHEST_PROTOCOL) TypeError: expected string or Unicode object, NoneType found What's the scenario? I'm testing form validation for image uploading. I'm disallowing file sizes beyond a certain limit, raising a validation error. The form instance bound to request.POST is saved in request.session, e.g.: form = PhotoForm(request.POST,request.FILES)) request.session["photo_form"] = form request.session.modified = True and then I redirect to a different view to use the said form instance. I've noticed all this works successfully most of the times, but for certain very, very big files where I'm supposed to raise a validation error, I instead get the error shown above. Not all validation errors result in this. For now, the pattern is that only extremely large files induce this. I can't make sense of that. Can anyone shed light on … -
how to start gunicorn automatically in server with Ubuntu 16.04
client name is siar , unroot here is my idea: 1 sudo mkdir -p /usr/lib/systemd/system 2 sudo vim /usr/lib/systemd/system/siar.service and it's context: [Unit] After=syslog.target network.target remote-fs.target nss-lookup.target [Service] # 你的用户 User=siar # 你的目录 WorkingDirectory=/home/siar/sites/django-blog-learning/blogproject # gunicorn启动命令 ExecStart=/home/siar/sites/env/bin/gunicorn --bind unix:/tmp/siar.socket blogproject.wsgi:application Restart=on-failure [Install] WantedBy=multi-user.target 3 sudo systemctl start siar and here i get error: Failed to start siar.service: Launch helper exited with unknown return code 1 See system logs and 'systemctl status siar.service' for details. andthen i try sudo systemctl start other .server'file here has the same error. i was confused and please you help me -
Is it possible to bundle Django web apps with Nuitka?
I want to bundle a python web app based on Django for off-internet business usage. I found Nuitka maybe suitable for such problem. -
Execute task on specific time in Django
I have to execute a task at a specific time, which is specified by the user. This will not be fix time... It will be according to user... On that time I have to execute my task... To achieve this I tried to use django-cron also tried to use django-crontab... But in both case either we have to specify cron details in settings.py or we've to execute runcron commands. I also checked django-celery (I don't have any idea about celery much. I may be wrong). In celery we have to specify time while defining task... Can any one help me how can I do this... I am using django as a backend... -
How to extend my django web application with a wordpress blog?
I have a Django web application at https://www.reelbugs.com I need to extend the application to have a blog of static content at https://reelbugs.com/blog I can create a Blogpost model, comment system, etc myself, but I'd rather have a good premium Wordpress template with Disqus, etc plugins for my blog. How can I go forward with this? Any hints would help. -
Inner loop on condition in list comprehension
I have a function to check availability of product and its variations. both model has quantity_left field. If a product has variations i want to get quantity_left from variation, otherwise i will take quantity_left from product. def check_quota(products): q_list = [] for p in products: if p.has_variations: for v in p.variations: q_list.append(v.quantity_left) else: q_list.append(p.quantity_left) return sum(q_list) So above function will return either 0 or any number. if it is zero means product sold out. Above code is working fine, but i want to optimize this function using list comprehension. I tried this but this doesn't seems to work. return sum([v.quantity_left if p.has_variations else p.quantity_left for p in products for v in i.variations]) How can i apply if p.has_variations on inner loop. -
MultiValueField returning data back to field
I have made a custom widget that holds a TextInput() and Select() fields, which looks like so: Now I'm struggling to get this working with the data that is captured. As of now i can input 12 days and the data will appear in the models as 12 days But i have had it as [u'12', u'days'] before. So my problem is the fields text not displaying again once saved. It will save completly fine but it will not render the data like it should back in the widget. class LeadTimeWidget(MultiWidget): def __init__(self, attrs=None): CHOICES = (('Days', 'Days'), ('Weeks', 'Weeks'), ('Months', 'Months'),) widgets = (forms.TextInput(), forms.Select(choices=CHOICES)) super(LeadTimeWidget, self).__init__(widgets, attrs) def decompress(self, value): if value: return value.split(' ') return [None, None] class LeadTimeMultiField(MultiValueField): widget = LeadTimeWidget # TODO struggling to convert data recieved from widget to a usable format def __init__(self, *args, **kwargs): list_fields = (forms.fields.CharField(max_length=31), forms.fields.CharField(max_length=31)) super(LeadTimeMultiField, self).__init__(list_fields, *args, **kwargs) def compress(self, data_list): return ' '.join(data_list) Can anyone help me understand and fix the issue as to why its not rendering like it should be? Thanks J -
django url issue using mutiple regular expressions
I am having an issue with an url and regular expression I get the error AttributeError: Generic detail view EmployeeDetailView must be called with either an object pk or a slug. What I am to achieve is to get to a user detail page coming from a specific project url(r'^project/(?P<pk>[0-9]+)/$',views.ProjectDetailView.as_view(), name='ProjectDetails'), url(r'^project/(?P<pk1>[0-9]+)/(?P<pk2>[0-9]+)/$',views.EmployeeDetailView.as_view(), name='EmployeDetails'), my view is : Project detail : class ProjectDetailView(generic.DetailView, LoginRequiredMixin): #import pdb; pdb.set_trace() model = Project template_name = 'project_details.html' def get_context_data(self, **kwargs): context = super(ProjectDetailView, self).get_context_data(**kwargs) try: team_name = Project.objects.get(id=self.kwargs['pk']).team_id.members.all() context['team_name'] = team_name except AttributeError: pass return context class EmployeeDetailView(generic.DetailView, LoginRequiredMixin): #import pdb; pdb.set_trace() model = MyUser template_name = 'Employee_Details.html' def get_context_data(self, **kwargs): context = super(EmployeeDetailView, self).get_context_data(**kwargs) employee_name = MyUser.objects.get(id=self.kwargs['pk']) context['employee_name'] = employee_name return context HTML link : <span class="fa fa-id-card-o" aria-hidden="true"><a href="{% url 'website:EmployeDetails' pk1 = project.id pk2 = member.id %}"> Show Results</a> could you please help me to figure it ? thx you ;) -
Can I combine view functions in one view class?
Below I have included two view functions that I am currently working with. I was thinking that since both functions operate on the same template that it would be wise to combine them. Can i just put a class decorator above these functions? Is the functionality then still the same? My main point is that one function only takes 'request' but the other takes 'request and 'slug' in its function. @login_required(login_url='/') def choose(request): if request.method == 'POST': print(request.POST.get) # Make a shoplist model instance, # define title, # define user as author, # define slug, # save budget value from the Budget view # save dagen value from the Budget view # save shoplist shoplist = Shoplist() shoplist.title = str(make_aware(datetime.now(), timezone=None, is_dst=None)) shoplist.author = request.user shoplist.slug = slugify(str(shoplist.author) + '-' + shoplist.title) shoplist.budget = request.POST.get('budget') shoplist.dagen = request.POST.get('dagen') shoplist.vegetarisch = request.POST.get('vegetarisch') shoplist.save() # Get recipes from database and POST data form previous view if request.POST.get('vegetarisch') == 'True': recipes = Recipe.objects.filter(vegetarisch=True).all() else: recipes = Recipe.objects.all() budget = shoplist.budget dagen = shoplist.dagen template = loader.get_template('recipes/choose.html') c = {'object_list': recipes, 'budget': budget, 'dagen': dagen} return HttpResponse(template.render(c)) else: return HttpResponseNotAllowed('GET') @login_required(login_url='/') def add_to_shoplist(request, slug): # Get the shoplist that is made in the choose … -
AttributeError: 'module' object has no attribute '__file__'
import google google.file Traceback (most recent call last): File "", line 1, in AttributeError: 'module' object has no attribute 'file'