Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to structure Django models for multiple forms using a subset of a list of fields?
I am building a large, complex form system through Django. It is more complex than any form I have yet built, and I have some database design background but not a lot of experience with Django. Let's say that there are about 500 possible questions, and 6 different form types. About 75% of the questions are common to all 6 forms, but the rest appear on 1-5 of the forms in various, somewhat overlapping combinations (for example, question 20 appears on forms A, B, and D, but question 21 appears on forms B, C, and D). The possible solutions I've come up with so far are: 1) have one model that is all of the common questions and then a separate model for each form type (A, B, C, D, E, F) that inherits the common questions and then adds each thing that is not common. The downside to this is that there is redundancy between form types on some fields (those questions that appear on multiple forms). 2) have one table/model for all 500 questions, then have each form type linked to an intermediary table that lists which questions apply to which form type. This seems easy enough to … -
Django CreateView redirect to ListView when form invalid
i have views.py like this class InventoryListView(ListView): context_object_name = 'inventorys' model = models.Inventory def get_context_data(self, **kwargs): context = super(InventoryListView, self).get_context_data(**kwargs) context['form'] = InventoryForm() return context class InventoryCreateView(CreateView): fields = ('name', 'sn', 'desc', 'employee') model = models.Inventory and here my urls.py url(r'^invn/$',views.InventoryListView.as_view(), name='inventory_list'), url(r'^invn/create$',views.InventoryCreateView.as_view(), name='inventory_create'), and here my inventory_list.html {% for inventory in inventorys %} <td>{{ inventory.name }}</td> {% endfor %} <form method="post" action="{% url 'system:inventory_create' %}"> {% csrf_token %} {{ form.as_p }} </form> if the form is valid, its work well. But if the form is invalid it will redirect to inventory_form.html that will cause TemplateDoesNotExist since Django CreateView need inventory_form.html (CMIIW). simple solution create inventory_form.html but that not what I want. how to make it redirect to my ListView when the form is invalid with error messages ?... -
How to create a Django database backup?
I run multiple (more or less) identical Django (1.11) deployments running on the exact same schema, but different settings (I make my own Settings models). Values in these Settings models, of which there are plenty, are different for each deployment, so these sites can appear differently depending on the settings, for example. A business requirement came up that requires me to regularly export these Settings models (DisplaySettings, CurrencySettings, etc.) from one stack, and import them into another stack. I know dumpdata and loaddata offer basic functionality in the form of JSON files, but I also need these extra functionalities from the business side: The admin must be able to select which settings to export, including ForeignKey and ManyToManyField relations that may be in these settings. When importing that file, the admin must be able to choose which settings in the file to import, and how (update the existing settings model, or create a new one). The same exported file can be re-imported into the same stack to create duplicate copies of these settings. Here are the solutions I have tried so far: dumpdata/loaddata: Does not need the "choose which settings to import/export" requirement. django-import-export: only supports exporting of tabular structures, … -
Django - FOREIGN KEY constraint failed when changing custom user model in admin page
I've created a custom User model, User manager, and User admin in Django 2.0. Everything works correctly except when I try to change a User's attributes as a superuser in the admin page. When I try to change anything, I get IntegrityError at /admin/home/myuser/14/change/ FOREIGN KEY constraint failed Request Method: POST Request URL: http://localhost:8000/admin/home/myuser/14/change/ Django Version: 2.0 Exception Type: IntegrityError Exception Value: FOREIGN KEY constraint failed I'm not sure what I'm doing wrong, as I wasn't even aware that my models had any foreign keys in the first place. I've tried all that I can think of. models.py: class UserManager(BaseUserManager): use_in_migrations = True def _create_user(self, email, name, organization, password, **extra_fields): if not all([email, name, organization, password]): raise ValueError("All fields are required") email = self.normalize_email(email) user = self.model(email=email, name=name, organization=organization, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, name, organization, password=None, **extra_fields): extra_fields.setdefault("is_staff", False) return self._create_user(email=email, name=name, organization=organization, password=password, **extra_fields) def create_superuser(self, email, name, organization, password, **extra_fields): extra_fields.setdefault('is_staff', True) #extra_fields.setdefault("is_admin", True) extra_fields.setdefault("is_superuser", True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') return self._create_user(email, name, organization, password, **extra_fields) class MyUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) name = models.CharField(max_length=40) organization = models.CharField(max_length=100) is_admin = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) can_use_monsoon = … -
Django admin adding ajax functionality
While the Django admin is great for getting projects up and running quickly, I find it hard to customise it exactly to my liking. One example of this is a situation where the user selects if the model in question has a parent. If the answer is True, you might want to display (via Ajax), a select dropdown asking if this model is to be shown in the main menu. If the answer to the question was False, you would not show the select dropdown, and set the value of this field (inMainMenu) to False (this could be done in the model). These fields of course do not have a Foreign Key relationship, so it's not a question of dependent dropdowns. Is there a simple solution to this problem? Many thanks in advance. -
CSV reader putting /n after each row
I have generated a CSV file from excel. I am trying to read this CSV file using python CSV. However after each row I get /n. How to remove this /n. Here is my code: with open('/users/ps/downloads/test.csv','rU') as csvfile spamreader = csv.reader(csvfile,dialect=csv.excel_tab) a = [] for row in csvfile: a.append(row) print a I get result like this: ['HEADER\n', 'a\n', 'b\n', 'c\n', 'd\n', 'e'] I want to have results like this: ['HEADER', 'a', 'b', 'c', 'd', 'e'] -
Django Model Field Callable Default Not Working
Django's callable model field default are broken. When I set a model field default equal to a callable (see migration file below), all models get the same value even though the callable returns different values each time it is called. This worked on previous fields, so I'm confused why Django would be failing on this field. Everything works up until the point I migrate, when inspecting the database column reveals all values to be the same. Migration file: # -*- coding: utf-8 -*- # Generated by Django 1.10.1 on 2018-05-10 14:53 from __future__ import unicode_literals from django.db import migrations, models import screen.models class Migration(migrations.Migration): dependencies = [ ('screen', '0064_employer_enable_show_question_template_tags'), ] operations = [ migrations.AddField( model_name='question', name='key', field=models.TextField(default=screen.models.generate_question_key), ), ] The default returns different values: >>> import screen >>> screen.models.generate_question_key() 'JpZzloZkiLyvPLrDZ9764VTWkNUon1FD08mGKODa2uiqW1nV422HXVvt78MsW7aR' >>> screen.models.generate_question_key() 'NHyTwPDA2cAAsTeIR77INLMM6Ik14EQ6vTlrTv4ZwV56nt6jGEtR8bKn8iyWDeMA' >>> screen.models.generate_question_key() 'q2aALA7WmvtiKLiGXfNEStpKhOFcNpMDrJ8Y9sv6mwWNsUU6mdgMlgaW5yJJ1yEI' >>> -
'mkvirtualenv' and 'workon' commands
Currently using Ubuntu Bionic Beaver to develop an app. My environment is [git] bash with the Linux installation based in vagrant. Basic commands are being highlighted as not found. However after installing Linux and attempting to setup a new virtual environment, both the commands 'mkvirtualenv' and 'workon' are not recognised as being valid commands. Might anyone know why? -
Performance: Store likes in Postgresql ArrayField (django example)
I have 2 models: Post and Comment, each can be liked by User. 1) For sure, total likes should be rendered somewhere near each Post or Comment 2) But also each User should have a page with all liked content. So, the most obvious way is just do it with m2m field, wich seems will lead to lots of problems in some future. And what about this? 1) Post and Comment models should have some users_liked_ids = ArrayField(models.IntegerField()) 2) User model should also have such fields: posts_liked_ids = ArrayField(models.IntegerField()) comments_liked_ids = ArrayField(models.IntegerField()) And each time User likes something, two actions are performed: 1) User's id adds to Post's/Comment's users_liked_ids field 2) Post's/Comment's id adds to User's posts_liked_ids/comments_liked_ids field The questions are: 1) Is it a good plan?) 2) Will it be efficient to make lookups in such approach to get "Is that Post/Comment` was liked but current user 3) Will it be better to store likes in some separate table, rather then in liked model, but also in ArrayField 4) Probably better stay with obvious m2m? -
Django2 - automatically assign certain amount of cryptocurrency to user signing up
Good morning, We are currently working on a school project where we have to built our own cryptocurrency market. So far so good. Now, when a user registers/signs up on our site he automatically get's a certain amount of one specific cryptocurrency. This is considered as being a transaction between the Bank and the created user. We have our custom sign up form and believe that the code that we need for this feature has to be implemented there, but don't know how this has to be done. Thank you very much for your help Our sign up form in the views.py #signup form def signup(request): if request.method =='POST': form = SignUpForm(request.POST) if form.is_valid(): form.save() #We want to log in the user after his sign up username = form.cleaned_data.get('username') raw_password = form.cleaned_data.get('password1') user = authenticate(username=username, password=raw_password) login(request, user) return redirect('/') else: form = SignUpForm() return render(request, 'sign-up.html', {'SignUpForm': form}) Our transaction model. We use the django user model class Transaction(models.Model): listing_id = models.ForeignKey(Listing, on_delete=models.CASCADE, null=True, blank=True) created_at = models.DateTimeField(auto_now_add = True) exchange_amount = models.IntegerField(null=True) user_debit = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user_debit', null=True) user_credit = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user_credit', null=True) currency_id = models.ForeignKey(Currency, on_delete=models.CASCADE, null=True) -
Django - filter drop down choices based on user group
i am trying to filter a forms drop down list based on the users group to find the user group i am using a custom templatetage template tag from django import template register = template.Library() @register.filter(name='in_group') def in_group(user,group_name): try: group=Group.objects.get(name=group_name) except Group.DoesNotExist: return False return group in user.groups.all() task.html {% load group_check %} <form method="post"> {% csrf_token %} {% if user.is authenticated %} {% if requset.user|in_group:'DEVELOPER' %} #...DO SOMETHING {{ form.as_p }} <button type="submit">add task</button> </form> models GOALS_TYPE= (('DT','Daily Task'), ('WT','Weekly Task'), ('V','Verified'), ('D','Done'), ) class GoalStatus(models.Model): title = models.CharField(max_length=254, null=True) task_id=models.IntegerField(default=1,null=False) description =models.CharField(max_length=254) verified_by=models.ForeignKey('ScrumyUser', on_delete= models.CASCADE, null=True) status=models.CharField(choices=GOALS_TYPE, max_length=2, default='DT') def __str__(self): return self.title the template for the form is based on the forms.py forms.py class ChangeTaskForm(forms.ModelForm): class Meta: model = GoalStatus fields = ('title', 'task_id','description','status', 'verified_by') -
python-saml (OneLogin) equivalent to SimpleSAMLphp filters
I'm wondering whether python-saml library from OneLogin (we use it as an SP) has features semantically similar to processing filters in SimpleSAMLphp (our IdP), as described here and here, for example. The use case for us would be: in an IdP-initiated flow from the different clients, what if the attribute names differ from client to client and our logic depends on certain names of those attributes. For example, client sends in a group name (or role) based on which entitlement decision in our SP are made. Or something similar, i.e. a client has an attribute capitalized which is not the case in our environment. What would be a proper python-saml feature to utilize for remapping of the incoming attributes on a consistent basis. Or should we develop it ourselves to keep the mappings of idiosyncrasies of each client onto our conceptual model? And in the latter case, are there any hooks in the python-saml library that we could utilize (we are Django specific). Thank you in advance. -
Retrieve the integer stored in (?P<topic_id>\d+)
In the urls.py of Django #urls.py url(r'^topics/(?P<topic_id>\d+)/$', views.topic, name='topic') The second part of the expression, /(?P<topic_id>\d+)/, matches an integer between two forward slashes and stores the integer value in an argument called topic_id. I try to understand it with regex In [6]: re.findall(r'topics/(?P<topic_id>\d+)/$', "topics/1/") Out[6]: ['1'] However, when I tried In [7]: re.findall(r'topics/(?P<topic_id>\d+)/$', "topics/1/").topic_id AttributeError: 'list' object has no attribute 'topic_id' It seems that the integer is not stored in topic_id , How to understand it? -
django ListView with a form
I have a CBV that use ListView at first here my views.py class InventoryListView(ListView): context_object_name = 'inventorys' model = models.Inventory and here my template_list.html {% for inventory in inventorys %} <tr> <td>{{ inventory.name }}</td> <td>{{ inventory.sn }}</td> <td>{{ inventory.employee.name }}</td> <td>{{ inventory.desc }}</td> </tr> {% endfor %} it returns all the data as expected. but I need add form with it. and then add some of code to my views.py class InventoryListView(ListView): template_name ='system/inventory_list.html' context_object_name = 'inventorys' model = models.Inventory def get(self, request): form = InventoryForm() return render(request, self.template_name, {'form': form}) def post(self, request): form = InventoryForm(request.POST) and here my forms.py class InventoryForm(forms.ModelForm): name = forms.CharField(max_length=255) sn = forms.DecimalField(max_digits=20, decimal_places=0) desc = forms.CharField(widget=forms.Textarea) employee = forms.ModelChoiceField(queryset=Employee.objects.all(), to_field_name="id") class Meta: model = Inventory fields = ('name', 'sn', 'desc', 'employee') and here my template_list.html {% for inventory in inventorys %} <tr> <td>{{ inventory.name }}</td> <td>{{ inventory.sn }}</td> <td>{{ inventory.employee.name }}</td> <td>{{ inventory.desc }}</td> </tr> {% endfor %} <form method="post" action="{% url 'system:inventory_create' %}"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Submit"> </form> now form working perfectly and checked on my DB its submitted. but list of data not showing like before, because I add: def get(self, request): form = InventoryForm() return … -
Connecting to pgsql from django web app within docker-compose on elasticbeanstalk
I'm running a multi-container app on AWS elastic beanstalk, the app works and connects to my local postgresql db fine while I docker-compose up. But however when I deploy it on elastic beanstalk, there's an error saying File "/usr/local/lib/python3.6/site-packages/psycopg2/__init__.py", line 130, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) django.db.utils.OperationalError: could not translate host name "db" to address: Name or service not known I read some post saying that it's my settings.py in my app directory and that I need to set the 'HOST': 'localhost',to'HOST': 'db', because that is the service the docker-compose.yml is looking for? So here is mysettings.py and my docker-compose.yml file. Please let me know if this is right or if there seems to be any other issue. settings.py: if 'RDS_DB_NAME' in os.environ: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': os.environ['RDS_DB_NAME'], 'USER': os.environ['RDS_USERNAME'], 'PASSWORD': os.environ['RDS_PASSWORD'], 'HOST': os.environ['RDS_HOSTNAME'], 'PORT': os.environ['RDS_PORT'], } } else: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'actualnameofdb', 'USER': 'xxx', 'PASSWORD': '*****', 'HOST': 'db', 'PORT': '5432', } } docker-compose.yml: version: '3' services: db: image: postgres:10.1 environment: - POSTGRES_USER=rdeng - POSTGRES_PASSWORD=walterfedy - POSTGRES_DB=db1 ports: - "5432:5432" volumes: - postgres_data:/var/lib/postgresql/data/ web: #image: rdeng/test:latest build: $PWD environment: - RDS_DB_NAME=db1 - RDS_USERNAME=rdeng - RDS_HOSTNAME=db - RDS_PASSWORD=walterfedy - RDS_PORT=5432 … -
I have installed the `mysqlclient`, why there still get Did you install mysqlclient or MySQL-python? issue
I have installed the mysqlclient in pip3, but I still get this error when I run uwsgi --ini uwsgi: *** Operational MODE: threaded *** django.setup() Traceback (most recent call last): File "/home/ldl/repo/myProject/venv/lib/python3.5/site-packages/django/db/backends/mysql/base.py", line 26, in <module> import MySQLdb as Database File "/home/ldl/repo/myProject/venv/lib/python3.5/site-packages/MySQLdb/__init__.py", line 19, in <module> import _mysql ImportError: No module named '_mysql' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "myProject/wsgi.py", line 19, in <module> django.setup() File "/home/ldl/repo/myProject/venv/lib/python3.5/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/home/ldl/repo/myProject/venv/lib/python3.5/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models() File "/home/ldl/repo/myProject/venv/lib/python3.5/site-packages/django/apps/config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "/usr/local/Python3/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 673, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 665, in exec_module File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed File "/home/ldl/repo/myProject/venv/lib/python3.5/site-packages/django/contrib/auth/models.py", line 4, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "/home/ldl/repo/myProject/venv/lib/python3.5/site-packages/django/contrib/auth/base_user.py", line 52, in <module> class AbstractBaseUser(models.Model): File "/home/ldl/repo/myProject/venv/lib/python3.5/site-packages/django/db/models/base.py", line 124, in __new__ new_class.add_to_class('_meta', Options(meta, app_label)) File "/home/ldl/repo/myProject/venv/lib/python3.5/site-packages/django/db/models/base.py", line 331, in add_to_class value.contribute_to_class(cls, name) File "/home/ldl/repo/myProject/venv/lib/python3.5/site-packages/django/db/models/options.py", line 214, in contribute_to_class self.db_table = truncate_name(self.db_table, connection.ops.max_name_length()) File "/home/ldl/repo/myProject/venv/lib/python3.5/site-packages/django/db/__init__.py", line 33, in … -
django rest framework dynamic "manual" @detail_route declarations
I have some highly repetitive code in my REST declarations, so I decided to inject @detail_route methods instead of re-declaring them over and over. However, between version 3.7.7 of drf and version 3.8.2, something (well, the URL generation functions, that's what) changed and these dynamically added detail routes are no longer registered in the router / rendered into URLs. My code: class SiteTreeViewSet(viewsets.ReadOnlyModelViewSet): ..... def generic_model_rest(model_, field, serfield): @detail_route() def _f(self, request, pk=None): itm = SiteTree.objects.get(pk=int(pk)) serializer = globals()['Settings' + serfield + 'Serializer'] if serfield in ('WWW', 'Oth',): data = serializer(getattr(itm, 'get_sett_' + serfield.lower())(), many=True) else: data = serializer(getattr(itm, 'get_sett_' + serfield.lower())()) return Response(data.data) setattr(SiteTreeViewSet, 'settings_%s' % serfield.lower(), _f) generic_model_rest(SettingsApartment, 'apartment', 'Apt') generic_model_rest(SettingsSwitch, 'switch', 'Swt') generic_model_rest(SettingsWeblinks, 'weblinks', 'WWW') generic_model_rest(SettingsWeblinks, 'weblinks1', 'WW1') generic_model_rest(SettingsOther, 'other', 'Oth') router.register(r'rest/sitetree', SiteTreeViewSet, 'SiteTree') Do I have any other options for "manually" inserting detail routes? -
Is Django right for my project?
I've been working on a web app using Django, and moving to testing it out on Heroku, but I'd like to get some feedback to see if I'm taking the right steps. To simplify it, I have a web app that would have tasks/workers (logic to run, running in parallel), scheduled to execute at a certain time. Right now I have that logic as a view in Django, using the celery framework to run scheduled tasks. My question is: Is Django the best option for running a lot of scheduled tasks/workers at once, for a web app? What are the other options? Thanks! -
Django migrations and docker containers
How does one handle Django migrations when using Docker. For example, using containers in your dev environment, you have a django app and other services, such as a Postgresql db container. Everything is docker pulled and docker-composed up. Voila! Now, you are asked to add features which requires altering the database. No problem in dev. You make some model changes, use makemigrations and migrate and all is looks ok. When pulling your new images to production your migrations don't jive with what's in the persistent db in the django_ tables in prod and you can't run migrations without erroring out. Anyone know how to make all this less painful. -
Vague KeyError during rendering of a Django template
I am getting KeyError: (<repr of django model instance>,) during template rendering with Django 1.11, the traceback shows as the most recent calls _resolve_lookup -> current = current() i.e. a template context is callable and a call to it produces a KeyError, why? I tried digging into django source, but it didn't help me, there is too much switching and procedural semi-magical stuff which is really hard to understand (for me, so no offense for developers of this wonderful framework). The traceback: ERROR exception: Internal Server Error: /alice-in-wonderland-53 Traceback (most recent call last): File ".../site-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File ".../site-packages/django/core/handlers/base.py", line 249, in _legacy_get_response response = self._get_response(request) ... File ".../django_project/books_app/views.py", line 672, in book 'last_context_dict_key': last_context_dict_value, ... File ".../site-packages/django/template/base.py", line 957, in render_annotated return self.render(context) File ".../site-packages/django/template/defaulttags.py", line 315, in render match = condition.eval(context) File ".../site-packages/django/template/defaulttags.py", line 892, in eval return self.value.resolve(context, ignore_failures=True) File ".../site-packages/django/template/base.py", line 708, in resolve obj = self.var.resolve(context) File ".../site-packages/django/template/base.py", line 849, in resolve value = self._resolve_lookup(context) File ".../site-packages/django/template/base.py", line 911, in _resolve_lookup current = current() KeyError: (<Book: Alice in Wonderland>,) I cut the parts which seem unimportant to me (there is just some template rendering recursion etc). -
ModelChoiceFilter not working using django-filter
I am using Django 1.8, I want to list all the merchant using the django_filters, I have two models Shipment and Merchant class Merchant(models.Model): merchant_id = models.CharField(max_length=100,db_index=True,verbose_name='Merchant ID',null=True,blank=True) class Shipment(models.Model): merchant_related = models.ForeignKey(Merchant,on_delete=models.CASCADE,verbose_name="merchant related to shipment") I have the shipments list page with all the shipments and related merchants, I need to add the merchant filter in shipment_list.html with all merchant created ids as choices. filter.py class MerchantFilter(django_filters.FilterSet): merchants = django_filters.ModelChoiceFilter(queryset=Merchant.objects.all()) class Meta: model = Merchant fields = ['merchants'] views.py def search_merchant(request): merchant_filter = MerchantFilter(request.GET,queryset=Merchant.objects.all()) context = { 'filter':merchant_filter } return render(request,"shipment_list.html",context) In shipment_list.html: <div> <form method="get"> {{ filter.form.as_p }} <button type="submit">Search</button> </form> </div> I am getting the search button.But not getting the merchant created ids as choices.Thanks in Advance .. -
adding static() to urlpatterns only work by appending to the list
I'm pretty sure there is a duplicate lying around, but couldn't find it. When declaring a urlpatterns in urls.py on dev, I use the following successfully: urlpatterns = [ # some routes ] urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) Which understandably, works. But if I try the following: urlpatterns = [ # some routes, static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) ] django server dies complaining: ?: (urls.E004) Your URL pattern [<URLPattern '^static\/(?P<path>.*)$'>] is invalid. Ensure that urlpatterns is a list of path() and/or re_path() instances. Why aren't the two definitions equivalent? The return of static() should be the same: return [ re_path(r'^%s(?P<path>.*)$' % re.escape(prefix.lstrip('/')), view, kwargs=kwargs), ] And thus valid, but only works if I concatenate the element to the list instead of defining it in the list directly. Why one method works but not the other? -
Use prefetch_related or prefetch_related_objects to combine a queryset with a a raw queryset
I have an initial queryset: qs = super().get_queryset() I prefetch this using reverse relationship: qs = qs.prefect_related('item'). I have also a raw query: qs2 = Cat.objects.raw('SELECT P.id ... I want to combine qs1 and qs2 (the objects in qs2 have a FK to object in qs1) I tried: qs = qs.prefetch_related(Prefetch('cat',queryset=qs2) gives me an error: 'RawQuerySet' object has no attribute '_iterable_class' Then I tried: prefetch_related_objects(qs, qs2) gives me another error: 'RawQuerySet' object has no attribute 'split' the I made qs2 = list(qs2) and applied again the above line. I get: unhashable type: 'list' -
Run a python file from webpage using CGIHTTPServer
How can I execute a python file that runs selenium webdriver from a webpage using CGIHTTPServer. I am new to programming and all the tutorials I found just print some basic HTML using print("content-type: text\html") in python file. I am using python2.7 and django framework. Links to tutorials, suggestions, steps, setup? I need help, how to do this. Anyone? -
What does this permission-denied error mean?
Error: I tried to put my oTree experiment game in the devserver and this error occours. I do not now, what it means, as it has nothing to do with my code I guess? Request Method: GET Request URL: http://localhost:8000/p/wypb8dnj/Intro/Understanding1/3/ Django Version: 1.11.2 Python Version: 3.6.3 Installed Applications: ['otree', 'django.contrib.auth', 'django.forms', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'channels', 'huey.contrib.djhuey', 'idmap', 'raven.contrib.django.raven_compat', 'radiogrid', 'Intro'] Installed Middleware: ['otree.middleware.CheckDBMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware'] Template error: In template c:\users\welschre\appdata\local\programs\python\python36\lib\site-packages\otree\templates\otree\Base.html, error at line 0 13 1 : {% load staticfiles %} 2 : {% load i18n %} 3 : {% load otree %} 4 : 5 : <!DOCTYPE html> 6 : <html> 7 : <head> 8 : <title>{% block head_title %}{% block title %} 9 : {% endblock %}{% endblock %}</title> 10 : Traceback: File "c:\users\welschre\appdata\local\programs\python\python36\lib\site-packages\otree\views\abstract.py" in dispatch 236. response.render() File "c:\users\welschre\appdata\local\programs\python\python36\lib\site-packages\django\template\response.py" in render 107. self.content = self.rendered_content File "c:\users\welschre\appdata\local\programs\python\python36\lib\site-packages\django\template\response.py" in rendered_content 84. content = template.render(context, self._request) File "c:\users\welschre\appdata\local\programs\python\python36\lib\site-packages\django\template\backends\django.py" in render 66. return self.template.render(context) File "c:\users\welschre\appdata\local\programs\python\python36\lib\site-packages\django\template\base.py" in render 207. return self._render(context) File "c:\users\welschre\appdata\local\programs\python\python36\lib\site-packages\django\template\base.py" in _render 199. return self.nodelist.render(context) File "c:\users\welschre\appdata\local\programs\python\python36\lib\site-packages\django\template\base.py" in render 990. bit = node.render_annotated(context) File "c:\users\welschre\appdata\local\programs\python\python36\lib\site-packages\django\template\base.py" in render_annotated 957. return self.render(context) File "c:\users\welschre\appdata\local\programs\python\python36\lib\site-packages\django\template\loader_tags.py" in render 177. return compiled_parent._render(context) File "c:\users\welschre\appdata\local\programs\python\python36\lib\site-packages\django\template\base.py" in _render 199. …