Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
- 
        
How to have Django templates display slugs
Hi guys i am new to django...i been watching youtube videos and reading books on Django but am still struggling with templates. I am working on a ecommerce project and i would love a bit of help with templates. So i want my template to display a list of categories as links on a sidebar. I have defined a slug field in my category models and i have managed to map a url...but i am still not getting a list of categories on my index page sidebar. This is my url pattern and this is working perfect. When i click 127.0.0.1.000/food it's working (food is a category) path('<slug:category_slug>/', views.category, name='category'), the view function def category(request, category_slug): """Defines category views""" categories= get_object_or_404(Category, slug= category_slug) context = {'categories': categories} return render(request, "categories_list.html", context) This is the categories_list.html template that i need help with <h3> Shop by Category </h3> {% if category in categories %} <li> <a href ="{{category.slug}}"> {{category.name}}</a> </li> {% endif %} My wish is to have the categories displayed on the sidebar of my index page as links. I have used {% include 'category_list.html' %} on my index page template, and its only displaying the Shop by Category heading instead … - 
        
Get List of Categories on the basis of foreign model in django
I've two models as below. class Category(models.Model): title = models.CharField(max_length=55) class Meta: verbose_name = 'Food Category' verbose_name_plural = 'Food Categories' def __str__(self): return self.title class FoodItem(TimeStampWithCreator): CATEGORY_CHOICES = ( ('takeway', 'Takeaway'), ('dine_in', 'Dine In'), ('function', 'Function'), ) type_menu_select = models.CharField(max_length=20, choices=CATEGORY_CHOICES, default='takeway') category = models.ForeignKey(FoodCategory, on_delete=models.CASCADE) i want to filter all the categories containing takeaway, I've no idea how to achieve this - 
        
DJango user not logging out
I'm new to DJango and I'm trying to make a user auth. My login is working fine but my user isn't logging out. My Logout view is: from django.contrib.auth import logout from django.contrib.auth.models import User class LogoutView(generic.View): @staticmethod def get(request): if User.is_authenticated: # Debug statement print('if') logout(request) return redirect('login') else: print('ekse') return redirect('index') My url is working fine because when i go to /logout/, My debug statement executes but if User.is_authenticated: always returns an object(true). How can I resolve this issue. Thanks - 
        
Same query set, different result in django
I get a different result when I filter another time with the same filters. This code is part of the get_queryset() of a class that inherits ListAPIView. validity_filters = Q( ( ( Q(display_publisher_group__publishers__id__exact=98) | Q(display_publisher_group__isnull=True) ) & ( ~Q(blacklist_publisher_group__publishers__id__exact=98) ) ) ) campaigns = Campaign.objects.filter(validity_filters) print(1, campaigns.distinct().count()) campaigns = campaigns.filter(validity_filters) print(2, campaigns.distinct().count()) The output is: 1 33276 2 33275 - 
        
App 'category' doesn't provide model 'category'
Django==3.0.6 class Category(CommentMixin, TitleMixin, SlugMixin, models.Model): pass from category.models import Category class Post(TitleMixin, SlugMixin, DescriptionMixin, models.Model): ... category = models.ForeignKey(Category, on_delete=models.PROTECT, related_name='blog_posts') The database has been dropped and recreated. All migrations have been deleted. In settings.py 'post' and 'category' are added. When making migrations: ValueError: The field post.Post.category was declared with a lazy reference to 'category.category', but app 'category' doesn't provide model 'category'. Could you help me understand what is going on here? - 
        
I am getting error ModuleNotFoundError: No module named 'rest_framework'
if I try to install rest fremwork by command pip3 install Django rest framework then it is showing Requirement already satisfied. - 
        
