Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to load test file upload using apache bench, written in django.
I am accessing the file using request.FILES in django views. def upload_file(request): upload_files = request.FILES.getlist('myfile') ... How to load test this particular case using apache bench? I checked online for some help but it's mentioned to pass data in a post.txt file to ab command. I tried it and couldn't make it work. Any solution for this? -
in inlineformset_factory, can't change widget of primary model(django 2.0)
I have 2 models class WorkOrder(models.Model): work_order_id = models.AutoField(db_column='Work_order_id', primary_key=True) work_order_number = models.CharField(db_column='Work_order_number', max_length=50, blank=True, null=True) work_order_date = models.DateField(db_column='Work_order_date', blank=True, null=True) customer = models.ForeignKey(Customer, db_column='Customer_id', blank=True, null=True,on_delete=models.CASCADE) description = models.CharField(db_column='Description', max_length=50, blank=True, null=True) completed_date = models.DateField(db_column='Completed_date', blank=True, null=True) completed = Bit1BooleanField(db_column='Completed', editable=False,default=0) class Meta: managed = False db_table = 'work_order' class WorkOrderItem(models.Model): work_order_item_id = models.AutoField(db_column='Work_order_item_id', primary_key=True) # Field name made lowercase. work_order = models.ForeignKey(WorkOrder, models.DO_NOTHING, db_column='Work_order_id') # Field name made lowercase. part = models.ForeignKey(Part,db_column='Part_id', blank=True, null=True,on_delete=models.CASCADE) # Field name made lowercase. quantity = models.IntegerField(db_column='Quantity', blank=True, null=True) # Field name made lowercase. class Meta: managed = False db_table = 'work_order_item' I am using a formset in forms.py WorkOrderFormSet = inlineformset_factory(WorkOrder, WorkOrderItem, # fields='__all__' # widgets={'work_order_date' : DateInput(attrs={'type': 'datetime'}),}, form=WorkOrderForm, extra=3, can_delete=False) I want to add a widget for work_order_date in Workorder table.When I add it inside WorkOrderFormset, it shows an error that WorkOrderItem does not have that particular field. So I tried adding form=WorkOrderForm and adding Widget there as:- class WorkOrderForm(forms.ModelForm): class Meta: model = WorkOrder fields = '__all__' widgets={'work_order_date': DateInput(attrs={'type': 'datetime'}),} But there is no change when it is displayed in the web page. The view is:- class CreateWorkOrderItem(CreateView): model=WorkOrder fields=['work_order_number','work_order_date','customer','description'] success_url=reverse_lazy('WorkOrder:WorkOrderPending_list') def get_context_data(self, **kwargs): print("from get_context_data") data = super(CreateWorkOrderItem, β¦ -
arnangodb and django database connection issue
I am facing issue when I try to connect arnagodb using Django framework.It throws below error, django.core.exceptions.ImproperlyConfigured: 'arangodb_driver' isn't an available database backend. Try using 'django.db.backends.XXX', where XXX is one of: 'mysql', 'oracle', 'postgresql', 'sqlite3' -
Implement update method on a Nested Serializer in Django 1.11 and django _rest framework
I Implemented a class based view in the views.py though when I tried to update an employee I realized that it's like I'm trying to create new one yet I have the PUT method defined. I have have an issue updating the user details since user field is a Foreign key. A user with that username already exists. Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only. views.py class EmployeeDetailView(APIView): permission_classes = [AllowAny] # queryset = Employee.objects.all() # serializer_class = EmployeeSerializer """ Retrieve, update or delete a employee instance. """ def get_object(self, pk): try: return Employee.objects.get(pk=pk) except Employee.DoesNotExist: raise Http404 def get(self, request, pk, format=None): employee = self.get_object(pk) serializer = EmployeeSerializer(employee) return Response(serializer.data) def put(self, request, pk, format=None): employee = self.get_object(pk) serializer = EmployeeSerializer(employee, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) serializers.py class EmployeeSerializer(serializers.ModelSerializer): user = UserSerializer() contract_type = ContractSerializer(read_only=True) company = CompanySerializer(read_only=True) job_title = JobSerializer(read_only=True) department = DepartmentSerializer(read_only=True) skill = SkillSerializer(read_only=True) unit = UnitSerializer(read_only=True) class Meta: model = Employee fields = ['id', 'user', 'hr_number', 'contract_type', 'company', 'tax_id_number', 'joining_date', 'job_title', 'skill', 'unit', 'department', 'identification_number', 'is_manager', 'active'] -
In this case, How to set uwsgi.ini?
I will use uwsgi on AWS EC2 service. I structured my server's workflow like this. Internet - ElasticLoadBalancer-a - webserver-nginx - ElasticLoadBalancer-b - web-application-django_uwsgi_server - RDS So between webserver-nginx and web-application-django_uwsgi_server, There will be communication through http data. Also you should know that I run web-application-django_uwsgi_server on a docker container. Like, docker run --name django_uwsgi -p 8080:8000 djangoproject_and_uwsgi:1.0 And I set uwsgi ini file like this. uwsgi.ini in docker container: [uwsgi] chdir = /sampledir wsgi-file = /sampledir/sample/wsgi.py master = true processes = 10 # cron = -5 -1 -1 -1 -1 /path/to/some/script harakiri=20 max-requests=5000 vacuum = true enable-threads = true single-interpreter = true lazy-apps = true # From this line, I ask these below options. http = 0.0.0.0:8000 # the socket (use the full path to be safe # socket = /path/to/your/project/mysite.sock # chmod-socket = 664 I'm newbie in linux and network, but heard that socket settings will be better than just setting like http = 8000. Because of http overheads. But I had webserver-nginx on another EC2 instance. In other words, webserver-nginx and web-application-django_uwsgi_server are not on the same EC2 instance(machine). QUESTION: In this case, How can I set socket or port settings appropriately? -
Access class based view from a method
I have a class based view in a model. And I want to access it from a view method. class GetAjaxViewUser(): def dispatch(self, request, *args, **kwargs): return super().dispatch(request, *args, **kwargs) And this is in a model. And, I want to access it from a view method, something like this: def AjaxView(request): return GetAjaxViewUser.as_view() -
django modelform self.instance chaned
I'm making user-information page. In the view I pass the request.user to form like this form = UserForm(request.POST, instance=request.user) The problem is when I save the form with form.save(), username is changed and I have checked self.isntance In UserForm than I found that the self.instance.username in the save()method is changed , but not in the field's clean method(clean_username()) and The form subclassβs clean()method. self.instance.username is only changed in the save()method. I have another field with Usermodel like email field, but only username field is changed. Any advise or clue is good for me Here is my code view @login_required(login_url='/member/login') def change_user_info(request): if request.method == 'POST': form = UserForm(request.POST, instance=request.user) if form.is_valid(): form.save() update_session_auth_hash(request, form.instance) return redirect('/member/change-user-info') else: form = UserForm(instance=request.user) context = { 'form': form, 'home_button': True } return render(request, 'member/user_info.html', context) model class User(AbstractUser): username = models.CharField(max_length=50, unique=True) email = models.EmailField() USERNAME_FIELD = 'username' EMAIL_FIELD = 'email' form class UserForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) field_list = ['username', 'email'] for field in field_list: self.fields[field].required = False new_password1 = forms.CharField( required=False, widget=forms.PasswordInput( attrs={ 'autofocus': True, 'id': 'userinfo-new-password1', 'class': 'form-control', 'placeholder': 'μ λΉλ°λ²νΈ', 'aria-describedby': 'newpassword1HelpBlock', }), ) new_password2 = forms.CharField( required=False, widget=forms.PasswordInput( attrs={ 'autofocus': True, 'id': 'userinfo-new-password2', 'class': 'form-control', 'placeholder': β¦ -
Separate processes for Dockerfile for dev and prod?
I have a project with the following structure. ProjectName/ βββ Dockerfile βββ api/ β βββ Dockerfile β βββ manage.py βββ docker-compose.yml βββ frontend/ β βββ Dockerfile β βββ build/ β βββ src/ βββ manifests/ βββ development.yml βββ production.yml docker-compose.yml has a database image that's common between both environments, and the dev.yml and prod.yml have similar but slightly different images for production and dev. Example: The api dev uses django and just runs python manage.py runserver, but in prod it will run gunicorn api.wsgi. And the frontend runs npm start but in prod I want it to be based off a different image. Currently the dockerfile only works with one or the other, since the npm command is only found when I use FROM node and the nginx command only shows up when I use FROM kyma/docker-nginx. So how can I separate these out when in different environments? ./frontend/Dockerfile: FROM node WORKDIR /app/frontend COPY package.json /app/frontend RUN npm install EXPOSE 3000 CMD ["npm", "start"] # Only run this bit in production environment, and not anything above this line. #FROM kyma/docker-nginx #COPY build/ /var/www #CMD 'nginx' ./api/Dockerfile: FROM python:3.5 RUN apt-get update \ && apt-get install -y --no-install-recommends \ postgresql-client \ && β¦ -
How can i add input field class(bootstrap class) "form-control" to {{form.as_p}}?
How can i add input field class(bootstrap class) "form-control" to {{form.as_p}} ?? <form class="form-inline" action="" method="post">{% csrf_token %} <div class="row"> <div class="col-sm-4"></div> <div class="col-sm-6 "> {{form.as_p}} <br> <input type="submit" class="btn btn-success" value="OK" /> <a href="/login/home"> <input type="button" class="btn btn-success" value="HOME" /> </a> </div></div> </form> -
Opening an HTML page with pre checked checkboxes
I am trying to open my HTML page with checked checkboxes if they were checked on the page prior to opening the current one. My current code is as follows: {% if job.activism %} checkbox?????? {% endif %} <br><input type="checkbox" name="activism" value="Yes">Activism & advocacy My backend is django and my front end is HTML. Thanks -
django get_absolute_url on search result
I am building board web application on Django=1.11 and try to figure out its search query. I have following url.py, models.py, 'views.py` and structures structure blog--- blog | |- urls.py | |- setting.py | |- boards |- models.py |- views.py |- templates |- search.html urls.py url(r'^search/$', boards_views.search_list, name="search"), url(r'^boards/(?P<pk>\d+)/$', TopicListView.as_view(), name="board_topics"), url(r'^boards/(?P<pk>\d+)/topics/(?P<topic_pk>\d+)/$',PostListView.as_view(), name="topic_posts"), models.py class Board(models.Model): name = models.CharField(max_length=50) class Topic(models.Model): subject = models.CharField(max_length=255) board = models.ForeignKey(Board, related_name='topics', on_delete=models.DO_NOTHING) views = models.PositiveIntegerField(default=0) class Post(models.Model): tag = models.CharField(max_length=300) message = models.CharField(max_length=1000, default="") topic = models.ForeignKey(Topic, related_name='posts', on_delete=models.DO_NOTHING) def get_absolute_url(self): return reverse("blog:topic_posts", args=[self.id]) views.py class TopicListView(ListView): model = Topic context_object_name = 'topics' template_name = 'boards/topics.html' paginate_by = 5 def get_context_data(self, **kwargs): kwargs['board'] = self.board return super().get_context_data(**kwargs) def get_queryset(self): self.board = get_object_or_404(Board, pk=self.kwargs.get('pk')) queryset = self.board.topics.order_by('-last_updated').annotate(replies=Count('threads') - 1) return queryset def search_list(req): Post_list = Post.objects.all() topic = Topic.objects.all() q = req.GET.get('q', '') if q: post_list = post_list.filter(post__icontains=q) context = { "filter" : post_list, "q" : q, "topics": topic, } return render(req, "search.html", context) search.html {% if q %} {% for post in filter %} <a href="{{ post.get_absolute_url }}">{{ post.topic }}</a> I have search function in my web application and once I conduct search it displays search result. I am trying to insert link β¦ -
User has no profile
This is my first question on this website,if there is something in a wrong way,please excuse me.And if there are some more specific to show,please contact me,thanks.I just run my Django program,and there is something wrong.I have searched it for a long time, but I can not fix it.When I trun to the detail page,the wrong occurs. The error message is belowοΌ models.py class UserProfile(models.Model): belong_to = models.OneToOneField(to=User, related_name='profile',on_delete = models.CASCADE) profile_image = models.FileField(upload_to='profile_image') view.py def detail(request, id): context = {} vid_info = Video.objects.get(id=id) voter_id = request.user.profile.id like_counts = Ticket.objects.filter(choice='like', video_id=id).count() try: user_ticket_for_this_video = Ticket.objects.get(voter_id=voter_id, video_id=id) context['user_ticket'] = user_ticket_for_this_video except: pass context['vid_info'] = vid_info context['like_counts'] = like_counts return render(request, 'detail.html', context) -
Looking solutions for performing full text search with low memory cost
I wrote a web application using Django to display products information. My database (MySQL) contains ~200000 records ( fields: brand, name, and img). I want to add a search function to my app (the search is performed on brand and name fields), I tried haystack with Whoosh, but I found it cost a lot of memory. Can anyone suggest a way to do it? The application is expected running on a cheap AWS EC2 (small memory). -
GeoDjango - LayerMapping: An error occurred in the current transaction. You can't execute queries until the end of the 'atomic' block
I am using LayerMapping to add a shapefile into the database. Here is the code I am using. The shapefile is ~100MB so there are a bunch of polygons to add. mapping = {'name': 'OBJECTID', 'poly': 'POLYGON'} lm = LayerMapping(TestGeo, 'toronto geo/PROPERTY_BOUNDARIES_WGS84.shp', mapping) lm.save(verbose=True) After running the above code, I'd see about 10 seconds of success message, showing something like Saved: 'name': 12345. Then 10 seconds later, the console would keep showing the message: Failure to save: {'name': 12345, 'POLYGON': (....)} An error occurred in the current transaction. You can't execute queries until the end of the 'atomic' block. It still keeps running after displaying the error message (I'm guessing it moved onto the next polygon object). After it goes through each polygon, despite the fact that the first couple hundred or so polygons showed a success message, none of the polygons from the shapefile were saved. I came across a similar error but the content doesn't seem to be related. Any idea why this is happening? -
how to return string for model class which its own field has choices in Django
I have a simple model class as follow: class Lang(models.Model): various_languages=( ('english','english'), ('french','french'), ) language = models.CharField(max_length=48, choices= various_languages) def __str__(self): return self.language I added the model to the admin as follow: from django.contrib import admin # Register your models here. from .models import Lang class LangAdmin(admin.ModelAdmin): pass admin.site.register(Lang, LangAdmin) I expect to have the language as string in the table on the admin page since I used the function: def __str__(self): return self.language but what I get is (Lang object) demonstrated on the table. How can I solve this. any suggestion or help is appreciated. Note: I use Django 1.11.4 version, Python3.6.5, mysql 5.7.22 -
all: unable to get repr for <class 'django.db.models.query.QuerySet'>
I am using Python3.6 and django 2.0.2, and developing a website for user search in Pycharm. I want to use a legacy database which called User, and had data saved automatically from other source, I won't change the database during the website interaction. Firstly, I configure the database in settings.py as following: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), }, 'legacy_db': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'name', 'USER': 'user', 'PASSWORD': 'pass', 'HOST': 'host', 'PORT': '3306', } } Then I use the inspect db to create the model file, the command is as following: python manage.py inspectdb --database legacy_db > models.py and the generated models.py is as following: from django.db import models class User(models.Model): username = models.CharField(max_length=16) email = models.CharField(max_length=255, blank=True, null=True) password = models.CharField(max_length=32) create_time = models.DateTimeField(blank=True, null=True) id = models.IntegerField(primary_key=True) def __str__(self): return self.username class Meta: managed = False db_table = 'user' After that, I used makemigrations appname and migrate appname to migrate the database. Then I call the model in my views.py as following: all = User.objects.all() I don't know how to get the traceback, I can only see the error info in debugging mode, the error is showing as all: unable to get repr for β¦ -
Updating and deleting multiple images using Formset in Django
I am new to Django so please forgive any silly mistakes. I have made a post with multiple images using FBV. it works perfectly fine and does its job of adding multiple images to a post. Now I am working on editing the Post however I am having issues with editing the post I get the below error. AttributeError at /posts/gangsters/edit/Scarface-the-story-of-Al-Capone/ 'tuple' object has no attribute '_committed' Request Method: POST Request URL: http://127.0.0.1:8000/gangsters/edit/Scarface-the-story-of-Al-Capone Django Version: 1.11 Exception Type: AttributeError Exception Value: 'tuple' object has no attribute '_committed' A brief description of my models Lets say I am trying to make this web-app that allows users to write about Gangsters (more like the post model)from around the world and from different time periods. There are 2 models. Gangsters and GangMembers. GangMember has a foreign_key to Gangster my models are as below class Gangster(models.Model): user = models.ForeignKey(User, related_name='posts') gangster_name = models.CharField(max_length=250, unique=True) slug = models.SlugField(allow_unicode=True, unique=True) history = models.TextField() gangster_image = models.ImageField() # there are more attributes like "Post-like but ignoring them as they are not relevant here" def save(self, *args, **kwargs): self.slug = slugify(self.title) #for SEO on google searches super().save(*args, **kwargs) class Gangmember(models.Model): gangster = models.ForeignKey(Gangster, on_delete=models.CASCADE, related_name="ganglord") gangmember_image= models.ImageField(upload_to='images/', blank=True, β¦ -
Djangotables2 form data to update html table
I've tried every ajax tutorial I can find, three days in and I can't get it. I want to update a simple HTML table with updated list object. Currently, every appended list/table is output to a new template page; I either want the table refreshed in the same template window (index) or in the same (initial) popup tab (roll). I've tried placing my html table in the index template and followed corresponding ajax tutorial(s) as well but no dice. Any help is appreciated. index.html ... <form action="roll.html" method="post" target="_blank"> {# Renders Custom Table #} {% csrf_token %} <div style="margin-left: 10%"> {% render_table table1 %} </div> <div class="button_align"> <input type="submit" value="Submit Files"> </div> </form> <script language="JavaScript"> function toggle(source) { checkboxes = document.getElementsByName('selection'); for(var i in checkboxes) checkboxes[i].checked = source.checked; } </script> ... urls.py ... url(r'^admin/', admin.site.urls), url(r'^$', custom_table), url(r'^$', index, name='index'), url('clear_session', clear_sesh, name='clear_sesh'), url('roll', roll_view, name='roll_view') ... views.py ... # view function - assigned to page roll.html def roll_view(request): if request.method == "POST": ... return render(request, 'roll.html', {'final_joblist': final_joblist}) -
Getting a module error what exists - Synapse_pay_rest | django
I have a django project that I have build. I am integrating the synapse_pay_rest api into my project. I downloaded the api on to my local machine an when I try to run my code I get an error with my code that has to do with the api. Does anyone know why this error is coming. The client and user that is important from the api should not be causeing any type of error. Here is the the error: nhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x10c764158> Traceback (most recent call last): File "/Users/omarjandali/anaconda3/lib/python3.6/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/Users/omarjandali/anaconda3/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 113, in inner_run autoreload.raise_last_exception() File "/Users/omarjandali/anaconda3/lib/python3.6/site-packages/django/utils/autoreload.py", line 248, in raise_last_exception raise _exception[1] File "/Users/omarjandali/anaconda3/lib/python3.6/site-packages/django/core/management/__init__.py", line 327, in execute autoreload.check_errors(django.setup)() File "/Users/omarjandali/anaconda3/lib/python3.6/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/Users/omarjandali/anaconda3/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/omarjandali/anaconda3/lib/python3.6/site-packages/django/apps/registry.py", line 89, in populate app_config = AppConfig.create(entry) File "/Users/omarjandali/anaconda3/lib/python3.6/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/Users/omarjandali/anaconda3/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line β¦ -
Templates mixed up. Acquiring view from another template. Django
I am new to coding in general. After taking a Python and Django developer bootcamp class in Udemy, I started building a simple website with a blog based on what I learned. Everything seems to be working fine except on one particular view on the blog - the Drafts view. I used class based views with one html template as base which extends to all my htmls. What's happening is the Drafts view which lists all draft posts is supposed to look a little different from the Published view which lists all of the published posts. But it seems that the Drafts view seems to be acquiring the view of the Published posts. For example - the Draft is supposed to list all the drafts with the "Created date" instead of the "Published date". The weird thing is that it's displaying the correct items - all the drafts but it's showing the published date instead of the created date. I also made like a sub navigation bar which is supposed to look different on the Drafts but it's displaying the one for the Published posts. Clearly, something is mixed up and I think this is a unique issue. Could you β¦ -
How to Preserve the Validity of Django Template Code in BeautifulSoup
I am trying to operate on some Django templates using Beautiful Soup. In some cases, when I put html that contains Django code through a BeautifulSoup instance, soup outputs invalid Django code: from bs4 import BeautifulSoup django_string = '<a href="{% url "some_url" %}">' soup = BeautifulSoup(django_string, 'html.parser') print(soup) <a %}"="" href="{% url " some_url"=""> # expected <a href="{% url "some_url" %}"> I also tried using the html5lib and lxml parsers. The lxml parser's output is slightly different than above, but still invalid. Is there any way use Beautiful Soup to output valid Django template code, or have I reached the limits of what it is designed to do? -
Transferring front end data from HTML checkboxes to backend django in forms.py/views.py/urls.py
I have a bunch of checkboxes on my HTML page and want to store whether a checkbox was ticked or not in backend django. My current HTML code is: <input type="checkbox" name="activism" value="Yes">Activism & advocacy I don't know how to modify my forms.py/urls.py/views.py to store whether a particular checkbox was ticked or not. Thank you very much. -
Dockerized Django REST Application and PostgreSQL DB
Is there any way that I do not need to change my settings.py file every time i decide to run my application ? What I mean is this: -Every time I want to run dockerized application with docker-compose my settings.py file looks like this: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'agent_technologies_db', 'USER': 'stefan_radonjic', 'PASSWORD': 'cepajecar995', 'HOST': 'db', 'PORT': '', } } -And every time i want to run my application on my local machine my settings.py looks like this: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'agent_technologies_db', 'USER': 'stefan_radonjic', 'PASSWORD': 'cepajecar995', 'HOST': 'localhost', 'PORT': '', } } Is there any way around this? Here is what my docker-compose.yml file looks like: version: '3' services: db: image: postgres environment: - POSTGRES_USER=stefan_radonjic - POSTGRES_PASSWORD=cepajecar995 - POSTGRES_DB=agent_technologies_db web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/agent-technologies ports: - "8000:8000" links: - db depends_on: - db -
Django - table renders a blank row from query set
I have a model named Season and a model named Game: # Season class Season(models.Model): teams = models.ManyToManyField('Team', related_name='season_teams', blank=True) current = models.BooleanField(default=False) year = models.PositiveIntegerField( validators=[ MinValueValidator(2018), MaxValueValidator(datetime.datetime.now().year)], help_text="Use the following format: <YYYY>", null=True, blank=True) session = models.CharField(max_length=100, null=True, blank=True) class Meta: ordering = ['year', 'session'] def __str__(self): session = self.session year = str(self.year) season = session + " " + year return season # Game class Game(models.Model): field_choices = FIELD_CHOICES team_choices = TEAM_CHOICES season = models.ForeignKey(Season, on_delete=models.CASCADE) home_team = models.CharField(max_length=100, null=True, blank=True, choices=team_choices) away_team = models.CharField(max_length=100, null=True, blank=True, choices=team_choices) field = models.CharField(max_length=100, choices=field_choices, null=True) date = models.DateTimeField(null=True, blank=True) score = models.CharField(max_length=5, null=False, blank=True, default='') tbd = 'TBD' win = 'W' draw = 'D' loss = 'L' result_choices = ( (tbd, 'TBD'), (win, 'W'), (draw, 'D'), (loss, 'L'), ) result = models.CharField( max_length=3, choices=result_choices, default=tbd, ) class Meta: ordering = ['home_team', 'away_team', 'field','score', 'result'] def __str__(self): return str(self.date) def __unicode__(self): return u'%s' % self.name I have a view Season which queries both models successfully: # Season class Season(generic.ListView): model = SeasonModel template_name = 'team/season.html' def get_queryset(self): qs1 = SeasonModel.objects.filter(current=True) qs2 = GameModel.objects.all().order_by('date') queryset1 = sorted(chain(qs1)) queryset2 = sorted(chain(qs2),key=attrgetter('home_team')) result = queryset1 + queryset2 return result And then a template β¦ -
Django - 'for' statements should have at least four words: for choice question_set.all
everything's cool? It's my first question, english is not my native language so please take it easy on me hahahaha Ok, so here is the problem, I believe it's a ident... idk how to say it in english but anyway, structural problem. What's happening: I'm learning following the tutorial and in my localhost website almost everything is running clean but when I decide to "vote" on a "Question", it leads to a error page. Here's the traceback (the final line): django.template.exceptions.TemplateSyntaxError: 'for' statements should have at least four words: for choice question_set.all and where the error (I believe) is placed, my "/results.html" file: <h1>{{ question.question_text }}</h1> <ul> {% for choice question_set.all %} <li>{{ choice.choice_text }} -- {{ choice.votes }} vote{{ choice.votes|pluralize }}</li> {% endfor %} </ul> <a href="{% url 'polls:detail' question.id %}">Vote again?</a> Thanks for everything! hope it's understandable. (: