Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Jinja2 Multi-level template inheritance issue
I have the following three files in a Django App, with the template engine being Jinja2 skeleton.html <head> {% block head_content %} <meta charset="utf-8"> <title> {% if page_title %} {{ page_title }} | {% endif %} Bhargavi Books & Stationery </title> <link rel="stylesheet" href="{{ static("css/semantic.min.css") }}"> <link rel="stylesheet" href="{{ static("Icons/font-awesome.min.css") }}"> {% endblock head_content %} </head> <body> <div id="navigation"> {% block navigation %} <div class="ui three item menu"> <a class="active item">Home</a> <a class="item">New Bill</a> <a class="item">View Bills</a> </div> {% endblock navigation %} </div> <div id="frame"> {% block frame_content %} <p> Body content goes here. Body for {{ content_name }}</p> {% endblock frame_content %} </div> <div id="app"> {% block app_content %} <p> APP content goes here. Body for {{ content_name }}</p> {% endblock app_content %} </div> {% block scripts %} <script src="{{ static("js/jquery.js") }}"></script> <script src=" {{ static("js/semantic.min.js") }} "></script> {% endblock scripts %} </body> base.html {% extends "skeleton.html" %} {% from "macros/globalmacros.html"import SUIIconList,SUISimpleList, SUIImageLabel,SUILabel, SUIActionInput,SUILabeledInput,SUIInput, SUIDimmableActionCard,SUICard, %} {% block frame_content %} Frame Content {% endblock frame_content %} {% block scripts %} {{ super() }} <script src=" {{ static("js/globalmacros.js") }} "></script> {% endblock scripts %} dashboard.html {% extends "base.html" %} <div> {% block body_content %} Body 3 {% endblock body_content %} … -
Django Admin - Custom Inline Form
I'm attempting to use a custom inline form within the django admin. admin.py -- class EmpInline(admin.StackedInline): model = Emp form = UpdateYearlyForm show_change_link = True class CompanyAdmin(admin.ModelAdmin): list_display = ('companyname','companyid','get_active', 'get_updated') inlines = [EmpInline] When the Company name is clicked on, the company details are shown along with a formset for all the related employees. This works in regards to displaying the form however one of the fields is a custom choice field which indirectly updated a model field. Which, in the normal user view (this form needs to be used both by an admin for all records and for users for the records pertaining to them) the custom field is handled as below. I've only shown a snippet of the view as it is quite long. views.py -- if formset.is_valid(): for form in formset.forms: if form.is_valid(): obj = form.save(commit=False) data = form.cleaned_data if data['updatefield'] == 'accident': obj.years += 1 else data['updatefield'] == 'free': obj.years += 1 obj.save() Is there a way of handling the form (and the custom field) in the same way when used as an inlineform in the admin? -
Pass None to DRF SerializerField's to_representation
I have the following SerializerField: class TimestampField(Field): def to_representation(self, value): if not value: return '' return value.timestamp() And I use it like this in my serializer: class ArticlePhotobookSerializer(ModelSerializer): delivery_date_from = TimestampField() delivery_date_to = TimestampField() Now the getter delivery_date_to can return None, which I want to transform into an empty string using the to_representation method. however, when I use the Serializer to parse this None value, it doesn't even enter the to_representation method and immediately returns None. What should I change to also use the method to_representation for None? -
Django: Data uownership for users
I am trying to create a simple app. It has the following model: Model: Product class Product(models.Model): product_owner = models.ForeignKey(User, verbose_name='User') product_title = models.CharField(max_length=100, null=False, verbose_name='Product title') product_description = models.TextField(max_length=250, verbose_name='Product description') product_qty = models.IntegerField(verbose_name='Quantity') product_mrp = models.DecimalField(max_digits=12, decimal_places=2, verbose_name='Maximum retail price') product_sku = models.CharField(max_length=100, null=False, unique=True, verbose_name='SKU',help_text='Enter Product Stock Keeping Unit') product_barcode = models.CharField(max_length=100, null=False, verbose_name='Barcode') I am using only the built in Admin App provided by django framework. And I was able to Make the Product data availaible for only the respective user by adding the following in the Admin classes. class ProductAdmin(ImportExportModelAdmin): exclude = ('product_owner',) list_display = ['product_title','product_description', 'product_qty', 'product_mrp','product_sku','product_barcode'] search_fields = ['product_title', 'product_description', 'product_sku', 'product_barcode'] ordering = ['id'] list_display_links = ['product_title'] def get_queryset(self, request): if request.user.is_superuser: return Product.objects.all() return Product.objects.filter(product_owner=request.user) def save_model(self, request, obj, form, change): if not change: obj.product_owner = request.user obj.save() As I just started experimenting, I added 2 users, User1 and User2. For User1 I added 10 products. Then I loggen in as User2 and User2 cannot see the products added by User1. Now when I am tying to add products for User2, and if there is a conflict in product_sku field which is a unique field, I cannot add the product at … -
How to raise 503 error in django?
I want to make site maintenance page and I create singleton model for site maintenance with checkbox field, So when I checked that checkbox from Django admin then the site should show maintenance page if we hit any URL of the website. I checked 503 status code is related to SERVICE UNAVAILABLE So How can I raise 503 error manually in my code and also want to render a custom template when 503 error raise. -
Django decimal precision loss
worth = Decimal(request.POST.get('worth')) print(request.user.profile.cash) # -> prints 10000.000000000000000 print(worth) # -> prints 10000 Profile.objects.filter(user=request.user).update(cash=F('cash')-worth) request.user.profile.refresh_from_db() if request.user.profile.cash < 0: ###!!!!#### print(request.user.profile.cash) # -> -1.819E-12 #model definition: class Profile(models.Model): cash = models.DecimalField(default=10000, max_digits=30, decimal_places=15) as can be seen, the player has 10k cash and I subtract 10k, which results in minus values, how can I solve this problem? I don't allow cash to be negative as you can expect. Am I doing something principally wrong? I want the player to be able to go all-in with his money. -
I have some CSV data and I want to import into django models using DB relationship
Thank you in advance. I have a Django database with some models: class District(models.Model): code = models.CharField("Code".encode('utf-8'),max_length=512, null=True) name = models.CharField("Name".encode('utf-8'),max_length=512) class Neighborhood(models.Model): code = models.CharField("Code".encode('utf-8'),max_length=512, null=True) name = models.CharField("Name".encode('utf-8'),max_length=512) district = models.ForeignKey(District, on_delete=models.CASCADE) dHab = models.DecimalField("Densiy of Habitants".encode('utf-8'),max_digits=15, decimal_places=5, default=0, validators = [MinValueValidator(0)]) And I need to import a csv file uploading both District and Neighborhood data. 01 District 1 02 District 2 03 District 3 011 Neigborhood a (Belongs to District 1) 012 Neigborhood b (Belongs to District 1) 021 Neigborhood c (Belongs to District 2) 031 Neigborhood d (Belongs to District 3) etc. If I upload a Neighborhood, how do I find the proper District before inserting into the database so they can be correctly related to each other? Because I far as I know, Django has an auto_increment field -
Inserting data into DataBase using Forms not working
So I'm building my 1st website and I'm having an issue. I don't really understand how views, modules and my website connects.. And maybe thats the reason I got this error... My folder of the html files is map/templates/serverlist.html I am trying to add my data into the DB and I have a problem because of the form action... I wrote 'map:serverlist' because I think it's the name of the project and the name of the template. isn't it? THE PROBLEM IS EITHER IN THE FORM LINE IN THE HTML OR THE url.py file. I don't know what to write in both of them.. :( Any idea what's missing? IndentationError at / unexpected indent (forms.py, line 6) Request Method: GET Request URL: http://172.16.10.60:8000/ Django Version: 1.3.1 Exception Type: IndentationError Exception Value: unexpected indent (forms.py, line 6) Exception Location: /media/sf_C_DRIVE/Users/eilon.ashkenazi/Desktop/EilonA/DevOpsMap/WebFiles/../WebFiles/map/views.py in <module>, line 4 Python Executable: /usr/bin/python Python Version: 2.7.5 Python Path: ['/media/sf_C_DRIVE/Users/eilon.ashkenazi/Desktop/EilonA/DevOpsMap/WebFiles', '/usr/lib64/python27.zip', '/usr/lib64/python2.7', '/usr/lib64/python2.7/plat-linux2', '/usr/lib64/python2.7/lib-tk', '/usr/lib64/python2.7/lib-old', '/usr/lib64/python2.7/lib-dynload', '/usr/lib64/python2.7/site-packages', '/usr/lib64/python2.7/site-packages/gtk-2.0', '/usr/lib/python2.7/site-packages'] Server time: Wed, 13 Sep 2017 07:39:50 -0500 view.py # Create your views here. from django.shortcuts import render_to_response from django.template import RequestContext from map.forms import PostForm from map.models import serverlist def home(request): entries = serverlist.objects.all() return render_to_response('serverlist.html', {'serverlist' : … -
Cannot assign "{'id': 31}": "Model.table_ABC" must be a "ABC" instance
I double checked if the id 31 exists, where some_id here is 31, where id is a pk. It does exist under ABC model and there is data. I don't see how this is incorrect? I've also tried ABC.objects.filter(id=some_id), also tried just setting abc=31, which doesn't make sense but wanted to try, also tried .get(pk=some_id) ABC is a foreign key to Model. a_id = ABC.objects.get(id=some_id) person_abc= Model(user=request.user, abc=a_id) form = ModelForm(request.POST, instance=person_abc) -
What are the best practices for installing Django with python3 & venv?
I have read other similar questions before posting but they still left me a bit unclear on some issues. I use both Linux Ubuntu and Windows 10 for development. On both platforms I have multiple versions of Python, in both python3 and python2 versions. 1) If I use Anaconda2 and Anaconda3, the version of Python that comes with Anaconda is the same binary as the default version of Python that I get on python.org? 2) With Anaconda and the conda command, virtual environments are put into a hidden directory, e.g. .myvenv. If I put my application, such as Django in a directory beneath that .myvenv then my IDE cannot find it. So in development, I can activate the appropriate venv ( with conda command or with virtualenv ) and put my application in a sibling or parent directory that is not hidden? Is that correct? 3) Why would I see python2 versions of modules/packages being installed with the pip command even when I have activated a python3 venv? For example, I saw a package with name that includes py2.python3. That may be a python3 version of Django but I think I have seen pip installing a clearly python2 package. In … -
Querying Record DRF (get_queryset defined)
I currently have a viewset with the following code class IndigentViewset(viewsets.ModelViewSet): serializer_class = IndigentSerializer def get_queryset(self): qry_status = self.request.GET.get('review_status') try: qry_limit = int(self.request.GET.get('qry_limit')) except Exception as e: pass try: qry_hldID = self.request.GET.get('hldID') except Exception as i: pass if qry_status == "un_reviewed" : retrieved_info = UrbanHousehold.objects.filter(form_reviewed=False)[:qry_limit] elif qry_status == "reviewed": retrieved_info = UrbanHousehold.objects.filter(form_reviewed=True)[:qry_limit] elif 'qry_hldID' in locals(): retrieved_info = UrbanHousehold.objects.filter(id=qry_hldID) else: retrieved_info = UrbanHousehold.objects.all() return retrieved_info I am more of a front-end developer so I am only learning Django and DRF on the fly as i go with my projects.My question is that when I try to retrieve a record using its ID from the Model associated with his viewset, all I keep getting is a 404 error stating the record was not found. Can any one assist with this problem or possibly point out what I might not be understanding. -
Python syntax error without traceback?
I'm using django mongodb for a gym application website that I'm building for fun as my first web development project. I've just installed PyMongo, Django MongoDB, and I've created some models: from django.db import models from djangotoolbox.fields import ListField, EmbeddedModelField class Person(models.Model): name = models.CharField(max_length=200) class Workout(models.Model): date = models.DateTimeField('workout date') person = models.ForeignKey(Person, on_delete=models.CASCADE) lifts = ListField(EmbeddedModelField('Lift')) cardio = ListField(EmbeddedModelField('Cardio')) def __str__(self): return str(self.date) class Lift(models.Model): name = models.CharField(max_length = 200) #e.g. bench press, squat, deadlift, ... sets = models.ListField() # Stores a list of reps, each element corresponding to a set def __str__(self): return str(self.name) class Cardio(models.Model): name = models.CharField(max_length = 200) #e.g. running, cycling, etc. distance = models.IntegerField() #In metres. duration = models.IntegerField() #In minutes def __str__(self): return str(self.name) Now, I would like to start the shell to try to save some data. I get this strange error: (workout) Sahands-MacBook-Pro:workout sahandzarrinkoub$ python manage.py shell SyntaxError: invalid syntax (base.py, line 272) Since it doesn't even point me to an error location, I don't know what to do. There are many base.py-files on my computer. What is this error and how do I solve it? Some (possibly) useful additional info: (workout) Sahands-MacBook-Pro:workout sahandzarrinkoub$ python Python 3.6.2 (default, Jul 17 … -
"ValueError: attributes needs to be a callable, a list or a dict" on mezzanine admin
im using Django + Mezzanine and getting and unknow problem. When i try to create a new page, blogpost or anything in the mezzanine admin interface i receive the folowing message: "ValueError: attributes needs to be a callable, a list or a dict". This error ocures only on production on my server, at the local testing runs ok. Im using Mezzanine 4.1.0 and Django 1.9 on both servers Print of the error page -
Django template include overwrite <h1> tag
I have the following html files. banner.html <header class="intro2"> <div class="intro-body"> <div class="container"> <div class="row"> <div class="col-md-8 col-md-offset-2"> <h1>{% block banner %}Bannertest{% endblock banner %}</h1> </div> </div> </div> </div> </header> test.html {% include 'banner.html' %} {% block banner %}Test{% endblock banner %} I'm new to Django but I would expect the H1 title to be updated to say Test instead of Bannertest? What am I doing wrong? -
Django Heroku and postgresql
I am new to publishing django apps on heroku. I have read their tutorials and figured I would start simple by modifying their template django project. So far everything was good. Then I made an app as one does, made a model and ran python3 manage.py makemigrations my_app python3 manage.py migrate and things seemed ok. I then pushed to heroku and there were no immediate complaints. However, now when I try to make save a new model I get the error: ProgrammingError at /my_app/ relation "my_app_myappmodel" does not exist LINE 1: INSERT INTO "my_app_myappmodel" ("field1", "field2", "field3") VALUES... odd... So I run this locally and everything works fine. I have tried cleaning my migrations, faking my migrations, squashing my migrations, etc (as other S.O. posts suggest) Nothing works. What is up and how do I fix it? -
Django model filter and do distinct by name
I have two models category class Category(models.Model): parent = models.ForeignKey() name = models.CharField(max_length=250) name parent ------- ------- vehicle 0 car 1 motorcycle 1 truck 1 bicycle 1 fff 0 .... Brand name category ---- --------- BMW car BMW truck BMW bicycle toyota car mercedes car mercedes truck someThing fff .... I want to create a queryset of Brand that is filtered by vehicle and to be distinct by name. so I can create a form in my template that will have a drop down filter with all the brands related to vehicle categories with no duplicate of names name category ---- --------- BMW car toyota car mercedes truck Is there any option to do it in a simple way,or do I need to write a function for that? I saw an example Select DISTINCT individual columns in django? but it returns a ValuesQuerySet and I need a QuerySet, and I prefer not to use ().distinct('someItem') that is supported only on PostgreSQL. -
Replacing django-admin default logo
I have generated a django-admin for my app and I can access the dashboard. But it contains a logo that says "django admin". I want to change it to my own custom logo. How can I do that? I have tried adding a base.html file to admin directory and tried to override but for some reason it's not working. It's code is as follows: {% extends "admin/base.html" %} {% load theming_tags %} {% load staticfiles %} {% block blockbots %} {{ block.super }} {# Using blockbots ensures theming css comes after any form media and other css #} {% render_theming_css %} <style type="text/css"> #header #branding h1 { background-image: url("bootstrap_admin/img/logo-140x60.png"); } </style> {% endblock %} {% block branding %} <a href="{% url 'admin:index' %}" class="django-admin-logo"> <!-- Django Administration --> <img src="{% static "bootstrap_admin/img/logo-140x60.png" %}" alt="{{ site_header|default:_('Django Admin') }}"> </a> {% endblock branding %} How can I achieve what I'm trying to? -
Social - Auth: google OAuth2 with Django project failing
I am trying to add googleOauth2 to my django project but keep getting a 404 as below stating "Backend not found" Page not found (404) Request URL: http://127.0.0.1:8000/social-auth/login/google/ Raised by: social.apps.django_app.views.auth Backend not found settings.py extract below: AUTHENTICATION_BACKENDS = ( 'social.backends.facebook.Facebook2OAuth2', 'social.backends.google.GoogleOAuth2', 'social.backends.twitter.TwitterOAuth', 'django.contrib.auth.backends.ModelBackend', 'account.authentication.EmailAuthBackend', ) SOCIAL_AUTH_FACEBOOK_KEY = 'xzy' SOCIAL_AUTH_FACEBOOK_SECRET = 'xzy' SOCIAL_AUTH_TWITTER_KEY = 'xzy' SOCIAL_AUTH_TWITTER_SECRET = 'xzy' SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = 'xzy' SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = 'xzy' I don't think I am getting as far as the google servers but I have rechecked and copied and pasted key and secret to ensure that was right. FB is working fine. -
attempt to create queryset with filters at runtime does not return rows but SQL looks fine
Django 1.11.5 I am trying to build a query set with a chain of filters at runtime def query_cache(self, object: ObjectType, filters: List[MutableMapping] = None) -> QuerySet: filters = filters or [] object_name = object.value q = Cin7Cache.objects.filter(object_type=f"'{object_name}'") for f in filters: q = q.filter(**f) return q I get a queryset that always evaluates to no rows. The sql generated is fine. If I run it on postgresql, I get the rows I want SELECT "voga_cin7cache"."object_uniqueID", "voga_cin7cache"."object_type", "voga_cin7cache"."last_modified", "voga_cin7cache"."jdata" FROM "voga_cin7cache" WHERE ("voga_cin7cache"."object_type" = 'orders' AND ("voga_cin7cache"."jdata" -> 'createdDate') > '"2017-09-09"'); I can produce the same SQL with this: result_query = Cin7Cache.objects.filter(object_type='orders').filter(jdata__createdDate__gt='2017-09-09') and in this case, the result_query is not empty. The query in this case is: SELECT "voga_cin7cache"."object_uniqueID", "voga_cin7cache"."object_type", "voga_cin7cache"."last_modified", "voga_cin7cache"."jdata" FROM "voga_cin7cache" WHERE ("voga_cin7cache"."object_type" = orders AND ("voga_cin7cache"."jdata" -> 'createdDate') > '"2017-09-09"') it's not exactly the same: in the where clause, string constant 'orders' is not quoted the second time, but both give the same result set when evaluated in the postgresql console. WHen I inspect the queryset object, in the non-working case I have _result_cache = [] and in the second example, the working one, the query set has _result_cache=None Why is my first query set empty? -
Django - IndentationError at /
So I'm building my 1st website and I'm having an issue. I don't really understand how views, modules and my website connects.. And maybe thats the reason I got this error... My folder of the html files is map/templates/serverlist.html My error - IndentationError at / unexpected indent (forms.py, line 6) Request Method: GET Request URL: http://172.16.10.60:8000/ Django Version: 1.3.1 Exception Type: IndentationError Exception Value: unexpected indent (forms.py, line 6) Exception Location: /media/sf_C_DRIVE/Users/eilon.ashkenazi/Desktop/EilonA/DevOpsMap/WebFiles/../WebFiles/map/views.py in <module>, line 4 Python Executable: /usr/bin/python Python Version: 2.7.5 Python Path: ['/media/sf_C_DRIVE/Users/eilon.ashkenazi/Desktop/EilonA/DevOpsMap/WebFiles', '/usr/lib64/python27.zip', '/usr/lib64/python2.7', '/usr/lib64/python2.7/plat-linux2', '/usr/lib64/python2.7/lib-tk', '/usr/lib64/python2.7/lib-old', '/usr/lib64/python2.7/lib-dynload', '/usr/lib64/python2.7/site-packages', '/usr/lib64/python2.7/site-packages/gtk-2.0', '/usr/lib/python2.7/site-packages'] Server time: Wed, 13 Sep 2017 07:39:50 -0500 view.py - # Create your views here. from django.shortcuts import render_to_response from django.template import RequestContext from map.forms import PostForm from map.models import serverlist def home(request): entries = serverlist.objects.all() return render_to_response('serverlist.html', {'serverlist' : entries }) def postView(request): if request.method == 'POST': form = PostForm(request.POST) if form.is_valid(): # Checks if validation passed servername = request.POST.get('ServerName','') owner = request.POST.get('Owner','') item = serverlist(servername=ServerName,owner=Owner) form.save() # Save the data into the DB return HttpRespondRedirect(reverse('map:serverlist')) # Resdirect after POST else: form = PostForm() return render(request, 'templates/serverlist.html', { 'form' : form, }) forms.py - from django import forms from map.models import serverlist class PostForm(forms.Form): ServerName … -
Django celery and rabbitmq doesn't work until restart
I have problem with django, celery and rabbitmq. I use celery to send messages to FCM devices, but problem is that celery doesn't run that FCM command for sending messages, until I restart celery server. And when I restart celery, and try again, still same, I need to restart it again after every action. Example code: from __future__ import absolute_import, unicode_literals from celery import shared_task # firebase cloud messaging from fcm.utils import get_device_model Device = get_device_model() @shared_task def send_firebase_message(json, **kwargs): response = Device.send_msg(json, **kwargs) return response This is simple code, so this Device.send_msg doesn't fire until I restart celery server. Anyone got any solution for this? What can be the problem? -
NoReverseMatch at /<urls>
I am using django 1.10. I want to know how the reverse function works. This is a basic chat application using django. I am stuck at line no:7 in index.html Below ones are the files: viwes.py from django.shortcuts import render from django.http import HttpResponse from django.shortcuts import get_object_or_404 from chat.models import ChatRoom def index(request): chat_rooms= ChatRoom.objects.order_by('name')[:5] context = { 'chat_list' : chat_rooms } return render(request,'chats/index.html', context) def chat_room(request,chat_room_id): chat = get_object_or_404(ChatRoom, pk =chat_room_id) return render(request,'chats/chat_room.html', {'chat':chat}) chat/urls.py from django.conf.urls import url from django.urls import reverse from chat import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^(?P<chat_id>[0-9]+)/$', views.chat_room, name='chat_room'), ] index.html {% if chat_list %}</pre> <ul> <ul>{% for chat in chat_list %}</ul> </ul> <ul> <ul> <li><a id=""href="{% url 'chat_room' chat.id %}"> {{ chat.name }}</a></li> </ul> </ul> <ul>{% endfor %}</ul> <pre> {% else %} No chats are available. {% endif %} Any suggestions are welcome! -
Unit test in Django dont see correct redirect url for successfull login?
In my Django project I create custom admin page (NOT admin from Django). I have 2 login pages. One for admin, second for other users. Here below you can see urls.py file for admin. I test it and it works fine. After successful login Django redirect user to url which was next parameter (/administration/dashboard/). I wrote unit test and it raise error. From error I understand that Django redirect to default url (/accounts/profile/). Why unit test dont use settings which I did in urls.py file (next parameter)? How to fix this problem? Right now I notice that problem disappear only if I use this code LOGIN_REDIRECT_URL = '/administration/dashboard/' in settings.py. I cant use it cause in the future I will use LOGIN_REDIRECT_URL to my other login page. I would be grateful for any help! urls.py: from django.contrib.auth import views as authentication_views urlpatterns = [ # Administration Login url(r'^login/$', authentication_views.login, { 'template_name': 'administration/login.html', 'authentication_form': AdministrationAuthenticationForm, 'extra_context': { 'next': reverse_lazy('administration:dashboard'), }, 'redirect_authenticated_user': True }, name='administration_login'), ] tests.py: class AdministrationViewTestCase(TestCase): def setUp(self): self.client = Client() self.credentials = {'username': 'user', 'password': 'password'} self.user = User.objects.create_user(**self.credentials) def test_administration_authorization(self): self.assertTrue(self.user) logged_in = self.client.login(**self.credentials) self.assertTrue(logged_in) response = self.client.post( reverse("administration:administration_login"), follow_redirects=True ) self.assertEqual(response.status_code, 302) self.assertRedirects( response, reverse("administration:dashboard"), status_code=302, … -
Check if User is in Many2Many field
I have the following model with a m2m field where logged in Users can show interest in a publication: models.py from django.db import models class Publication: title = models.CharField(max_lenth=512) users_interested = models.ManyToManyField(User) views.py from django.shortcuts import render from django.views import View from .models import Publication class listPublicationView(View): def get(self, request, *args, **kwargs): publications = Publication.objects.all() return render(request, "base.html", {'publications': publications}) Now i try to produce a "i am already interested" in the template when a logged in user is already interested in the publication: base.html {% for publication in publications %} {{publication.title}} {% if currently logged in User is interested in publication (check users_interested) %} i am already interested {% endif %} {% endfor %} I've been stuck on this problem for days. Any help is appreciated. -
Django view not receiving variables from post form
I am sending variables from one template to a view through a post form and then using them in the next template. But the variables are not present when it reaches the template. Here is the JavaScript used in the first template. game2.html: function clickFntn(clicked_id) { {% autoescape off %} var clicked = document.getElementById(clicked_id).src; var clicked1 = clicked.replace(/^.*[\\\/]/, ''); var clicked2 = clicked1.slice(0,-4); if (clicked2 == gv_common) { gv_set1_counter = gv_set1_counter + 1; var set1 = {{ set1 }}; if (gv_set1_counter == 2) { var_user = "{{user}}"; game_id = {{game.id}}; var player_end_time = new Date(); var play_time = parseInt((player_end_time-player_start_time)/1000); post("{% url 'game2_end' %}", {type:"first", user:var_user, time: play_time, id: game_id}); } {% endautoescape %} }; function post(path, params, method) { method = method || "post"; // Set method to post by default if not specified. // The rest of this code assumes you are not using a library. // It can be made less wordy if you use one. var form = document.getElementById("form1"); form.setAttribute("method", method); form.setAttribute("action", path); for(var key in params) { if(params.hasOwnProperty(key)) { var hiddenField = document.createElement("input"); hiddenField.setAttribute("type", "hidden"); hiddenField.setAttribute("name", key); hiddenField.setAttribute("value", params[key]); form.appendChild(hiddenField); } } document.body.appendChild(form); form.submit(); } view.py: def game2_end(request): if request.method == "POST": if request.POST.get("type") == "first": …