How to handle AJAX POST request in Django
I have a sort of twitter like button function in my app such that, when the button is clicked, it triggers an AJAX call and performs the action specified in the views. However, when i click the button, it does not perform action in views. The code reaches the 'like view' but does not execute anything after 'if request.POST:'. Please help. Menu.html <form action="{% url 'like'%}" id="plt_{{menu.id}}" data-id="{{menu.id}}" method="post"> {%csrf_token%} <input name="menu_id" type="hidden" value="{{ menu.id }}"> <div class="like-button" id="btn_{{menu.id}}"></div> </form> <script> $('.like-button').on('click', function () { var id = $(this).attr('id'); id = id.replace('btn_',''); $(this).toggleClass('animate').promise().done(function () { var link = $("#plt_"+id).attr('action') $.ajax({ type: 'POST', url: link, headers: {'X-CSRFToken': '{{ csrf_token }}'}, }) }); }); </script> Views.py def like(request): print('reached') //this prints if request.POST: menu = Menu.objects.get(pk=request.POST.get('menu_id')) //execute code to like return HTTPResponse('') - 
        
Django restframework, Authentication credentials were not provided
I took a tutorial in Redox and Django from youtube from Traversy Media. I follow along with the tutorial and now I don't know were it curshed. curl http://localhost:8000/api/auth/login/ -d \ '{"username": "Tom", "password": "PassWord@321"}' \ -H "Content-type: application/json" -X POST By doing so I need to get user and the corresponding token but instead I'm getting {"detail":"Authentication credentials were not provided."} What all I did => # settings.py INSTALLED_APPS = [ 'leads', 'rest_framework', 'frontend', 'accounts', 'knox', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] REST_FRAMEWORK = { "DEFAULT_AUTHENTICATION_CLASSES": ("knox.auth.TokenAuthentication", ), } # serializers.py class LoginSerializer(serializers.Serializer): username = serializers.CharField() password = serializers.CharField() def validate(self, data): user = authenticate(**data) if user and user.is_active: return user raise serializers.ValidationError("Incorrect Credentials") # api.py class LoginAPI(generics.GenericAPIView): serializer_class = LoginSerializer def post(self, request, *args, **kwargs): serializer = self.get_serializer(data = request.data) serializer.is_valid(raise_exception = True) user = serializer.validated_data _, token = AuthToken.objects.create(user) return Response({ "user": UserSerializer(user, context = self.get_serializer_context()).data, "token": token }) # leadmanager/urls.py urlpatterns = [ path("api/auth/", include("accounts.urls")), ] # accounts/urls.py urlpatterns = [ path("login/", LoginAPI.as_view()), ] I don't know were it crushed. - 
        
Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response?
I am using react for my frontend and Django restframework for API. I am getting Access to XMLHttpRequest at 'xxxxxxxx' from origin 'xxxxxxxx' has been blocked by CORS policy: Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response. I have enabled "corsheaders" at my installed app, 'corsheaders.middleware.CorsMiddleware' at Middleware and CORS_ORIGIN_ALLOW_ALL = True and CORS_ALLOW_METHODS = [ 'DELETE', 'GET', 'OPTIONS', 'PATCH', 'POST', 'PUT', ] CORS_ALLOW_HEADERS = [ 'accept', 'accept-encoding', 'authorization', 'content-type', 'dnt', 'origin', 'user-agent', 'x-csrftoken', 'x-requested-with', ] in setting.py. Can anyone guide why i am getting this issue. Whether it is from client side or Server side. - 
        
