Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
psycopg2.ProgrammingError: column "data" of relation "WorldBank_projects" does not exist
I'm working on a Django application which fetches JSON data from an API and stores it in PostgreSQL database. But while migrating the app I'm getting these errors: psycopg2.ProgrammingError: column "data" of relation "WorldBank_projects" does not exist LINE 1: INSERT INTO "WorldBank_projects" ("data", "project_id", "pro... What should I change in code to resolve this error? Here's the traceback: Traceback (most recent call last): File "/python/lib/python3.6/site-packages/django/db/backends/utils.py", line 65, in execute return self.cursor.execute(sql, params) psycopg2.ProgrammingError: column "data" of relation "WorldBank_projects" does not exist LINE 1: INSERT INTO "WorldBank_projects" ("data", "project_id", "pro... ^ The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() File "/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 355, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/python/lib/python3.6/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/python/lib/python3.6/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/app/aggregator/WorldBank/management/commands/fetch_wb.py", line 53, in handle project_abstract = data['project_abstract'] File "/python/lib/python3.6/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/python/lib/python3.6/site-packages/django/db/models/query.py", line 394, in create obj.save(force_insert=True, using=self.db) File "/python/lib/python3.6/site-packages/django/db/models/base.py", line 807, in save force_update=force_update, update_fields=update_fields) File "/python/lib/python3.6/site-packages/django/db/models/base.py", line 837, in save_base updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) File "/python/lib/python3.6/site-packages/django/db/models/base.py", line 923, in _save_table … -
TemplateDoesNotExist at /music/album/2/
Index.html code {% extends 'music/base.html' %} {% block body %} My Albums {% if all_albums %} {% for album in all_albums %} {{ album.album_title }} {{ album.artist }} View Details {% csrf_token %} {% cycle '' '' '' '' '' '' %} {% endfor %} {% else %} Add an Album {% endif %} {% endblock %} url.py code from django.conf.urls import url from . import views app_name='music' urlpatterns = [ #/music/ url(r'^$', views.Indexview.as_view(), name='index'), #/music/123/ url(r'^(?P<pk>[0-9]+)/$', views.Detailview.as_view(), name='detail'), url(r'album/add/$', views.AlbumCreate.as_view(), name='album-add'), url(r'album/(?P<pk>[0-9]+)/$', views.AlbumUpdate.as_view(), name='album-update'), url(r'album/(?P<pk>[0-9]+)/delete/$', views.AlbumDelete.as_view(), name='album-delete'), -
Django data handling in custom middleware
In my django webapp, I have to pass user data param(udp) in a request and return the same in response without modifying it in view. Request { "mobile": "111111111", "udp":[ { "key": "keyName", "value":"valueName" }, { "key": "keyName", "value":"valueName" }, ] } Response { "code": "200", "message": "success message", "response": { "data":"user data" "udp":[ { "key": "keyName", "value":"valueName" }, { "key": "keyName", "value":"valueName" } ] } } I thought of acheiving this by writting custom middleware but after accessing request in middleware, View is throwing me error you cannot access body after reading from request's data stream Can anyone suggest how this can be implemented? or What will be best approach of doing this in django -
How do I track user behaviour/Activity on my website?
I'm working on a big Django project think of it like all social networks combined. I wanted to create a recommendation system and I realised I need data. I'm wanna use Cassandra for this task using Django Cassandra engine but I really don't know what should be the structure of the data should it be like and how do I store it. my biggest concerns are How the data should look like (the structure of unstructured data) Eh. user 4679 most used hashtags Users 5753 visits:- User 123's profile 6 times User 986's profile 34 times User likes post User commented on post contains Keywords Etc etc etc How do I store the data -
Django QuerySet not appearing in HTML file for PythonAnywhere Web App
I'm having a bit of trouble with this part of the DjangoGirls tutorial (about templates). Currently, my website is at chocoberrie.pythonanywhere.com. It's supposed to show a few posts inside the QuerySet, but the list is empty, and I don't know why (or how to fix it). 1) The QuerySet isn't loading at all in the HTML file. I followed the steps to import the Post model into views.py and add the QuerySet in the posts variable (the previous part of the tutorial). When I tried putting {{ posts }} in the HTML file (post_list.html), nothing appears in the QuerySet that loads on the page. 2) I don't know how to edit the database file on PythonAnywhere. This database file is supposed to be separate from the local db.sqlite3 on my computer (since db.sqlite3 is in the .gitignore file, it's not committed). I read about this here. I understand that this is useful to keep production changes from being displayed on the live website, but how I supposed to have this data on the PythonAnywhere side? What file am I supposed to edit on PythonAnywhere? Thanks for the help, I appreciate it! Here are my local files: urls.py from django.conf.urls import … -
Django 1.11.7: How do I call a method from a Class in Views?
In my models.py I have a Class (Paths) with a method, validate_time that uses the two properties of the Paths model (time_start, time_end): class Paths(m.Model): time_start: m.TimeField() time_end: m.TimeField() def validate_time(self): start = self.time_start end = self.time_end #some function that returns True or False How do I call this method of the Paths class in my views.py? This is what I'm trying: from .models import Paths def paths_data(request): valid_times = Paths.validate_timeslot() if valid_times == False: -
Django selectdatewidget how to render manually?
I'm trying to render a selectdatewidget in django out manually so I can customise with bootstrap. However I'm not clear on how I render out the indvidual inputs with the selectdatewidget? class ProfileForm(forms.Form): first_name = forms.CharField(max_length=30) last_name = forms.CharField(max_length=30) eighteen_years_from_now = (datetime.datetime.now().year - 18) date_of_birth = FieldBuilder(User, 'date_of_birth', widget=SelectDateWidget( years=range(eighteen_years_from_now, 1919, -1))) template to render an individual field: <div class="form-group"> <label for="{{ field.id_for_label }}" class="sr-only"> {{ field.label }} </label> {% if form.is_bound %} {% if field.errors %} {% render_field field class="form-control is-invalid" %} {% for error in field.errors %} <div class="invalid-feedback"> {{ error }} </div> {% endfor %} {% else %} {% render_field field class="form-control is-valid" %} {% endif %} {% else %} {% render_field field class="form-control" placeholder=field.label %} {% endif %} {% if field.help_text %} <small class="form-text text-muted">{{ field.help_text }}</small> {% endif %} </div> -
ValueError: invalid literal for int() with base 10: ' ' [Django]
I'm working on a Django application which fetches JSON data from an API and stores it in PostgreSQL database. But while migrating the app I'm getting this error: ValueError: invalid literal for int() with base 10: '' What should I change in code to resolve this error? Here's the traceback: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() File "/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 355, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/python/lib/python3.6/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/python/lib/python3.6/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/python/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 204, in handle fake_initial=fake_initial, File "/python/lib/python3.6/site-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 "/python/lib/python3.6/site-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 "/python/lib/python3.6/site-packages/django/db/migrations/executor.py", line 244, in apply_migration state = migration.apply(state, schema_editor) File "/python/lib/python3.6/site-packages/django/db/migrations/migration.py", line 129, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/python/lib/python3.6/site-packages/django/db/migrations/operations/fields.py", line 87, in database_forwards field, File "/python/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 415, in add_field definition, params = self.column_sql(model, field, include_default=True) File "/python/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 155, in column_sql default_value = self.effective_default(field) File "/python/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 229, in effective_default default = field.get_db_prep_save(default, self.connection) File "/python/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 770, in get_db_prep_save prepared=False) File "/python/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 762, in get_db_prep_value value = self.get_prep_value(value) … -
Pickle database independent query in Django
First of all, I know that my question duplicate this question. But I supose it's not the same. I need to save user "search filter". As I understand Django ORM create specific SQL query for different DB. So if I save SQL query I can't migrate on other database with different SQL syntax. Am I wrong? If no, how can I save Django side of query, without accsesing to DB? -
Django 1.9.1 - make migrations can't detect changes
I have Django 1.9.1 installed: >>> django.__version__ '1.9.1' And I had my model defined in main.models: from __future__ import unicode_literals from django.db import models class Collection: name = models.CharField(max_length=1024) desc = models.TextField() snap = models.ImageField() f = models.FileField() def __str__(self): return self.name; And I had already added "main" to INSTALLED_APPS in settings: INSTALLED_APPS = [ 'main', ... # Other Django stuff ] And when I run python manage.py makemigrations I get the following: ➜ python manage.py makemigrations No changes detected I've searched through the internet and it seems like no one has encountered a problem like this... Any help will be greatly appreciated!! Thanks! -
TypeError at /admin/login/ can't multiply sequence by non-int of type 'tuple'
I don't believe it's my code, but something in django? My project works on other machines, but I'm getting a particular error on one: TypeError at /accounts/login/ can't multiply sequence by non-int of type 'tuple' Exception Location: C:\Python34\lib\sitepackages\mysql\connector\django\operations.py in bulk_insert_sql, line 223 Python Executable: C:\Python34\python.exe Python Version: 3.4.4 The method: def bulk_insert_sql(self, fields, num_values): items_sql = "({0})".format(", ".join(["%s"] * len(fields))) return "VALUES " + ", ".join([items_sql] * num_values) Has anyone ran into something like this before? Is it a certain python version, dependencies, or my machine? -
type object 'RadioSelect' has no attribute 'renderer'
I am trying to do a radioselect horizontal align and I am receiving the following error message:type object 'RadioSelect' has no attribute 'renderer' What I am doing wrong? from django.utils.safestring import mark_safe class HorizontalRadioRenderer(forms.RadioSelect.renderer): def render(self): return mark_safe(u'\n'.join([u'%s\n' % w for w in self])) class ApprovalForm(forms.Form): approval = forms.ChoiceField(choices=APPROVAL_CHOICES, initial=0, widget=forms.RadioSelect(renderer=HorizontalRadioRenderer), ) -
sorl thumbnail migrate no effect
I wanna use sorl.thumbnail django app for generating thumbnails in my site. I wanna use sorl.thumbnail django app for generating thumbnails in my site. I followed the guide and I added 'sorl.thumbnail' to INSTALLED_APPS. Also I gonna use the default key-value store, so I need to run python manage.py migrate command, but this doesn't do anything, it doesn't create the required data base table. I also tried python manage.py makemigrations first, still nothing, and tried also python manage.py makemigrations sorl.thumbnail and python manage.py makemigrations sorl.thumbnail. Whats going on? How can I migrate and add the required table in order to use default key-value store? -
Pycharm Django url issues
I have a question related to using Django in Pycharm. I don't know why every time I made a url in urlplattern for my project and this url would not work unless I restart my computer. I did not use virtual environment for my project. -
Django UpdateView - can't see errors in second form
I have model UserProfile which has field: languages = models.ManyToManyField('profiles.Language', through='UserProfileLanguage') The through model: class UserProfileLanguage(models.Model): userprofile = models.ForeignKey('UserProfile', ) language = models.ForeignKey('Language') level = models.CharField(max_length=50, choices=settings.USERPROFILE_LANGUAGE_LEVEL_CHOICES) class Meta: unique_together = ('userprofile','language') I'm trying to create an "update profile" page. I figured out how to add formset and everything works correctly except errors. I don't see errors when there are in the formset (not the UserProfileForm). Do you know how to make it work? The problem is probably in the post method. class UserProfileUpdateView(LoginRequiredMixin, UpdateView, ): model = UserProfile form_class = UserProfileUpdateForm template_name = 'profiles/profile/userprofile_update.html' def get_object(self, queryset=None): if self.request.user.is_authenticated(): return self.request.user.userprofile def get_context_data(self, **kwargs): context = super(UserProfileUpdateView,self).get_context_data(**kwargs) context['language_formset'] = self._get_userprofile_language_formset() return context def _get_userprofile_language_formset(self,POST=None,FILES=None): Factory = inlineformset_factory(UserProfile,UserProfileLanguage,fields=('language','level')) formset = Factory(POST or None,FILES or None,instance=self.request.user.userprofile) return formset def get_success_url(self): return reverse('profiles:profile',args=(self.request.user.userprofile.slug,)) def post(self, request, *args, **kwargs): self.object = self.get_object() formset = self._get_userprofile_language_formset(POST=request.POST,FILES=request.FILES) if formset.is_valid(): formset.save() else: # WHAT TO DO return self.render_to_response(self.get_context_data(formset=formset)) return super(UserProfileUpdateView,self).post(request,*args,**kwargs) -
Wagtail/Django App not serving images using DEFAULT_FILE_STORAGE storage backend
I have a wagtail app and using this guide I've managed to serve static files from an S3 bucket. I am trying to do the same thing for media files, however, changing DEFAULT_FILE_STORAGE and MEDIA_URL seems to have no effect on where uploads are stored, or the URLs rendered by templates. These are the relevant config settings: AWS_STORAGE_BUCKET_NAME = 'bucket-name' AWS_S3_REGION_NAME = 'eu-west-1' AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME MEDIAFILES_LOCATION = 'media' MEDIA_URL = STATIC_URL DEFAULT_FILE_STORAGE = 'home.custom_storages.MediaStorage' STATICFILES_LOCATION = 'static' STATICFILES_STORAGE = 'home.custom_storages.StaticStorage' STATIC_URL = "https://%s/" % AWS_S3_CUSTOM_DOMAIN And custom_storages.py: from storages.backends.s3boto3 import S3Boto3Storage from django.conf import settings class StaticStorage(S3Boto3Storage): location = settings.STATICFILES_LOCATION class MediaStorage(S3Boto3Storage): location = settings.MEDIAFILES_LOCATION Static files are rendered in the admin site with the S3 url, however images still have src=/media/images/... relative urls, and they are uploaded to the host's file system rather than S3. -
Django/Wagtail/taggit - Getting model specific tag list
I have seen this: Generating a unique list of Django-Taggit Tags in Wagtail; and the solutions there have generated a list of all stored tags, i.e. image, document, etc tags. I am trying to accomplish a similar goal. On a News Index Page, have a dropdown of the News Page Tags. I can't seem to get a list of tags that are only News Page Tags, currently this gives me a list of all tags in my site, including image and document tags. from django.template.response import TemplateResponse from modelcluster.fields import ParentalKey, ParentalManyToManyField from modelcluster.tags import ClusterTaggableManager from taggit.models import TaggedItemBase, Tag from core.models import Page class NewsPageTag(TaggedItemBase): content_object = ParentalKey('NewsPage', related_name='tagged_items') class NewsPage(Page): tags = ClusterTaggableManager(through=NewsPageTag, blank=True) class NewsIndexPage(Page): def serve(self, request, *args, **kwargs): context['tags'] = Tag.objects.all().distinct('taggit_taggeditem_items__tag') return TemplateResponse( request, self.get_template(request, *args, **kwargs), context ) I have also tried: from django.contrib.contenttypes.models import ContentType # ... def serve(self, request, *args, **kwargs): news_content_type = ContentType.objects.get_for_model(NewsPage) context['tags'] = Tag.objects.filter( taggit_taggeditem_items__content_type=news_content_type ) return TemplateResponse( request, self.get_template(request, *args, **kwargs), context ) which assigns context['tags'] an empty set My template: {% if tags.all.count %} {% for tag in tags.all %} <a class="dropdown-item" href="?tag={{ tag.id }}">{{ tag }}</a> {% endfor %} {% endif %} HELP! This feels … -
How to customize CSS with django-bootstrap3
Im working on a project in Django that I installed Django-bootstrap3 on. It seems to have installed successfully and is generally working...but I'm not sure how to customize the css with this setup. Can anyone help? -
Django ModelForm with ManyToMany intermediary table
My model UserProfile has field languages: languages = models.ManyToManyField('profiles.Language',through='UserProfileLanguage') Which uses UserProfileLanguage as intermediary table: class UserProfileLanguage(models.Model): userprofile = models.ForeignKey('UserProfile', ) language = models.ForeignKey('Language') level = models.CharField(max_length=50, choices=settings.USERPROFILE_LANGUAGE_LEVEL_CHOICES) class Meta: unique_together = ('userprofile','language') When I create a ModelForm with model UserProfile, it contains multiple choice field for model Language. I would like to force user to specify a level of the language. Is there a built in way or do I have to create formset and override save method? -
ValueError at /admin/login/ - dictionary update sequence element #0 has length 0; 2 is required
I have a django project that I haven't touched in about a month. I have comeback to see an error when trying to connect to any page for the app (including admin login page). The error is: ValueError at /admin/login/ dictionary update sequence element #0 has length 0; 2 is required Here is the full traceback: Environment: Request Method: GET Request URL: http://localhost:8000/admin/login/?next=/admin/ Django Version: 1.11.4 Python Version: 3.6.2 Installed Applications: ['ad_app.apps.AdAppConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "C:\Users\James\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\exception.py" in inner 41. response = get_response(request) File "C:\Users\James\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\base.py" in _get_response 217. response = self.process_exception_by_middleware(e, request) File "C:\Users\James\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\base.py" in _get_response 215. response = response.render() File "C:\Users\James\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\template\response.py" in render 107. self.content = self.rendered_content File "C:\Users\James\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\template\response.py" in rendered_content 84. content = template.render(context, self._request) File "C:\Users\James\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\template\backends\django.py" in render 66. return self.template.render(context) File "C:\Users\James\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\template\base.py" in render 205. with context.bind_template(self): File "C:\Users\James\AppData\Local\Programs\Python\Python36-32\lib\contextlib.py" in __enter__ 81. return next(self.gen) File "C:\Users\James\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\template\context.py" in bind_template 263. updates.update(processor(self.request)) Exception Type: ValueError at /admin/login/ Exception Value: dictionary update sequence element #0 has length 0; 2 is required Here is my settings.py file: import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - … -
Deploy Django-channels with Docker
I'm trying to move my application to Docker. I'm currently using fabric to deploying my Django app. I created a docker-compose file: version: '3' volumes: static-files: services: nginx: image: nginx:latest volumes: - ./deploy/conf/nginx.conf.template:/etc/nginx/conf.d/mysite.template - static-files:/app/static ports: - "80:80" environment: - NGINX_HOST='localhost' command: /bin/bash -c "envsubst '\$NGINX_HOST' < /etc/nginx/conf.d/mysite.template > /etc/nginx/conf.d/default.conf && nginx -g 'daemon off;'" depends_on: - interface redis: image: redis:latest db: restart: always image: mdillon/postgis:9.5 environment: - POSTGRES_USER=production - POSTGRES_PASSWORD=production - POSTGRES_DB=production interface: restart: always build: . working_dir: /app/code/src command: ["../../../wait-for-db.sh", "db", "./interface-entrypoint.sh"] volumes: - static-files:/app/static environment: - DJANGO_SETTINGS_MODULE=restapi.settings.production_settings expose: - "8001" depends_on: - db - redis workerserver: restart: always build: . working_dir: /app/code/src command: ["./worker-entrypoint.sh"] environment: - DJANGO_SETTINGS_MODULE=restapi.settings.production_settings depends_on: - db - redis - interface This docker-compose works fine, I can connect to server and all. So my questions are: How can I use my existing database with Docker setup? I tried using volumes but I can't get it working.. How do you handle migrations and code changes with this setup? With fabric I only did migrate and only restarted workers with supervisor. Here every worker has it's own "code" in container. Would it make sense to somehow share code between containers and make separate container for migrations? … -
Perform subqueries for each day in range
I building a 'airbnb clone' app on Django. The app has a flexible price system. Each landlord-user can save arbitrary number of prices which differ by priority and date range. Here is how it looks like (most of the fields skipped for the sake of simplicity): class PriceBlock(models.Model): price = models.DecimalField() priority = models.CharField(choices=PRIORITY_CHOICES) start_date = models.DateField() end_date = models.DateField() class Flat(models.Model): prices = models.ManyToManyField(related_name='flats') For example User created 3 PriceBlock instances with date values in some random month. p1 - has priority 1, price 100$ and dates from 1 to 3 p2 - has priority 2, price 200$ and dates from 2 to 5 p3 - has priority 3, price 300$ and dates from 4 to 6 To calculate price for flat from 1 to 6 days on this month we need to calculate price of PriceBlock with higher priority on each day. The problem is - I need calculate price for each flat in the ListView of all flats. Here's how I do it: class FlatQueryset(models.QuerySet): ... def with_block_full_price(self, start, end): days = get_days(start, end) # function returns list of days nums prices = {} for num, day in enumerate(days): prices[f'price_{num}'] = Subquery( PriceBlock.objects.filter(flats=OuterRef('pk')) .filter(start_date__lte=day, end_date__gte=day) .order_by('-priority') .values('price')[:1], … -
templatetag: could not parse remainder
I'm greeted with the following error when attempting to follow a books example of templatetags with modification: django.template.exceptions.TemplateSyntaxError: Could not parse the remainder: '% get_list %' from '% get_list %' [17/Nov/2017 09:12:57] "GET /account/requestaccess/?report_id=88&report_id=89 HTTP/1.1" 500 180158 I'm following the instructions of adding templatetags to my app directory and included the init.py and the app_filter.py i'd like to filter on, as such: Security Accounts templatetags app_filter.py __init__.py My app_filter.py is defined as such: from django import template register = template.Library() @register.filter('accounts/requestaccess.html') def get_list(querydict, itemToGet ): return querydict.getlist(itemToGet) My settings.py includes the following: INSTALLED_APPS = [ 'django_python3_ldap', 'django_extensions', 'django_filters', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'accounts', ] TEMPLATE_LOADERS = ( 'django.template.loaders.app_directories.load_template_source', ) My view is passing the array correctly: checkedlist = request.GET.getlist('report_id') I see the array in my console, when doing a print checkedlist: ['75', '76', '77'] My template is the following: {% load app_filters %} {% for reports in retreivecheckbox %} <input type="checkbox" name="report_id" value ="{{reports.report_name_sc}}"> {{ % get_list % }} </div> {% endfor %} -
Adding data to related model (custom user model)
I have a custom User Model. I can successfully add user to it and want to add the relationship to a related model. It gives me no errors but does not link the user to the related field compusers in the company model. Basically I need it to after creating a user, also add the user to the related compusers field. This is the code I am trying in the view: self.object.compusers.add(self.object.id) The Model class Company(models.Model): user = models.ManyToManyField(settings.AUTH_USER_MODEL,related_name='compusers') name = models.CharField(max_length=265, blank=True) tel = models.IntegerField(blank=True, null=True) email = models.EmailField(max_length=265,blank=True) address = models.TextField(blank=True) postal = models.TextField(blank=True) regno = models.CharField(max_length=265,blank=True) vatno = models.CharField(max_length=265,blank=True) def __str__(self): return self.name def get_absolute_url(self): return reverse('nodisoapp:home') The View class AddStaffView(CreateView): form_class = forms.AddStaffMember success_url = reverse_lazy('nodisoapp:home') template_name = "scrty/addstaff.html" def form_valid(self, form): self.object = form.save(commit=False) self.object.password = get_random_string(length=8) self.object.save() self.object.compusers.add(self.object.id) return super(AddStaffView, self).form_valid(form) The form Class AddStaffMember(forms.ModelForm): usrtype = forms.ChoiceField(choices=[('Admin','Admin'),('Manager','Manager'),('Employee','Employee')],label="User Type: See below for descriptions" ) class Meta: model = get_user_model() fields = ("firstname","lastname","email","usrtype") labels = { "firstname": _("First Name"), "lastname": _("Last Name"), "email": _("E-mail"), } -
Django urls.reverse with argument
Stuck on this for a while: in Django pytest I am trying to do req = RequestFactory().get(reverse('app_name:app_view_name')) But I require the url to have '/[number]' at the end so that UpdateView will recognise the number and display appropriate form from model. In the browser the links and form submission all work fine, but I am unable to use reverse() in testing. I have tried: req = RequestFactory().get(reverse('app_name:app_view_name', args=[1])) and req = RequestFactory().get(reverse('app_name:app_view_name'), kwargs=['pk'=1]) but none of these work. I am simply trying to build the url with '/1' added at the end. Any help much appreciated.