Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Table appears empty without any value (Django)
My data are like this : 13.2610136284,20.8676059554,11.6376896892,0.51203356592,167,20154.4815106,395,766,56,55047.3477967,-26818.1766435,3072.97868784,12.5402166873,-1443.74556748,-4.0 I need to display it as a table in html This is the function used in python to transform the data suitable for a table import string from datetime import datetime, date def ratio_fil(): ratioFil = open('sergRatiosOut20170426','r') rat = ratioFil.read().split(',') ratioFil.close() return rat Rat is similar to this : ['13.2610136284', '20.8676059554', '11.6376896892', '0.51203356592', '167', '20154.4815106', '395', '766', '56', '55047.3477967', '-26818.1766435', '3072.97868784', '12.5402166873', '-1443.74556748', '-4.0\r\n'] I need to put it in a table, So i create a data_table tags : <tr><td>X</td> <td>{{data_table.0|floatformat:1}} %</td></tr> <tr><td>y</td> <td>{{data_table.1|floatformat:1}} %</td></tr> <tr><td>y1 </td> <td>{{data_table.2|floatformat:1}} </td></tr> <tr><td>y2</td> <td>{{data_table.3|floatformat:1}} </td></tr> In Html : <div> {% with rat as data_table %} {% include 'tags/data_table.html' %} {% endwith %} </div> The table appears empty, i think it should be a method to import rat ? Please i need your help -
sitemap.xml empty for static urls in Django
I have a Django project and I am trying to create a sitemap for my static urls (no Models). However, when running python manage.py runserver and going to http://127.0.0.1:8000/sitemap.xml, I get it empty: <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"></urlset> My code looks like this: #urls.py from main_app.sitemaps import StaticSitemap sitemaps = { 'static': StaticSitemap(), } urlpatterns = [ ... url(r'^sitemap\.xml$', sitemap, {'sitemaps': sitemaps}), ... ] urlpatterns += i18n_patterns( ... ) and #sitemaps.py from django.contrib.sitemaps import Sitemap from django.urls import reverse class StaticSitemap(Sitemap): priority = 0.5 changefreq = 'weekly' i18n = True def location(self, item): return reverse(item) The documentation shows an example with Models and it modifies the function items; but since I do not have, I am not sure if I am missing something there. What am I doing wrong? -
How to send form data from Angularjs to Django
Good evening. I did the application on the sample from this lesson. Here, using DRF, a list of all added games is displayed on the page. I would really like to learn how to write a simple form of adding a new record to the database (two fields: title and description [as in the example]). With js, I'm not very familiar with so far, so I do not know which side to get close to solving the problem. I will be grateful for any help, thanks. -
Django Pyodbc Stored procedure not all arguments converted during string formatting 1- Sql server
I am unable to call STORED Procedure from Django. I am able to call use the STORED Procedure from normal python program. Sample working pythoncode cursor = connect.cursor() params=('IBM','2016') cursor.execute("EXEC SP_Competitor_Extract ?, ? ",params) This piece of code is working fine . But when i am trying to execute from Django it does not working . def index(request): cursor = connection.cursor() try: params=["IBM","2015"] cursor.execute("{call SP_Competitor_Extract (?,?)}",params) while cursor.nextset(): try: results={'results':cursor.fetchall()} break except pyodbc.ProgrammingError: continue This is giving me the error message not all arguments converted during string formatting -
Sort and paginate a list in Django
Is there any way to sort and paginate a list in Django with Python 3.5.4? The only app that works for me in Python 3.5.4 is webstack-django-sorting which only sorts, and it does not work with the native Django pagination. I tried with: linaro-django-pagination (which webstack-django-sorting recommends) django_filter django_pagination -
factoryboy not working with freezegun
simple model(models.py): from django.db import models class MyModel(models.Model): start_date = models.DateField() simple factory(test_factories.py): from datetime import date import factory from .models import MyModel class MyModelFactory(factory.django.DjangoModelFactory): class Meta: model = MyModel start_date = date.today() In manage.py shell: In [1]: from datetime import date In [2]: from freezegun import freeze_time In [3]: from polls.test_factories import MyModelFactory In [4]: date.today() Out[4]: datetime.date(2017, 8, 16) In [5]: with freeze_time(date(1999,9,9)): ...: print(date.today()) ...: m = MyModelFactory() ...: print(m.start_date) ...: 1999-09-09 2017-08-16 current date is 2017-08-16 and fake date is 1999-09-09. Inside freeze_time, date.today() give fake date but factoryboy is not affected by freezegun. It still give real current date. Is this bug? If yes, bug with factoryboy or freezegun? How to solve this? In other words, How to make factoryboy give fake date? (For now, I use MyModelFactory(start_date=date.today()) to create model with fake date.) freezegun version: 0.3.9 factoryboy version: 2.8.1 -
Parse First N Lines of CSV on Model Save
I have a model where users can upload a CSV, however because the files might sometimes be too big, I'd like to parse the first 5 lines of the uploaded CSV and create a new CSV file. This will act as a sample file, that will be smaller and faster to work with later on. This is what my models.py looks like: from django.db import models class Source(models.Model): file = models.FileField() sample = models.FileField(blank=True, null=True) name = models.CharField(max_length=255) def save(self, *args, **kwargs): # I want to parse the 'file' field and write it to 'sample' here super(Source, self).save(*args, **kwargs) def __str__(self): return self.name Basically in the save function of the model, I want to parse the first 5 lines of the file field and take those first 5 lines, create a CSV and upload it to the sample field`. Any ideas on how I can accomplish this? Thanks. -
django timeout file upload
Hey I am trying to do a simple manage.py collectstatic that uploads to s3 which is in the aws china region. The problem I am having is the process stops halfway and then gives this error Traceback (most recent call last): File "/srv/bnn/env/bin/manage.py", line 6, in <module> exec(compile(open(__file__).read(), __file__, 'exec')) File "/srv/bnn/content/scripts/manage.py", line 12, in <module> execute_from_command_line(argv) File "/srv/bnn/env/lib/python3.5/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() File "/srv/bnn/env/lib/python3.5/site-packages/django/core/management/__init__.py", line 355, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/srv/bnn/env/lib/python3.5/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/srv/bnn/env/lib/python3.5/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/srv/bnn/env/lib/python3.5/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 199, in handle collected = self.collect() File "/srv/bnn/env/lib/python3.5/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 139, in collect for original_path, processed_path, processed in processor: File "/srv/bnn/env/lib/python3.5/site-packages/pipeline/storage.py", line 62, in post_process for name, hashed_name, processed in super_class.post_process(paths.copy(), dry_run, **options): File "/srv/bnn/env/lib/python3.5/site-packages/pipeline/storage.py", line 39, in post_process for name, hashed_name, processed in super_class.post_process(paths.copy(), dry_run, **options): File "/srv/bnn/env/lib/python3.5/site-packages/django/contrib/staticfiles/storage.py", line 414, in post_process for post_processed in all_post_processed: File "/srv/bnn/env/lib/python3.5/site-packages/django/contrib/staticfiles/storage.py", line 246, in post_process for name, hashed_name, processed, _ in self._post_process(paths, adjustable_paths, hashed_files): File "/srv/bnn/env/lib/python3.5/site-packages/django/contrib/staticfiles/storage.py", line 312, in _post_process hashed_name = self.hashed_name(name, content_file) File "/srv/bnn/env/lib/python3.5/site-packages/django/contrib/staticfiles/storage.py", line 109, in hashed_name file_hash = self.file_hash(clean_name, content) File "/srv/bnn/env/lib/python3.5/site-packages/django/contrib/staticfiles/storage.py", line 86, in file_hash for chunk in content.chunks(): File "/srv/bnn/env/lib/python3.5/site-packages/django/core/files/base.py", line 76, in chunks self.seek(0) … -
Couldnt import Django when moving whole virutal env from windows to mac
It worked fine between windows OS but not in the mac. I didn't have requirements.txt file but was hoping the virutal envrionment with a lot of libraries imported by two developers would work just fine. runserver generates error couldnt import django. Any ideas? -
Django reuse method in views that extend base template, how to?
I have a header.html (call it base.htm if you like) and the typical "n00b learning to create a Django blog" views for post_list, post_edit and post_detail, all of which extend header.html. In the header view/model there is a slogan that is chosen at random from the DB on page load. This works fine on the main page where post_list.html extends header.html. I want to use the call to "propaganda" (my slogans) in each view without repeating it in every method. I tried creating a method that just included the slogan call and called that method from each view-method, but couldn't get it to work. What am I not understanding? header.html > <!DOCTYPE html> <html lang="en"> <head> <title>Ken Dodd's weblogs</title> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content="Blog site."> <!-- Let's get the static files where we use them, but this could be before the html tag --> {% load staticfiles %} <link rel="stylesheet" href="{% static 'blog/css/bulma.css' %}" type="text/css"/> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"> </head> <body> <section class="hero is-success is-bold"> <div class="hero-body"> <div class="container"> {% block slogan %} {% for propaganda in propagandas %} <h6>{{ propaganda.slogan }} it's</h6> {% endfor %} {% endblock %} <h1 class="title"> <span class="icon"> <i class="fa fa-home"></i> … -
ERROR (no such file) nginx + uwsgi + supervisor + Django
Dears, There is an issue when deploy the Django project by using nginx + uwsgi + supervisor. Everything works fine when using command approach on Ubuntu but failed in supervisord, hope someone can help me through. Works fine with: sudo uwsgi --http :8001 --chdir /home/ubuntu/mysite2 --module mysite2.wsgi Error message when start program in supervisor: root@ip-172-31-9-54:~# sudo supervisorctl -c /etc/supervisord.conf restart mysite2 mysite2: ERROR (not running) mysite2: ERROR (no such file) mysite2_uwsgi.ini: [uwsgi] # Django-related settings #http = :8001 socket = /home/ubuntu/mysite2/mysocket.sock chdir = /home/ubuntu/mysite2 wsgi-file = mysite2/wsgi.py touch-reload = /home/ubuntu/mysite2/reload processes = 2 threads = 4 chmod-socket = 664 chown-socket = ubuntu:www-data vacuum = true /etc/supervisord.conf [program:mysite2] command=/usr/local/bin/uwsgi --ini /home/ubuntu/mysite2/mysite2_uwsgi.ini ; ddd ;process_name=%(program_name)s ; process_name expr (default %(program_name)s) ;numprocs=1 ; number of processes copies to start (def 1) directory=/home/ubuntu/mysite2 ; directory to cwd to before exec (def no cwd) ;umask=022 ; umask for process (default None) ;priority=999 ; the relative start priority (default 999) autostart=true ; start at supervisord start (default: true) startsecs=0 ; # of secs prog must stay up to be running (def. 1) ;startretries=3 ; max # of serial start failures when starting (default 3) autorestart=true ; when to restart if exited after running (def: unexpected) ;exitcodes=0,2 … -
After changing the database from sqlite3 to MySQL of Django, some part of view doesn't work
After changing the database from sqlite3 to MySQL of Django, some part of view doesn't work. my Schedule model class Schedule(models.model): Trainer = models.ForeignKey(settings.AUTH_USER_MODEL,blank=True,null=True, related_name='schedule', on_delete=models.SET_NULL) title = models.CharField(max_length=12,blank=True) start = models.DateTimeField(null=True, blank=True) views.py search_date1 = request.GET.get('search_date','') #get time search_date= datetime.datetime.strptime(search_date1, '%Y-%m-%d') for f in Fitness_list: for s in f.schedule.all(): #to test print(s.title) #some title print(s.start.month) # 8 print(search_date.year) #2017 print(search_date.month) #8 print(search_date.day) #17 sc = f.schedule.filter(start__month=search_date.month) print(sc) There are schedules with start = 2017-08-17, 2018-08-18, etc.. Also, the search_date.month is 8 But, sc = f.schedule.filter(start__month=search_date.month) results nothing. More odd thing is sc = f.schedule.filter(start__year=search_date.year) works well. Only month and day doesn't work. Before changing the database the views worked well. Why doesn't the code filter correctly? -
OperationalError at /admin/login/ FATAL: password authentication failed for user - Django & Postgres &
Heyy, I have been struggling with this for a while now.. I have hosted a website on Digital Ocean using ubuntu, nginx, gunicorn, virtualenv, Postgres and Django and while the site is visible and working, logging into the admin page gives me this error: OperationalError at /admin/login/ FATAL: password authentication failed for user "usr" FATAL: password authentication failed for user "usr" Request Method: POST Request URL: https://www.***.com/admin/login/?next=/admin/ Django Version: 1.11 Exception Type: OperationalError Exception Value: FATAL: password authentication failed for user "usr" FATAL: password authentication failed for user "usr" Exception Location: /***/lib/python3.5/site-packages/psycopg2/__init__.py in connect, line 130 Python Executable: *** Python Version: 3.5.2 Note: for privacy reasons I have replaced the user for postgres with "usr" ,the websites address with "*" and the database name with "db".** The connection is not happening between my Postgres user and Postgres database. When I run:sudo -u postgres psql -U usr db I get the same error. I use environment variables for the passwords as you can see below: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'db', 'USER': 'usr', 'PASSWORD': os.environ["DB_PASSWORD"], 'HOST': 'localhost', } } My environment variables are in the .bashrc file: export DB_PASSWORD="*******" export SECRET_KEY="******************************" when I run the python shell and … -
python-social-auth - failed to login django admin via google authentication
I made a Django application to implement Google 0auth2 service by using python-social-auth package and made as per the official documentation. I successfully made the application and passed the authentication procedure. But, the problem is; after the authentication procedure, the new-user is not logged in. The new-user, the user created by Google auth is visible on Django Admin page under User section. Hope someone can solve my issue. I'm adding my code here. settings.py 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 - unsuitable for production # See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'gq(+ymm#x$*#k)kbz0&6+qpg%o=-q)6_+v!_^&f%q=kgq=*2ks' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'social_django', ] 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', ] ROOT_URLCONF = 'GauthDemo.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['templates', ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'social_django.context_processors.backends', 'social_django.context_processors.login_redirect', ], }, }, ] WSGI_APPLICATION = 'GauthDemo.wsgi.application' # Database # https://docs.djangoproject.com/en/1.11/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, … -
Best way to store Array in a Django Model field (not using postgresql)
What is the best way to store an array in a Django Model Field ? I figure out there is probably a a way to store JSon Data structure in a textfield with method like add_value(), get_array()... Is there a best way to do that? -
Django - Apache Server Error (500) when uploading/saving file
I am attempting to deploy a Django site that has the ability to upload a file and then modify that file. It works 100% on the dev server, however after deploying it with Apache I am running into problems. The Server Error (500) happens on the indicated line in my views.py. What am I doing wrong? My problem is probably not understanding the save() method, however I could not find any info/documentation that helped me. views.py def upload(request): if request.method == "POST": formU = FileUploadForm(request.POST, request.FILES) if formU.is_valid(): f = request.FILES['myFile'] fs = FileSystemStorage() set_file_name(str(f)) fs.save(str(f), f) # where error occurs Since everything works fine under the dev server, I assumed it would be a media file thing but (I think) all looks good there. settings.py MEDIA_ROOT = os.path.join(BASE_DIR, "media/") MEDIA_URL = '/media/' proj.conf Alias /media /home/4rsenal/f_proj/media <Directory /home/4rsenal/f_proj/media> Require all granted </Directory> -
Docker: Access container with python class instance via django application
I am a newbie in docker and ran into a problem that deals with the communication between docker containers: I want to build a docker container that runs an instance of a python class and access this instance via my django application inside my web container. I am running a docker-compose that runs a django application (served through gunicorn) with a postgres database: version: '2' services: # My web application running django and gunicorn web: restart: always build: ./web expose: - "8000" links: - "postgres:postgres" env_file: .env volumes: - ./web:/code - ./web/static:/usr/src/app/static command: /usr/local/bin/gunicorn toolapp.wsgi:application -w 2 -b :8000 --reload # The web server nginx: restart: always build: ./nginx/ ports: - "8084:80" volumes: - /www/static volumes_from: - web links: - "web:web" # The database postgres: restart: always build: ./postgres ports: - "5432:5432" volumes: - ./postgres/data:/var/lib/postgrsql/data By web container makes use of a python class (https://github.com/ch-bu/cohvis/blob/master/web/cohapp/coherenceanalyzer/analyzerenglish.py) that uses spacy (https://spacy.io/) to process texts from a user. As the language models of spacy are very memory intensive I want to build a knew spacy container with an instance of the class and access this instance via my web container. The reason behind this restructuring is that these language models have to be … -
dynamically load data in django modal for each table cell
Okay I have tried asking this question before but I haven't gotten much help and I think its because I've been framing it the wrong way. So I'm going to give it one more try. Please bear with me as I am still a pretty novice developer. So here is my problem: I am passing data from the view into the template as context which is being populated into a table for viewing. To make it more consolidated and easier to view I am truncating the data in the table. However, to give the user full access to the data I want to display the full data in modal popup window. However, the modal is only loading data for the first row in the table and displaying that for every other row in the table. Here is my template html: {% if data %} {% for key, value in data %} <tr> <td scope="row">{{ forloop.counter }}.</td> <td> <div id="popup"> <p class="citation" data-hover="{{ value.2 }}">{{ value.1 }} <img src='{% static "img/expand-icon2.png" %}' id="expand"></p> <a class="article" target="_blank" href={{ value.3 }}>{{ value.2 }}</a> </div> </td> {% if value.4 %} <td class='test'>{{ value.4 }}<a href='#' id="trigger_{{ forloop.counter }}"><img src='{% static "img/expand-icon2.png" %}' id="expand"></a> {% … -
Paginator Mixin unknown inputs?
I'm just starting with Django so I have a lot of questions. I've built a Mixin to paginate a GCBV (ListView): class PageLinksMixin: page_kwarg = 'page' def _page_urls(self, page_number): return "?{pkw}={n}".format(pkw=self.page_kwarg, n=page_number) def previous_page(self, page): if page.has_previous(): return self._page_urls(page.previous_page_number()) return None def next_page(self, page): if page.has_next(): return self._page_urls(page.next_page_number()) return None def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) page = context.get('page_obj') if page is not None: context.update({'previous_page_url': self.previous_page(page), 'next_page_url': self.next_page(page)}) return context Everything seems to work. But I can simply not see where some of the inputs for functions were created. Especially "page", "page_number". With a CBV it would be necessary to declare: page = paginator.page(page_number) But in the GCBV this is apparently unnecessary which means the attribute is created somewhere and later inherited. For the ListView there is a function def paginate_queryset but in there page is only declared in a local scope not a global scope. Can somebody explain this to me? I'm really confused and trying to figure this out for a while now. This is the View: class TagList(PageLinksMixin, ListView): template_name = 'organizer/tag_list.html' paginate_by = 5 model = Tag -
Group by day and aggregate count
I want count the records group by date. Here is my model from django.db import models class MemberProfile(models.Model): imc = models.CharField(max_length=50, null=True, db_index=True) # Anonymous mac address content = models.TextField(null=True) # TODO Remove null=True # pyrad shoot pin_value = models.CharField(max_length=30, null=True) # pyrad shoot created_at = models.DateTimeField(auto_now_add=True) As is: I use very primitive technique. Just iterate over the day in the month. MemberProfile.objects.filter(created_at__date=date(2017, 8, 1)).count() Requirements: --------------------- |Count | created_at | --------------------- | 10 | 2017-07-31| | 17 | 2017-08-01| | 8 | 2017-08-01| | ... | ... | --------------------- Question: 1. How can I archive the same think with single ORM query without outer loop? -
How to execute external command in jenkins which in docker
I pulled the official jenkins from dockerhub and run it with: docker run --name jenkins -p 8080:8080 -p 50000:50000 -v /var/www/jenkins:/var/jenkins_home -u root jenkins And then I added new execution shell in build: python3.6 manage.py collectstatic --noinput But it inform me that "python3.6" not found in build result. Is there any way to execute external docker command? Or what's the best practice for django + jenkins in docker? -
Django: ValidationError using is_authenticated and logout when authenticating from an external source
I am currently building a Django application that gets all its data from an external source (via HTTP). I therefore do not want to use my own database. I have already implemented my own user and remote user backend as per the solution stated in this SO question: Django users and authentication from external source. I am using signed cookies for storing sessions. After implementing the above stated, I was able to login without any errors. However, on checking whether a user is authenticated in a template (or when trying to log him out in a view), I receive an error: ValidationError at /products/ ["'None' value must be an integer."] at the line in the template {% if user.is_authenticated %} where request.user is passed as a template variable user in the corresponding view (I know I shouldn't do that, it's just temporary). Here is some of the other relevant traceback: /home/ines/.virtualenvs/diet/lib/python3.6/site-packages/django/contrib/auth/middleware.py in <lambda> request.user = SimpleLazyObject(lambda: get_user(request)) ... /home/ines/.virtualenvs/diet/lib/python3.6/site-packages/django/contrib/auth/middleware.py in get_user request._cached_user = auth.get_user(request) ... /home/ines/.virtualenvs/diet/lib/python3.6/site-packages/django/contrib/auth/__init__.py in get_user user_id = _get_user_session_key(request) ... /home/ines/.virtualenvs/diet/lib/python3.6/site-packages/django/contrib/auth/__init__.py in _get_user_session_key return get_user_model()._meta.pk.to_python(request.session[SESSION_KEY]) The error happens in the to_python() call, where the line 942 in file django/db/models/fields/__init__.py: return int(value) throws an Exception as it receives value='None'. … -
How should I add category in template?
Models: class Category(models.Model): name = models.CharField(max_length=20) slug = models.SlugField(max_length=200, unique=True ) def __unicode__(self): return self.name class Post(models.Model): title = models.CharField(max_length = 100) content = models.TextField(max_length = 600, default = 'cool' ) date_of_creating = models.DateTimeField(auto_now=False, auto_now_add=True) image = models.ImageField( upload_to=upload_location, null=True, blank=True, height_field="height_field", width_field="width_field" ) height_field = models.IntegerField(default=0) width_field = models.IntegerField(default=0) category = models.ForeignKey('Category') slug = models.SlugField(unique=True, blank=False) def __unicode__(self): return self.title Views: def category(reguest, slug): category = Category.objects.get(slug=slug) post = Post.objects.filter(category=category) html = 'category.html' context = { 'category': category, 'post': post, } return render(reguest, html, context) def listofposts(request): query_set_list = Post.objects.all() context = { "list" : query_set_list, } html = 'base.html' return render(request, html, context) I dont know what should I write in template to filter my posts by categories. I need to choose category and display posts of this category. How can I filter it by category? -
Django Authentication and Login Issue with Class Based Views
I am trying to achieve two different views: one for registration purpose and one for login purpose. Now, the registration process works perfectly but the authentication process does not. Here's the code: in forms.py the first form called UserForm is used to sign up users, the second form called LoginForm is used to log in users. from django.contrib.auth.models import User from django import forms class UserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput) class Meta: model = User fields = ['first_name', 'last_name', 'username', 'email', 'password'] class LoginForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput) class Meta: model = User fields = ['username', 'email', 'password'] in views.py from django.shortcuts import render, get_object_or_404, redirect from .models import Step, Cycle, Program, MotorSetting, GeneralSetting from django.views import generic from django.views.generic.edit import CreateView, UpdateView, DeleteView from django.core.urlresolvers import reverse_lazy from django.contrib.auth import authenticate, login from django.views.generic import View from .forms import UserForm from .forms import LoginForm class UserFormView(View): form_class = UserForm template_name = 'programs/registration_form.html' # display blank form def get(self, request): form = self.form_class(None) return render(request, self.template_name, {'form': form}) #process form data def post(self, request): form = self.form_class(request.POST) if form.is_valid(): #storing the data but NOT SAVING them to db yet user = form.save(commit=False) #cleaning and normalizing data username = form.cleaned_data['username'] password = form.cleaned_data['password'] … -
How to overriding model save function when using factory boy?
I'm using Factory Boy for testing a Django project and I've run into an issue while testing a model for which I've overridden the save method. The model: class Profile(models.Model): active = models.BooleanField() user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE, related_name='profiles') department = models.ForeignKey(Department, null=True, blank=True) category_at_start = models.ForeignKey(Category) role = models.ForeignKey(Role) series = models.ForeignKey(Series, null=True, blank=True) status = models.ForeignKey('Status', Status) def save(self, *args, **kwargs): super(Profile, self).save(*args, **kwargs) active_roles = [] active_status = [] for profile in Profile.objects.filter(user=self.user): if profile.active: active_roles.append(profile.role.code) active_status.append(profile.status.name) self.user.current_role = '/'.join(set(active_roles)) if 'Training' in active_status: self.user.current_status = 'Training' elif 'Certified' in active_status: self.user.current_status = 'Certified' else: self.user.current_status = '/'.join(set(active_status)) self.user.save() super(Profile, self).save(*args, **kwargs) ### <-- seems to be the issue. The factory: class ProfileFactory(f.django.DjangoModelFactory): class Meta: model = models.Profile active = f.Faker('boolean') user = f.SubFactory(UserFactory) department = f.SubFactory(DepartmentFactory) category_at_start = f.SubFactory(CategoryFactory) role = f.SubFactory(RoleFactory) series = f.SubFactory(SeriesFactory) status = f.SubFactory(StatusFactory) The test: class ProfileTest(TestCase): def test_profile_creation(self): o = factories.ProfileFactory() self.assertTrue(isinstance(o, models.Profile)) When I run the tests, I get the following error: django.db.utils.IntegrityError: UNIQUE constraint failed: simtrack_profile.id If I comment out the last last/second 'super' statement in the Profile save method the tests pass. I wonder if this statement is trying to create the profile again with the same ID? …