django.db.utils.OperationalError: no such table - after deleting all Django migrations
I had some issues with my database(design) and deleted all migrations, but not the db.sqlite3 file. I then rewrote my models.py, re-registered them inadmin.py and ran python3 manage.py makemigrations and python3 manage.py migrate. Both seemed to work fine and create the tables. In the Django admin interface, I can see my new tables, but when trying to access them or do something in my views.py with them i get this error (in this case for table orders_dish: django.db.utils.OperationalError: no such table: orders_dish Can anyone help me? Am really stuck here... Below the full traceback: Internal Server Error: /admin/orders/dish/ Traceback (most recent call last): File "/home/anna/py3_cs50W/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "/home/anna/py3_cs50W/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 303, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: no such table: orders_dish The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/anna/py3_cs50W/lib/python3.6/site-packages/django/core/handlers/exception.py", line 35, in inner response = get_response(request) File "/home/anna/py3_cs50W/lib/python3.6/site-packages/django/core/handlers/base.py", line 128, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/anna/py3_cs50W/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/anna/py3_cs50W/lib/python3.6/site-packages/django/contrib/admin/options.py", line 574, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "/home/anna/py3_cs50W/lib/python3.6/site-packages/django/utils/decorators.py", line 142, in _wrapped_view response = view_func(request, *args, **kwargs) File "/home/anna/py3_cs50W/lib/python3.6/site-packages/django/views/decorators/cache.py", line 44, in _wrapped_view_func response … - 
        
Django access fields of model with many to many relationship
So I have the following models: class Image(models.Model): image=models.ImageField(upload_to='postimages') id=models.UUIDField(default=uuid.uuid4, editable=False, unique=True, primary_key=True) class Post(models.Model): title=models.CharField(max_length=500) created_date=models.DateField(auto_now=True) id=models.UUIDField(default=uuid.uuid4, editable=False, unique=True, primary_key=True) images=models.ManyToManyField(Image) user=models.ForeignKey(get_user_model(), on_delete=models.CASCADE, null=True, related_name='posts') In my views I have created a post object like this: post=Post(title=title) post.save() post.images.add(image) Now I need to diplay the image field of the Image model in my homepage. I am trying to do it like this: {%for post in posts%} <img src="{{post.images.image}}"> {%endfor%} But this returns image with src=(unknown). So my question is how do I access the image field of the Image model? - 
        
'NoneType' object has no attribute 'nazev_zanru' although it should have
Good day community, I need your help as I cannot proceed with my project. Django model.py returns an AttributeError: 'NoneType' object has no attribute 'nazev_zanru' My models.py is as follows; from django.db import models class Zanr(models.Model): nazev_zanru = models.CharField(max_length=80, verbose_name="Žánr") def __str__(self): return "Nazev_zanru: {0}".format(self.nazev_zanru) class Meta: verbose_name = "Žánr" verbose_name_plural = "Žánry" class Film(models.Model): nazev = models.CharField(max_length=200, verbose_name="Název Filmu") rezie = models.CharField(max_length=180, verbose_name="Režie") zanr = models.ForeignKey(Zanr, on_delete=models.SET_NULL, null=True, verbose_name="Žánr") def __str__(self): return "Nazev: {0} | Rezie: {1} | Zanr: {2}".format(self.nazev, self.rezie, self.zanr.nazev_zanru) class Meta: verbose_name = "Film" verbose_name_plural = "Filmy" As far as I understand, the def __str__(self): return "Nazev: {0} | Rezie: {1} | Zanr: {2}".format(self.nazev, self.rezie, self.zanr.nazev_zanru) code refers through zanr = models.ForeignKey(Zanr, on_delete=models.SET_NULL, null=True, verbose_name="Žánr") to class Zanr(models.Model): nazev_zanru = models.CharField(max_length=80, verbose_name="Žánr") def __str__(self): return "Nazev_zanru: {0}".format(self.nazev_zanru) ` which is therefore defined. Where is the mistake? Migrations, URLs and admin done. Thank you in advance, David - 
        
Django URL routing
I am learning Django and progressing well but i am stuck on how to configure the different urls to view functions. I created a project TenancyMGt and an app rentals. I have created several views in the module views.py Two are relevant here: def createTenant(request): form = TenantsForm context = {'form': form} html_form = render_to_string('rentals/partial_tenant_create.html', context, request=request, ) return JsonResponse({'html_form': html_form}) class TenantsListView(ListView): model = Tenants context_object_name = 'tenant_list' template_name = 'rentals/tenants_list.html' paginate_by = 5 def get_queryset(self): return Tenants.objects.all() Now i created a file urls.py under the app rentals: from . import views from django.urls import path app_name='rentals' urlpatterns = [ path("", views.TenantsListView.as_view(), name="index"), path("",views.TenantDetailView.as_view,name="detail"), path("",views.createTenant, name='createTenant'), path("<int:pk>/",views.TenantUpdateView.as_view, name='edit'), path("<int:pk>/",views.delete, name='delete'), ] under TenancyMgr/urls, i add the following: from django.contrib import admin from django.urls import path,include from rentals import views urlpatterns = [ path('admin/', admin.site.urls), path('', include('rentals.urls')), ] When i run the server, the index view opens successfully! From the index, i want to open the createTenant view as below. <button type="button" class="btn btn-primary js-create-tenant" data-url="{% url 'rentals:createTenant' %}> <span class="glyphicon glyphicon-plus"></span> New Tenant </button> When the button is clicked, i get the urls below: http://127.0.0.1:8000/rentals/createTenant/ Then i get the response is 404,page not found error. But this opens admin … - 
        
how can I avoid hide lesson content from end user views-template?
I am trying to do this all vip user paid that contains type 2 allow to see the full information , but however it does as expect, but with a minor issue , it hide the lesson to the end-user if this doesnt belong to x user logged. I want to keep lesson displayed to the end-user, but however if the user tries to click to the lesson then display upgrade account instead of hidding content. how can I achieve this? model class Lesson(models.Model): content_title = models.CharField(max_length=120) content_text = models.CharField(max_length=200) thumbnail = models.ImageField(upload_to='xxx/xxx/xxx/xxx/xxx') link = models.CharField(max_length=200, null=True) allowed_memberships = models.ManyToManyField(Membership) def __str__(self): return self.content_title view def get_context_data(self, **kwargs): context = super(bootCamp, self).get_context_data(**kwargs) lesson = Lesson.objects.first() user_membership = UserMembership.objects.filter(user=self.request.user).first() user_membership_type = user_membership.membership.membership_type lesson_allowed_mem_types = lesson.allowed_memberships.all() context['lessons_allowed_mem_types'] = lesson_allowed_mem_types context['lessons'] = None if lesson_allowed_mem_types.filter(membership_type=user_membership_type).exists(): if Lesson.objects.filter(allowed_memberships=1): context['lessons'] = Lesson.objects.filter(allowed_memberships=1).values() elif Lesson.objects.filter(allowed_memberships=2): context['lessons'] = Lesson.objects.filter(allowed_memberships=2).values() else: pass return context template {% if lessons is not None %} {% for lessson in lessons %} <div class="col-md-3"> <a href="/{{ lessson.link }}"> <div class="item"> <div class="content-overlay"></div> <img src="/{{ lessson.thumbnail }}" /> <div class="content-details fadeIn-bottom"> <h3 class="content-title">{{ lessson.content_title }}</h3> <p class="content-text">{{ lessson.content_text }}</p> </div> </div> </a> </div> {% endfor %} {% else %} <p>upgrade</p> {% endif %} - 
        
django not redirecting from CreateView
So I initially thought that the submit button was not working, but looking in the database, it is POSTing to the database, but it is not clearing the form and going to the success url, any ideas what I'm doing wrong here? <!DOCTYPE html> {% extends "project_portal/base.html" %} {% block detail %} <div class="project_setup"> <h1>Project Setup</h1> <form class="update" method="POST"> {% csrf_token %} <table> {{ form.as_table }} </table> <input type="submit" class="btn" value="Submit"> <a href="{% url 'project-list' 0 %}">Cancel</a> </form> </div> {% endblock %} and here is the view: class ProjectCreateView(CreateView): template_name = 'project_portal/project_create.html' form_class = ProjectModelForm queryset = Project.objects.all() success_url = '/si/home/0/' def form_valid(self, form): user = self.request.user form.instance.user = user return super().form_valid(form) - 
        
Django - How do i calculate the sum of a field in a queryset
Using DJANGO I have a simple model that has fields Customer_ID, Date, Product, Total_price. I want to display them in groups by Date so all prices on that date are shown grouped eg 28 April 2020 Crisps £1.20 Cheese £1.40 29 April 2020 Crisps £1.80 Cheese £3.40 How do I then show total price under each date (eg £2.60, £5.20) Here's what I tried in my html, all good displaying in groups but last tag for calculating sum doesn't work: {% regroup results by Date as new_list %} {% for Date, results2 in new_list %} <div class="track-row"> <span class="track-item track1">{{ Date }}</span> {% for data in results2 %} <div> <span class="track-item track3">{{ data.Stock }}</span> <span class="track-item track5">£{{ data.Sell_price }}+vat</span> <span class="track-item track4">{{ data.Quantity }}</span> <span class="track-item track5">£{{ data.Total_price }}+vat</span> </div> {% endfor %} <h6 class="title4">£{{ data.Total_price__sum }} + vat</h6> </div> {% endfor %} In my views.py I created a queryset with all totals: total = Quotes.objects.values('Customer_ID', 'Date').filter(Customer_ID=customer_id).\ annotate(total_price=Sum('Total_price')).order_by('-Date') and this works fine and gives me the correct totals, but how do I show these results alongside my html. I tried: {% for data2 in total %} <h6 class="title4">£{{ data2.total_price }} + vat</h6> {% endfor %} which works great but just … - 
        
Djnago: Failed to link nested child to parent
I have an issue when trying to create nested objects, more specifically creating a parent and its child at the same time. The child's model has the parent's id as foreign key as can be seen below. Here is my parent_model: from django.db import models from django.contrib.auth import get_user_model User = get_user_model() from PIL import Image class Work(models.Model): user = models.ForeignKey(User, null=True, on_delete=models.SET_NULL) name = models.CharField(max_length=200) length = models.IntegerField(null=True) width = models.IntegerField(null=True) def __str__(self): return "{}".format(self.id) My child_model: from django.db import models from .model_work import * from .model_taxes import * from djmoney.models.fields import MoneyField class Price(models.Model): work = models.OneToOneField(Work, on_delete=models.CASCADE, related_name='price') price = MoneyField(max_digits=19, decimal_places=4, default_currency='USD', null=True) total = models.IntegerField(null=True) def __str__(self): return "{}".format(self.price) Here is my ParentCreateSerializer: class WorkCreateSerializer(serializers.ModelSerializer): """ Serializer to create a new Work model in DB """ price = PriceCreateSerializer() class Meta: model = Work fields = [ 'user', 'price', 'name', 'length', 'width' ] def create(self, validated_data): price_data = validated_data.pop('price') work = Work.objects.create(**validated_data) price = Price.objects.create(**price_data) return work My ChildCreateSerializer: class PriceCreateSerializer(serializers.ModelSerializer): """ Serializer to create a new Price when new Work model is created in DB """ # work = WorkDetailsSerializer() class Meta: model = Price fields = [ 'work', 'price', 'price_currency', 'total' ] def … - 
        
How to manually enter latitude and longitude for a PointField in Django admin with OSMGeoAdmin or GeoModelAdmin?
How can I enter the latitude and longitude of a PointField when creating/editing an entry using the OSMGeoAdmin or GeoModelAdmin? Currently, I have a map where I can place the point by clicking on the map. I'd like to keep this behavior but also be able to manually specify the exact values. Details I have a Location model with a PointField attribute. # models.py class Location(models.Model): name = models.CharField(max_length=255, db_index=True) point = PointField(blank=True, null=True) # admin.py from django.contrib.gis.admin import OSMGeoAdmin @admin.register(Location) class LocationAdmin(OSMGeoAdmin): list_display = ("id", "name") - 
        
Реализация вложенные комментариев в django-rest-framework
Пытаюсь сделать вложенные комментарии к постам, но при выводе постов выдает ошибку: "столбец news_comment.parent_id не существует". Как решить эту проблему или, возможно, стоит сделать все иначе? serializers.py # сериализатор комментария class CommentSerializer(serializers.ModelSerializer): replys = serializers.SerializerMethodField() def get_replys(self, obj): queryset = Comment.objects.filter(parent_id=obj.id) serializer = CommentSerializer(queryset, many=True) return serializer.data class Meta: model = Comment fields = '__all__' # сериализатор вывода постов class PostListSerializer(serializers.ModelSerializer): comments = serializers.SerializerMethodField() def get_comments(self, obj): queryset = Comment.objects.filter(post_id=obj.id, parent_id=None) serializer = CommentSerializer(queryset, many=True) return serializer.data class Meta: model = Post fields = '__all__' models.py # модель комментария class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') parent = models.ForeignKey( 'self', default=None, blank=True, null=True, on_delete=models.CASCADE, verbose_name='parent', related_name='replys' ) text = models.TextField(max_length=1500) date = models.DateTimeField(auto_now=True) username = models.CharField(max_length=50) user = models.ForeignKey(User, on_delete=models.CASCADE) - 
        
django : The view papers.views.member_agreement_vc didn't return an HttpResponse object. It returned None instead
I'd like to make user access to page depends on model exist. it works when there is models.objects, but if there is no objects, it doesn't work. How can I control user path create or just view? hope kindly help me. def member_agreement_vc(request, preassociation_pk): preassociation = preassociation_models.Preassociation.objects.get( pk=preassociation_pk ) try: member_agreement = models.MemberAgreement.objects.get(pk=1) return render( request, "papers/member_agreement/detail.html", {"member_agreement": member_agreement}, ) except models.MemberAgreement.DoesNotExist: form_class = forms.CreateMemberAgreementFormVC template_name = "papers/member_agreement/create.html" def form_valid(self, form): pk = self.kwargs.get("preassociation_pk") member_agreement = form.save() member_agreement.writer = self.request.user member_agreement.association = preassociation_models.Preassociation.objects.get( pk=pk ) member_agreement.category = "member_agreement" member_agreement.is_business = True member_agreement.is_general = False member_agreement.save() form.save() return redirect( reverse( "preassociations:paper", kwargs={"pk": member_agreement.association.pk}, ) ) - 
        
ValueError at /add_to_cart/printed-shirt/ Field 'id' expected a number but got 'Green'
I got this error and have no idea what to do ValueError at /add_to_cart/printed-shirt/ Field 'id' expected a number but got 'Green'. I'm trying to add variations to my product. So when I'm submitting, I'm printing the values the users are selecting request.POST.getlist('variations', []) and those are coming back as ['Green', 'Large']. Now I was trying to see if the product matching these variations already exists in the cart. If i exists, then I would increase the quantity, and if it does not exist, then I would add a new item. But my code doesn't seem to work. Can anyone please help me with this? Thanks in advance! My views.py: @login_required def add_to_cart(request, slug): item = get_object_or_404(Item, slug=slug) variations = request.POST.getlist('variations', []) print(variations) minimum_variation_count = Variation.objects.filter(item=item).count() if len(variations) < minimum_variation_count: messages.info(request, "Please specify the required variations.") order_item_qs = OrderItem.objects.filter( item=item, user= request.user, ordered=False, ) for v in variations: order_item_qs = order_item_qs.filter( item_variations__exact=v ) if order_item_qs.exists(): order_item = order_item_qs.first() order_item.quantity += 1 order_item.save() else: order_item = OrderItem.objects.create( item=item, user= request.user, ordered=False, ) order_item.item_variations.add(*variations) order_item.save() order_qs = Order.objects.filter(user=request.user, ordered=False) if order_qs.exists(): order = order_qs[0] if not order.items.filter(item__id=order_item.id).exists(): order.items.add(order_item) messages.success(request, "Product added to cart.") return redirect("order-summary") else: ordered_date = timezone.now() order = Order.objects.create(user=request.user, … - 
        
Thread local attribute defined globally not accessible in threads
import threading threadlocal = threading.local() threadlocal.depth = 0 def _increase_depth(): threadlocal.depth += 1 def _decrease_depth(): threadlocal.depth -= 1 def _use_it(): print(threadlocal.depth) But I get: AttributeError: '_thread._local' object has no attribute 'depth' What I would expect: each threads gets a depth initialized to 0, and modifications will only visible within that particular thread. Why are the attributes defined in threadlocal not accessible in the threads? (This code is running in development with the django test server: I have not yet adapted it to produce a mimimum example which can be demonstrated with plain threads) - 
        
django-meta project throws lots of exception in the console
I added django-meta to my project as indicated in the documentation on the GitHub : https://github.com/nephila/django-meta (the complete doc are on ReadTheDocs : https://django-meta.readthedocs.io/en/latest/ I tried to only activate the Twitter META tags (for a start). I copy - pasted the default MetaModel values from the source code of django-meta to initialize an instance variable named meta. in my settings, I set several values as it seems django-meta prefers to receive some value through the settings (instead of being set in the code). In the source code it clearly tries to initialize itself from the settings. Here below is relevant part of my Django settings. # CONFIGURATION for the DJANGO-META project # ########################################## META_SITE_PROTOCOL = 'https' META_SITE_DOMAIN = env('DJANGO_META_SITE_DOMAIN', default='www.intrainingnetwork.com') # META_USE_SITES = True # WARNING : DO NOT ACTIVATE as it makes the compilation fail. META_USE_OG_PROPERTIES = False # All the FB keys FB_TYPE='' FB_APPID='' FB_PROFILE_ID='1111111' # From the default_values FB_PUBLISHER='@IntTrainingNetwork' FB_AUTHOR_URL='/fr/' FB_PAGES='/IntrainingNetwork' META_FB_PUBLISHER='This is a Test : ({})'.format(FB_PUBLISHER) USE_TITLE_TAG = True META_USE_TWITTER_PROPERTIES = True TWITTER_TYPE=11 TWITTER_SITE=env('DJANGO_META_SITE_DOMAIN', default='www.intrainingnetwork.com') TWITTER_AUTHOR='International Training Network' META_USE_GOOGLEPLUS_PROPERTIES = False # END In the View Template class, I defined an instance variable. meta = Meta(title = 'title', og_title = 'og title', twitter_title = 'twitter title', … - 
        
Django: Could not parse the remainder
I'm trying to pass a response from JsonResponse as a parameter of specific function in views. But, got the following error instead django.template.exceptions.TemplateSyntaxError: Could not parse the remainder: '${response.id_ajuan}' from '${response.id_ajuan}' Here it is my code url.py url(r'^course-eksternal/review/(?P<id>\d+)/update$', course_eksternal.update_ajuan, name='update-ajuan') views.py # Function that pass the JsonResponse def get_update_ajuan(request): ajuan = Pengajuan.objects.get(pk=request.POST.get('ajuan_id')) res = { 'id_ajuan': ajuan.id, ... } status_code = 200 return JsonResponse(res, status=status_code) file.html # Get the JsonResponse success : function(response) { $('.modal-body').empty().append(` <div class="modal-body"> <form action="{% url 'app:update-ajuan' id=${response.id_ajuan} %}" method="POST"> # Error occurs here ... `); Thank you in advance for your help! - 
        
saving in stages in a django view
I am trying to get a field value from the database and modify it by getting the value from the page when it is rendered, The main issue is that I need to keep updating and savings the seconds every time the user refreshes the page. I want to do that on the same view where the user post his final response, I keep getting this error : IntegrityError: NOT NULL constraint failed: study_answer.completion_time although the field in the answer model has a default value: completion_time = models.FloatField(default=30) Completion time should be saved when the user finally submits the answer that comes from a different AJAX post call. views.py def attention_view(request): participant = get_object_or_404(Participant, user=request.user) attention_question = Question.objects.get(id=13) answer, created = Answer.objects.get_or_create(participant=participant, question=attention_question) seconds_left = int(answer.seconds_left) if request.method == 'POST': selected_choice = request.POST.get('selected_choice') completion_time = request.POST.get('completion_time') seconds_left = request.POST.get('left') seconds_left.answer=seconds_left if answer.answer is not None: return HttpResponseRedirect('/study/attention_view') print('already submitted') else: answer.answer = selected_choice answer.completion_time = completion_time answer.save() context = {'attention_question': attention_question, 'seconds_left':seconds_left, 'answer':answer} return render(request, 'study/AttentionCheck.html', context) I tried to save seconds_left in another view and it works but I want to save it in the same view where I have the GET request