Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
error for ImportError: No module named 'PyQt4' in Django
I am working Django app I want to create graph in django view using plot When I import from matplotlib import pylab as plt it thorws an error as below File "/home/akashk/anaconda3/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 985, in _gcd_import File "<frozen importlib._bootstrap>", line 968, in _find_and_load File "<frozen importlib._bootstrap>", line 957, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 673, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 697, in exec_module File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed File "/home/akashk/projects/tutorial/website/urls.py", line 3, in <module> from . import views File "/home/akashk/projects/tutorial/website/views.py", line 21, in <module> from matplotlib import pylab File "/home/akashk/anaconda3/lib/python3.5/site-packages/matplotlib/pylab.py", line 274, in <module> from matplotlib.pyplot import * File "/home/akashk/anaconda3/lib/python3.5/site-packages/matplotlib/pyplot.py", line 114, in <module> _backend_mod, new_figure_manager, draw_if_interactive, _show = pylab_setup() File "/home/akashk/anaconda3/lib/python3.5/site-packages/matplotlib/backends/__init__.py", line 32, in pylab_setup globals(),locals(),[backend_name],0) File "/home/akashk/anaconda3/lib/python3.5/site-packages/matplotlib/backends/backend_qt4agg.py", line 18, in <module> from .backend_qt5agg import FigureCanvasQTAggBase as _FigureCanvasQTAggBase File "/home/akashk/anaconda3/lib/python3.5/site-packages/matplotlib/backends/backend_qt5agg.py", line 15, in <module> from .backend_qt5 import QtCore File "/home/akashk/anaconda3/lib/python3.5/site-packages/matplotlib/backends/backend_qt5.py", line 31, in <module> from .qt_compat import QtCore, QtGui, QtWidgets, _getSaveFileName, __version__ File "/home/akashk/anaconda3/lib/python3.5/site-packages/matplotlib/backends/qt_compat.py", line 124, in <module> from PyQt4 import QtCore, QtGui ImportError: No module named 'PyQt4' I am having PyQt5 with latest version. How can I avoid calling module PyQt4 Thanks -
Multiple keys vs dictionary in memcache?
What is a better approach? Having multiple keys or having a dictionary? In my scenario I want to store songs in a country basis and cache that for further access later on. Below I write the rough pseudocode without disclosing too many details to keep it simple. The actual songs will most probably be IDs from songs in a database. Many keys approach cache.set("songs_from_city1", city1_songs) cache.set("songs_from_city2", city2_songs) .. Dictionary approach cache.set("songs_by_city", { 'city1': city1_songs 'city2': city2_songs .. }) .. -
Can I generate a REST service from a GraphQL schema?
I'd like to build a Django app with both a GraphQL endpoint and a REST API. Maintaining both separately would be too much of a pain; I'm looking for a good way to only maintain the GraphQL service and have the REST endpoints generated automagically. Does anyone know about a good way to do this? I know there are ways to build a GraphQL server on top of REST endpoints, but I'd rather have it the other way around, as the REST API requirement might go away in the future. -
'by_the_time', expected 'empty' or 'endfor'. Did you forget to register or load this tag?
I got an error, TemplateSyntaxError at /app/detail/3/ Invalid block tag on line 23: 'by_the_time', expected 'empty' or 'endfor'. Did you forget to register or load this tag? . I wrote in detail.html like {% load static %} <html lang="en"> <body> <div id="comment-area"> {% for comment in post.comment_set.all %} <div class="media m-3"> <div class="media-body"> <h5 class="mt-0"> <span class="badge badge-primary badge-pill">{% by_the_time comment.created_at %}</span> {{ comment.name }} <span class="lead text-muted">{{ comment.created_at }}</span> <a href="{% url 'blog:recomment' comment.pk %}">REPLY</a> </h5> {{ comment.text | linebreaksbr }} {% for recomment in comment.recomment_set.all %} <div class="media m-3"> <div class="media-body"> <h5 class="mt-0"> <span class="badge badge-primary badge-pill">{% by_the_time recomment.created_at %}</span> {{ recomment.name }} <span class="lead text-muted">{{ recomment.created_at }}</span> </h5> {{ recomment.text | linebreaksbr }} </div> </div> {% endfor %} </div> </div> {% endfor %} </div> </body> </html> in models.py class Comment(models.Model): name = models.CharField(max_length=100, blank=True) text = models.TextField() target = models.ForeignKey(POST, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) I think the number of if-else statement of template tag is correct,and I wrote {% load static %} so I really cannot understand why this error happens.When I deleted <span class="badge badge-primary badge-pill">{% by_the_time comment.created_at %}</span>,the error was also deleted... How should I fix this? -
Django slow server response with file large file upload
Python 3.6 and Django 1.11 I am sending from a client multipart/form-data to a django form, the model looks like class Document(models.Model): name = models.CharField(max_length=300) author = models.CharField(max_length=100) file = models.FileField(upload_to='files/') and i am using class based views class DocumentCreate(CreateView): model = Document form_class = DocumentForm success_url = reverse_lazy('document_list') and a classic ModelForm: class DocumentForm(forms.ModelForm): class Meta: model = Document fields = '__all__' Im on the embedded server, wich i knwow may perform poorly, but when i send a 2gb files with the client, is see that the file is created after ~10 seconds (and databases entries etc..) but the client have to wait 10 more seconds for the django server to send the response (seen with wireshark). I can even keyboardinterupt the client script before the django server answer, with no consequences to the data transmission. Here is the client script in gross: fich = open('2go', 'rb') sess = requests.session() data = {'author': 'gerard', 'csrfmiddlewaretoken': csrftoken, 'name': 'gerard'} sess.post('http://127.0.0.1:8000/post_document', data=data, files{'file': fich}) I got another script which streams the multipart data, but its slower and also have to wait for the server response. So the question is, why is the server answer so slow, although everything is already uploaded … -
Django rest framework: not updating the results immediately
I am using Django 2.0 and Django rest framework 3.7.3. I have updated the published_date field of an object but when i retrieve the list of posts it does not reflect. I think its showing the old results postsclass PostListAPIView(ListAPIView): today = timezone.now() def get_queryset(self): today = timezone.now() articles = Article.objects.all() return articles.filter(publish_date__lte=today).order_by('-publish_date')[:30] serializer_class = PostSerializer class PostSerializer(serializers.ModelSerializer): publish_date = serializers.DateTimeField(format="%Y-%m-%d %H:%M UTC") class Meta: model = Article fields = "__all__" what to do so that the changes are reflected immediately in the api -
Converting pandas dataframe to json is slow
Converting a csv (of 50k rows) to json for eventual consumption by a Django template is quite slow. I was wondering if I was converting it correctly or if there's a better way to do this. First few rows of the csv are: tdate,lat,long,entity 3/6/2017,34.152568,-118.347831,x1 6/3/2015,34.069787,-118.384738,y1 1/1/2011,34.21377,-118.227904,x1 3/4/2013,33.81761,-118.070374,y1 Am reading this csv in views and rendering the request this way: def index(request): df = pd.read_csv('app/static/data.csv') df.tdate=pd.to_datetime(df.tdate) df['Qrt'] = df.tdate.dt.quarter df['Yr'] = df.tdate.dt.year jzon=df.groupby('entity')[['lat','long','Qrt','Yr']].apply(lambda x: x.to_dict('records')).to_json(orient='columns') return render(request, 'app/index.html', {'jzon': jzon}) -
order a child model with respect to parent model in Django
I have Problem and Solution model defined in my models.py. Solution has a foreignkey to the Problem model. That is, a problem can have many solutions. I want to create urls like www.example.com/problem/problem_id/solution/solution_number/ where problem_id describes the primary key of Problem model and solution_number describes the order in which the solution was posted for a particular problem. In other words, if a solution is first solution to a given problem, its order should be 1 and second solution to the same problem gets an order 2. This will allow me to access a solution to particular problem like Solution.objects.get(problem=problem, order=order) -
Cannot query "____": Must be "Article" instance
models.py from django.db import models from django.urls import reverse class ProductCategory(models.Model): name = models.CharField(max_length=128, blank=True, null=True, default=None) is_active = models.BooleanField(default=True) def __str__(self): return '%s' % self.name class Meta: verbose_name = 'Category' verbose_name_plural = 'Categories' class Product(models.Model): name = models.CharField(max_length=128, blank=True, null=True, default=None) description = models.TextField(default=None) processor = models.CharField(max_length=300, blank=True, null=True, default=None) video = models.CharField(max_length=300, blank=True, null=True, default=None) ram = models.CharField(max_length=300, blank=True, null=True, default=None) disk_space = models.CharField(max_length=300, blank=True, null=True, default=None) oS = models.CharField(max_length=300, blank=True, null=True, default=None) video_trailer = models.CharField(max_length=10000, blank=True, null=True, default=None) img = models.CharField(max_length=10000, blank=True, null=True, default=None) category = models.ManyToManyField(ProductCategory, blank=True, default=None) is_active = models.BooleanField(default=True) created = models.DateTimeField(auto_now_add=True) slug = models.SlugField(primary_key=True, max_length=250, unique=True, default=None) def __str__(self): return '%s' % self.name def get_absolute_url(self): return reverse('product', args=[str(self.slug)]) class Meta: verbose_name = 'Game' verbose_name_plural = 'Games' class ProductDownload(models.Model): product = models.ForeignKey(Product, blank=True, null=True, default=None, on_delete=False) link = models.CharField(max_length=10000, blank=True, null=True, default=None) is_active = models.BooleanField(default=True) number = models.PositiveIntegerField(blank=True, default=True) def __str__(self): return '%s' % self.product.name class Meta: ordering = ['number'] class Meta: verbose_name = 'Download Link' verbose_name_plural = 'Download Links' class ProductImage(models.Model): product = models.ForeignKey(Product, blank=True, null=True, default=None, on_delete=False) image = models.CharField(max_length=10000, blank=True, null=True, default=None) is_main = models.BooleanField(default=False) is_active = models.BooleanField(default=True) def __str__(self): return '%s' % self.product class Meta: verbose_name = 'Product Image' verbose_name_plural … -
How to Deploy Django on apache2 server using native python installation ?
I have developed an Django application which uses a python binding for c/C++ based dependency. Now How can I deploy this application without virtualenv using native python installation. My "000-default.conf" <VirtualHost *:80> # The ServerName directive sets the request scheme, hostname and port that # the server uses to identify itself. This is used when creating # redirection URLs. In the context of virtual hosts, the ServerName # specifies what hostname must appear in the request's Host: header to # match this virtual host. For the default virtual host (this file) this # value is not decisive as it is used as a last resort host regardless. # However, you must set it for any further virtual host explicitly. #ServerName www.example.com Alias /static /home/jai/myproject/protocol/static <Directory /home/jai/myproject/protocol/static> Require all granted </Directory> <Directory /home/jai/myproject/pep_learn> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess myproject python-path=/home/jai/myproject:/home/jai/myproject/myprojectenv/lib/python2.7/site-packages WSGIProcessGroup myproject WSGIScriptAlias / /home/jai/myproject/pep_learn/wsgi.py ServerAdmin webmaster@localhost DocumentRoot /var/www/html # Available loglevels: trace8, ..., trace1, debug, info, notice, warn, # error, crit, alert, emerg. # It is also possible to configure the loglevel for particular # modules, e.g. #LogLevel info ssl:warn ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined # For most configuration files from conf-available/, which are # enabled or … -
Step by step with django-jet-demo
I am trying to see django-jet-demo in action, i.e. https://github.com/geex-arts/django-jet-demo, but It didn't work. git clone https://github.com/geex-arts/django-jet-demo.git mkvirtualenv venv cd django-jet-demo pip install -r requirements/base.txt django makemigrations I have the errors 1- configparser.NoSectionError: No section: 'common' If I remove config.get(..., 'common') inside application/settings.py 2- configparser.NoSectionError: No section: 'email' If I remove config.get(..., 'email') inside application/settings.py 3- configparser.NoSectionError: No section: 'database' How could I fix this problem? What are the steps to make django-jet-demo works? Does it work well on your computer? -
Django, when using ForeignKey field, which is better blank=True or null=True?
From: https://docs.djangoproject.com/en/2.0/ref/models/fields/#django.db.models.Field.null Avoid using null on string-based fields such as CharField and TextField. If a string-based field has null=True, that means it has two possible values for “no data”: NULL, and the empty string. In most cases, it’s redundant to have two possible values for “no data;” the Django convention is to use the empty string, not NULL. So What is better on ForeignKey Field? ForeignKey field is not string-based field, isn't it? I wonder what is convention for ForeignKey in django. null=True is better or blank=True is better? In performance, convenience or somewhat anything. -
unique_together with a field from a foreign key in a through table for a ManyToMany relation
I am developing a Django 2.0 project app. It has a (non-working) models.py file, which looks something like this: from django.db import models from django.utils import timezone class Computer(models.Model): name = models.CharField(max_length=25) def __str__(self): return "Computer {}".format(self.name) class Software(models.Model): name = models.CharField(max_length=25) description = models.CharField(max_length=1024, blank=True) def __str__(self): return self.name class SoftwareVersion(models.Model): software = models.ForeignKey(Software, on_delete=models.CASCADE, related_name="versions") version = models.CharField(max_length=100) released_at = models.DateTimeField(default=timezone.now) def __str__(self): return "{} {}".format(self.software, self.version) class ComputerSoftwareBundle(models.Model): computer = models.ForeignKey(Computer, on_delete=models.CASCADE, related_name="bundles") installed_at = models.DateTimeField(default=timezone.now) versions = models.ManyToManyField(SoftwareVersion, through="BundleSoftwareVersion", related_name="bundles") class BundleSoftwareVersion(models.Model): bundle = models.ForeignKey(ComputerSoftwareBundle, on_delete=models.CASCADE) version = models.ForeignKey(SoftwareVersion, on_delete=models.CASCADE) class Meta: unique_together = (("bundle", "version__software"),) The app tracks software bundles currently or previously installed on computers. The thing here is that a bundle should not contain more than one version of the same software. Also, SoftwareVersion should contain a reference to Software, because the same version string has a different meaning for different pieces of software. The code does not work as described in this Stackoverflow answer. I left the unique_together line in to illustrate what I am trying to achieve. I've tried to work around this limitation of Django (not being able to use fields referred to via a foreign key in unique_together) by … -
Validation error (required) in Django ModelForm when using a field that is extra to the Model fields
I have 2 models Company and CompanyLogo. class CompanyLogo(models.Model): company = models.ForeignKey(Company, on_delete=models.CASCADE) logo = models.ImageField(upload_to='st/a') Instead of using CompanyLogo as an inlineformset I want to use it like afield in the CopmanyModelForm. I do this because I need just a specific size of the logo, plus some asyncronus tasks, and I need specific template for the widget. class CompanyModelForm(forms.ModelForm): logo = forms.ImageField(widget=CompanyLogoWidget) class Meta: model = Company fields = ['name', 'short_description', 'description', 'address', 'city', 'zip'] when I save the Company object I save also the logo: def save(self, commit=True): company = super().save(commit=commit) CompanyLogo.objects.update_or_create(company=self.company, defaults={"logo": self.fields['logo']}) The logo field is mandatory/required to save the Company form and be an image. The issue is that even if the field is completed(added a file), I get a validation error "This fields is required". I suppose the error happens because the field is not in the Company Model, and this is why he doesn't see the value. -
Customize updated|timesince in a django template
I've a django template which displays the last time an element was updated in a database like this: <small>updated {{ updated|timesince }} ago</small> where updated is the timestamp of the last update of that element. I, however, don't like thw way it is displaying this information. For example if i's just updated it sais: 'updated 0 minutes ago' which looks kinda wierd. I would like it to say something like: 'updated just now' So I wrote this piece of code to try to make that happen: {% if is_updated%} {% if updated|timesince == '0 minutes' %} <small>updated just now </small> {% else %} <small>updated {{ updated|timesince }} ago</small> {% endif %} {% endif %} here is_updated is a context variable set like this: if element.updated != element.uploaded: is_updated = True however it's always showing me 'updated X minutes ago' even if the element hasn't been updated. What could I be doing wrong? Model for the element: title = models.CharField(max_length=120) identifier = models.SlugField(blank=True, null=True) category = models.CharField(max_length=120, default="uncategorized") description_short = models.CharField(max_length=300, default="none") description = models.TextField(default="none") uploaded = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) time = models.IntegerField() -
Wagtail customizing struct block template on admin
I have read the 'custom-editing-interfaces-for-structblock' section of documentation. Then I have written: settings = StructBlock([ ('width', blocks.CharBlock(required=False, max_length=20 ) ), ('background_color', blocks.CharBlock(max_length=10, required=False)) ], form_template = 'personal_web/admin_blocks/section_settings.html' ) I have copied the code in wagtail/admin/templates/wagtailadmin/block_forms/struct.html to my custom struct template for better customizing. On the admin there is an error: 'builtin_function_or_method' object is not iterable... In template /Users/burakk/BurakWorks/Web/VIRTUAL_ENVIRONMENTS/python3.6.1_dj_1_11/lib/python3.6/site-packages/wagtail/wagtailadmin/templates/wagtailadmin/block_forms/sequence_member.html, error at line 23 By the way I am using jinja as template renderer, django 1.11.6, python 3.6 -
Django Heroku App not compatible with buildpack
Sorry about bad English first. I'm trying to push my existing django project to heroku, and i try to use heroku-django-template to modify my django project. My interpreter(or compiler?) is Python 2.7.14 and I didn't use virtual env. But after a whole day of trying, i only got this error repeatly: remote: -----> App not compatible with buildpack: https://codon-buildpacks.s3.amazonaws.com/buildpacks/heroku/python.tgz remote: More info:https://devcenter.heroku.com/articles/buildpacks#detection-failure remote: remote: ! Push failed remote: Verifying deploy... remote: remote: ! Push rejected to py-mosaic-image. remote: To https://git.heroku.com/py-mosaic-image.git ! [remote rejected] master -> master (pre-receive hook declined) here's my dictionary: -- .git/ -- my-project/ ---- some-app-dir/ ---- some-app-dir/ ---- my-project/ ---- __init__.py ---- .env ---- db.sqlite3 ---- manage.py ---- Pipfile ---- Pipfile.lock ---- Procfile ---- requirements.txt ---- runtime.txt and here's some code( many are generated by heroku-django-template ) .env WEB_CONCURRENCY=2 Pipfile (ignore some \r) [[source]] url = "https://pypi.python.org/simple" verify_ssl = true name = "pypi" [requires] python_version = "2.7" [packages] dj-database-url = "==0.4.2" django = "==2.0" gunicorn = "==19.7.1" "psycopg2" = "==2.7.3.2" whitenoise = "==3.3.1" [dev-packages] Procfile web: gunicorn py-mosaic-image.wsgi --log-file - requirements.txt attrs==17.4.0 autobahn==17.10.1 Automat==0.6.0 backports.functools-lru-cache==1.4 constantly==15.1.0 cycler==0.10.0 Django==1.8.18 django-socket-server==0.0.4 django-socketio==0.3.9 gevent==1.2.2 gevent-socketio==0.2.1 gevent-websocket==0.10.1 greenlet==0.4.12 gunicorn==19.7.1 hyperlink==17.3.1 incremental==17.5.0 matplotlib==2.1.0 numpy==1.13.3 olefile==0.44 Pillow==4.3.0 PyAudio==0.2.11 pyparsing==2.2.0 python-dateutil==2.6.1 pytz==2017.3 scipy==1.0.0 six==1.11.0 … -
Django form error:local variable 'context' referenced before assignment
I'm collecting data from form, processing data(right now I'm not) and displaying the result on the same HTML page from where the user submits the form. Here is my views.py file: def index(request): template = 'predictor/index.html' if request.method =='POST': form = EvalForm(request.POST) if form.is_valid(): text ='thank you for submitting form' else: text='something wrong.' context: { 'text':text, } return render(request,template,context) else: form = EvalForm() return render(request,template) Here is my index.html file <form method="POST" action="{% url 'predictor' %}"> {% csrf_token %} //all input fields including submit button here </form> <div class="result"> {{ text }} </div> All other things like urls are configured properly. What I'm doing wrong here? -
uWSGI -> Logstash Connectivity Troubleshooting
I run a Django application(NGINX+uWSGI) in a Docker container and the following configurations are used in uwsgi.ini to connect to the logstash(It has both TCP and UDP port opened). logger = file:/var/log/uwsgi_server.log logger = socket:192.168.0.167:5591 But the logstash never receives any log messages from UWSGI based on the above configuration. The logs are being populated in the configured log file. Moreover, I can telnet to the configured host/port inside the container and I can see the test log messages in the logstash which I gave in the terminal. Is there any way to troubleshoot it further? -
Dynamic querying for tagulous (django)
I'm using tagulous and have 2 sets of tags on my model e.g. class MyModel(models.Model): primary_tags = TagField(to=ActionToolTreeTag, blank=True, null=True, related_name='primary') secondary_tags = TagField(to=ActionToolTreeTag, blank=True, null=True, related_name='secondary') class ActionToolTreeTag(TagTreeModel): class TagMeta: protected = True This works fine. However, on my admin frontend I have a querybuilder (Jquery QueryBuilder) and want to query the tags. It creates queries in json. I need to convert these queries to use the django ORM to pull out the model instances that fit the query. I've tried adapting a recursive script I found that looks like this: def build_query(self, json_query): if 'condition' in json_query.keys(): if json_query['condition'] in ['AND', 'OR']: if json_query['condition'] == 'AND': qop = 0 else: qop = 1 resultq = None for rule in json_query['rules']: q = self.build_query(rule) if q != None: if resultq == None: resultq = q else: if qop == 0: resultq = resultq & q elif qop == 1: resultq = resultq | q else: if json_query['operator'] == 'equal': cmd = 'exact' elif json_query['operator'] == 'contains': cmd='in' else: cmd = '' field_name = json_query['field'] kwname = str("%s%s%s" % (field_name, '__', cmd)) if json_query['operator'] == 'contains': kwdict = {kwname : [json_query['value'],]} else: kwdict = {kwname : json_query['value']} resultq = Q(**kwdict) … -
Displaying the objects from my class on the base template in Django
Sorry if my english is confusing I created a class Button on my app menu models.py (App 'menu') from django.db import models class Button(models.Model): button_name = models.CharField(max_length=30, verbose_name='xxx') button_dirurl = models.CharField(max_length=40, verbose_name='xxx') button_corequise = models.BooleanField(default=False, verbose_name='xxx') def __str__(self): return self.button_name What I would like to do is to display all the objects into base.html, located into the template at the root. I tried to do a tag, but I would like to add some html elements and as far as it goes I won't be able to do much menu_tags.py (App 'menu') from django import template from menu.models import Button register = template.Library() @register.simple_tag def show_menu(): a = Button.objects.all() return a I'm sorry if this was already asked but I don't know how to google this as my english is quite bad. Thanks ! -
Display URLS as links(Higlight, blue color, clickable etc) in Django Text Area Field
I have a site where users can post stuff (mainly links with comments.) Now when I render the text area filed, the links are being displayed as plain text. They are not clickable, blue links. I want to render identified urls as links which are clickable. Don't suggest a language or syntax in which the user has to prepend something to make it a link. Instead I want an automatic way for links to be clickable. Like how SO and SE and other forums do it. -
Using Sql Server with Django 2.0
I would like to use Django 2.0 with legacy MS SQL Server database. Latest information regarding usage Django with MS SQL Server i could find is Using Sql Server with Django in production/These days and it is about Django 1.11 Most supported seems django-pyodbc-azure but it's not supporting Django 2.0 yet: django-pyodbc-azure issue #124 Is there any alternative? -
Django Test: TypeError: __init__() got an unexpected keyword argument
I get the error from the ProductTestCase: ...setUp department = DepartmentForm(department_name_text=self.department_name) ... ...in __init__ super(DepartmentForm, self).__init__(*args, **kwargs) TypeError: __init__() got an unexpected keyword argument 'department_name_text' It would be great to know how to fix this issue and why it only occurs when on Foreign keys. I have added in Department test as well, it works fine. Thank you for your time. Department Test class DepartmentTestCase(ModelTestCase): def setUp(self): super(DepartmentTestCase, self).setUp() self.department_form = self.get_department_form(department_name_text=self.department_name) def test_valid_input(self): self.assertTrue(self.department_form.is_valid()) Product Test class ProductTestCase(ModelTestCase): @classmethod def setUpTestData(cls): super(ProductTestCase, cls).setUpTestData() def setUp(self): super(ProductTestCase, self).setUp() self.product_data = {'barcode_text': self.barcode } department = DepartmentForm(department_name_text=self.department_name) department_inst = None if department.is_valid(): department_inst = department.save(commit=False) department_inst.pk = None department_inst.save() maker = MakerForm(maker_name_text=self.maker_name) maker_inst = None if maker.is_valid(): maker_inst = maker.save(commit=False) maker_inst.pk = None maker_inst.save() self.product_data.update({'name_text': department_inst, 'from_maker': maker_inst}) def test_valid_input(self): product_form = ProductForm(**self.product_data) self.assertTrue(product_form.is_valid()) Department Form class DepartmentForm(ModelForm): field_names = {'department_name_text': 'Department Name'} class Meta: model = Department fields = ['department_name_text'] def __init__(self, *args, **kwargs): super(DepartmentForm, self).__init__(*args, **kwargs) for field, name in self.field_names.items(): self.fields[field].label = name -
Django: Problems regrouping a regroup
I'm trying to get a list of countries that are stored in my Post model. Models: Articles App: class Post(models.Model): title = models.CharField(max_length=100, unique=True) ... country_slug = models.ManyToManyField(Country_Data, related_name='nation_slug') Nation App: class Country_Data(models.Model): name = models.CharField(max_length=250) country_slug = models.CharField(max_length=250) View: get_context_data: self.sport = get_object_or_404(Sport, sport_slug=self.kwargs['sport_slug']) context['country'] = Post.objects.filter(post_category=self.sport) Template: {% for nation in country %} <ul> {% regroup nation.country_slug.all by name as country_list %} {% for country in country_list %} <li>{{ country.grouper }} <ul> {% for item in country.list %} <li>{{ item.name }}</li> {% endfor %} </ul> </li> {% endfor %} </ul> {% endfor %} The problem I'm having is looping through the list of countries and only pulling out one result. Currently, because of how it needs to be set up, it is pulling out one country per news article, which is obviously not useful for this because I'll end up with hundreds of duplicates. I cant work out how to get it to loop through the Post model, pull out all the "country_slug" fields, then regroup that into a list of unique countries. I've read through the documentation and a few other questions multiple times, I'm just failing to understand exactly what I'm doing wrong.