Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django generic view initial value in form
i want to have default value in my form which should be current user's choice. For example, user chooses to give 5 for a movie and he should see 5 in form until he changes it. views.py class MovieDetailView(FormMixin, DetailView): model = Movie template_name = 'main/detail_movie.html' context_object_name = 'movie' form_class = RateForm def get_context_data(self, **kwargs): context = super(MovieDetailView, self).get_context_data(**kwargs) context['form'] = RateForm(initial={'movie': self.object}) context['my_rate'] = Rate.objects.filter( sender=self.request.user, movie=self.get_object()).first() return context def post(self, request, *args, **kwargs): self.object = self.get_object() form = self.get_form() if request.method == 'POST': if form.is_valid(): new_rate, _ = Rate.objects.update_or_create( sender=self.request.user, movie=self.object, defaults={'choice': form.cleaned_data['choice']} ) return JsonResponse({'rate': model_to_dict(new_rate)}, status=200) else: return self.form_invalid(form) def get_success_url(self): return reverse('detail_movie', kwargs={'slug': self.object.slug}) I was trying get_initial method but it still gives me '---' in form as default. def get_initial(self): return {'choice': Rate.objects.filter(movie=self.object, sender=self.request.user).first().choice } Even something like this doesn't work def get_initial(self): return {'choice': 1 } -
Real-time location tracking in website built on django
I want some guidance on how to build a real-time location tracking website for my project in django. I have never worked on an application like this so I have no knowledge on how to do that. So, basically my project is a food delivery website, like ubereats. What I want to do in my project is to monitor the location of food deliverer and show it to the customer who has ordered their food in real-time. My project is based on Django, with Vanilla JS, and it is a web application I will love your input on this such as the database required, technologies that I will need, or any similar project that have been built, and any guidance that will help me get started with my project. Thank you! -
What is the problem for using fullPage.js moveTo?
I want to make a button to move specific page...like if i click the #move_to_slide2, then page moves to slide2 but moveTo function doesn't work. there is only one section and 4 slides. how can i make move to button? <div class="section" anchor="s0"> <div class="slide" data-anchor="slide1"> <div class="container w-1/3 mx-auto"> <div class = "my-40"> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="text-xl font-bold text-center text-unifolio-blue">Getting Started</div> <div class="flex w-full mt-5 items-center justify-center"> <p id="move_to_slide1"> <p class="w-full h-6 rounded-full bg-unifolio-blue cursor-pointer"></p> </p> <div class="h-px w-full bg-gray-400"></div> <p id="move_to_slide2"> <p class="w-full h-6 rounded-full bg-gray-400 cursor-pointer"></p> </p> <div class="h-px w-full bg-gray-400"></div> <p id="move_to_slide3"> <p class="w-full h-6 rounded-full bg-gray-400 cursor-pointer"></p> </p> <div class="h-px w-full bg-gray-400"></div> <div class="flex w-full mb-5 items-center text-center justify-center"> <p id="move_to_slide1"> <p class="w-full h-6 text-xs text-unifolio-blue cursor-pointer">아이디 및 비밀번호 설정</p> </p> <div class="h-px w-full bg-white"></div> <p id="move_to_slide2"> <p class="w-full h-6 text-xs text-gray-400 cursor-pointer">개인정보 입력</p> </p> <div class="h-px w-full bg-white"></div> <p id="move_to_slide3"> <p class="w-full h-6 text-xs text-gray-400 cursor-pointer">핸드폰 인증</p> </p> <div class="h-px w-full bg-white"></div> this is my script. <script> $(document).ready(function() { $('#fullpage').fullpage({ //options here autoScrolling:true, scrollHorizontally: true }); $('#move_to_slide1').click(function(){ fullpage_api.moveTo(1,slide1); }); $('#move_to_slide2').click(function(){ fullpage_api.moveTo(1,slide2); }); $('#move_to_slide3').click(function(){ fullpage_api.moveTo(1,slide3); }); $('#move_to_slide4').click(function(){ fullpage_api.moveTo(1,slide4); }); }); </script> -
django 2 model function is not recognized inside of index.html
hey im new to django so don't be harsh !.im trying to make a blog in django . i need to map the posts in home page to the post page. for that .i have defined a function called get_absulute_url(self) in models.py but it is not recognized in index.html. when i click on Links nothing happens...i'm not where did i made the mistake ! model.py from django.db import models from django.urls import reverse import posts # Create your models here. class post(models.Model): title=models.CharField(max_length=500) content=models.TextField() timestamp=models.DateTimeField(auto_now=False,auto_now_add=True) updated= models.DateTimeField(auto_now=False,auto_now_add=True) def get_absulute_url(self): return reverse("posts:detail", kwargs={'id': self.id}) # return reverse(viewname=posts.views.posts_list,urlconf=any, kwargs={"id": self.id}) views.py def posts_list(request):#list items queryset=post.objects.all() context={ "objectsList":queryset, "title":"list" } return render(request,"index.html",context) index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>{{ title }}</title> </head> <body> {% for obj in objectsList %} <a href="{{ obj.get_absulute_url }}">Link</a><br> <a href="{% url "posts:detail" id=obj.id %}">{{ obj.title }}</a> <br> {{ obj.content }} <br> {{ obj.timestamp }} <br> {{ obj.updated }} <br> {{ obj.id }} <br> {{ obj.pk }} <br> {% endfor %} </body> </html> -
How to delete a spaceil data from database by python django
For example, I have a table called BlackList in the database which looks like this: and the model of the table is: class BlackList(models.Model): list = models.CharField(max_length=1000, null=True, blank=True) What I try to do is: if request.method == "POST": username = request.POST.get('username') # Get username input first password = request.POST.get('password') user = authenticate(request, username=username, password=password) BL = BlackList.objects.values_list('list', flat=True) # Read all data into array if username in BL: # Check if the username is in blacklist # Remove this username from the BlackList table So my question is how to delete the special data for a special, for example, if 'aaa' try to log in, then 'aaa' will be removed or deleted from the BlackList table. -
SyntaxError: unexpected EOF while parsing Django 1:10
I do not know how this works; urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^a/(?P<shortcode>[\w-]+)/$', Loop_redirect_view), url(r'^b/(?P<shortcode>[\w-]+)/$', LoopCBView.as_view()), ^ SyntaxError: unexpected EOF while parsing -
Django, Integrity error on self referring model and weird postgres behavior
I have the following model: class Group(models.Model): name = models.CharField(max_length=255) milking = models.BooleanField(help_text=GroupHelpTexts.MILKING) sub_groups = models.ForeignKey('self', on_delete=models.DO_NOTHING, blank=True) herd = models.ForeignKey(on_delete=models.CASCADE, to=Herd) def __str__(self): return self.name When I'm trying to add a new group in the admin I get the following error: IntegrityError at /admin/farm_api/group/add/ null value in column "sub_groups_id" violates not-null constraint DETAIL: Failing row contains (5, milking 1, t, 1, null). This is the first problem. The second one is that the DB shows this table as empty (At least when accessed from pg admin 4) SELECT * from farm_api_group; outputs an empty table and when I validated from the shell: from farm_api.models.group_models import Group q = Group.objects.all() print(len(q)) 0 print(q) <QuerySet []> -
Access a function via url in django
I'm trying to access a function thats in a class in a file through a url in DJANGO This is my url.py from search import backends as backends from search.backends import AzureSearchBackend urlpatterns = [ url(r'^search/list', AzureSearchBackend.list_index()), ] This is my backends.py - It contains a class which contains the function I wan't to hit import json from collections import defaultdict from search.azuresearch import AzureSearch, AzureSearchException from django.http import JsonResponse class AzureSearchBackend(BaseSearchBackend): mapping_class = AzureMapping index_class = AzureIndex rebuilder_class = AzureIndexRebuilder query_compiler_class = AzureQueryCompiler autocomplete_query_compiler_class = AzureAutocomleteQueryCompiler results_class = AzureSearchResults def __init__(self, params): self.service_name = 'name' self.api_key = 'key' self.api_version = params.pop('AZURE_API_VERSION', '2020-06-30') self.client = AzureSearch(service_name=self.service_name, api_key=self.api_key) def list_index(self): return self.list_index(self) This is my azuresearch.py import json from django.core.serializers.json import DjangoJSONEncoder import requests class AzureSearchException(Exception): def __init__(self, *args, **kwargs): self.response = kwargs.pop('response') self.code = kwargs.pop('code') super().__init__(*args, **kwargs) class AzureSearch(object): ACTION_UPLOAD = 'upload' ACTION_MERGE = 'merge' ACTION_UPLOAD_MERGE = 'mergeOrUpload' ACTION_DELETE = 'delete' CONTENT_TYPE_JSON_HEADER = {'Content-Type': 'application/json'} def __init__(self, service_name, api_key, api_version): self.base_url = f'https://{service_name}.search.windows.net' self.api_key = api_key self.headers = {'api-key': api_key} self.api_version = api_version self.uri_params = {'api-version': api_version} def _handle_error(self, response): error_data = response.json() error = error_data.get('error') raise AzureSearchException(error.get('message'), code=error.get('code'), response=response) def list_indexes(self): response = requests.get(f'{self.base_url}/indexes', headers=self.headers, params=self.uri_params) if response.ok: return … -
Django: How do I get the username of the logged-in user in my class based view?
I have implemented a DeleteView and would like it to redirect it to the logged-in user's profile after deleting the object: class DeleteAttendanceFeedItem(DeleteView, LoginRequiredMixin): model = AttendanceFeedItem template_name = "users/delete_attendance_feed_item.html" context_object_name = "attendance_feed_item" success_url = reverse_lazy("user_profile", kwargs={"username" : request.user.username}) I don't have access to the request object in a class-based view, though. Searching StackOverflow suggests I have access to self.request.user.username, but that's throwing the same error. This seems like a very simple thing that I have burned a surprisingly large amount of time reading SO and Django documentation to absolutely no avail. Help? -
request.GET.get(), How it works in django?
removepunct = request.GET.get('removepunc','off') This is my django template code <form action='/analyze' method='get'> <textarea name='text' style="margin: 0px; width: 1567px; height: 221px;"></textarea> <button type='submit'>Analyze Text</button><br> <input type="checkbox" name="removepunc">Remove Punctutations <input type="checkbox" name="fullcapitalize">Full Capitalize<br> </form> Actually,I am new to django and want to know about request.GET.get(). Actually if checkbox is not checked then it returns "off" the second parameter and if its "on" returns on. I know GET contains GET variable and .get() used for dictionary for getting values of keys but question is "how the second arquement is selected if checkbox is off" because .get() takes keys as a arguements????? -
Showing a table in Django template with optional columns using many to many relationship
I'm building a dynamic tracking app in Django, but i'm struggling to show relational the data in a table. In the app, an Activity can be defined, which can contain 0 or more ActivityMetrics. When a user logs having done an Activity, an Entry is created and the metrics they have entered are stored as multiple ActivityMetricInstances. However, when logging an Entry the ActivityMetrics are optional, leading to my issues showing the data in a table. To give a full example, I created an Activity called "Example Activity". This Activity has 3 ActivityMetrics: Metric 1, Metric 2 and Metric 3. I created 2 Entries like so: Entry Metric 1 Metric 2 Metric 3 ------------------------------------------------------------ Entry2 #2 Metric 1 Data #2 Metric 3 Data Entry1 #1 Metric 1 Data #1 Metric 2 Data #1 Metric 3 Data However, when displaying this data in a table using Django template language, the following happens: This is the code I used for the template: <table class="table"> <thead> <tr> <th scope="col">Date</th> {% if activity_metrics %} {% for activity_metric in activity_metrics %} <th scope="col">{{ activity_metric.name }}</th> {% endfor %} {% endif %} </tr> </thead> <tbody> {% for entry in entries %} <tr> <th scope="row">{{ entry.time }}</th> … -
Can't make Django delete a file when deleting the object associated with it in database
This is the code for the models.py file. from django.db import models from django.db.models.signals import pre_delete from django.dispatch.dispatcher import receiver import os # Create your models here. def create_new_path(instance, filename): return os.path.join('images', instance.project_name.project_name, filename) class Project(models.Model): project_name = models.CharField(max_length=250, primary_key=True) project_title = models.CharField(max_length=300) created_at = models.CharField(max_length=20) modified_at = models.CharField(max_length=20) status = models.CharField(max_length=50) modified_by = models.CharField(max_length=150) series_name = models.CharField(max_length=250, blank=True) def images(self): return self.image_set.filter(project_name=self) class Image(models.Model): project_name = models.ForeignKey(Project, on_delete=models.CASCADE) file_id = models.CharField(max_length=400, primary_key=True) file_name = models.CharField(max_length=200) image = models.FileField(upload_to=create_new_path) @receiver(pre_delete, sender=Image) def image_delete(sender, instance, **kwargs): instance.image.delete() I am trying to delete an image when the object associated with it is deleted. Django successfully deletes the row associated with the image, but the image is not deleted from the media folder. -
Validation POST request by OAuth1.0a in Django
I'm using Django 3.0.7 and i need to validate the incoming POST request from my partner server by HMAC-SHA1 or OAuth1.0a and if it validated send response {"OK":"200"}. My views.py looks like this: def api_create_blog_view(request): blog_post = BlogPost(author=request.user) if request.method == 'POST': serializer = BlogPostSerializer(blog_post, data=request.data) data = {} if serializer.is_valid(): serializer.save() return Response({"response_code":"OK"}) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) There are a lot of topics how to do it, but i can't get how to do it in my case. -
Using a variable for the app name {% url %} in Django template
In my template, I want to refer to a certain URL, let's say it's named homepage. However, this named URL is available in two of my apps, and I am using the same html page that needs to sometimes refer to the one app, and sometimes to the other app. I now have this: <a href="{% if app_name == 'app1' %}{% url 'app1:homepage' %}{% else %}{% url 'app2:homepage' %}{% endif %}">link</a> This is not great and doesn't scale well (sometimes there could be up to 4 apps that may be used here). Ideally I'd use something like this: <a href="{% url app_name + ':homepage' %}">link</a> But this doesn't work. Is there a way to somehow using the app_name as a variable in the url? -
How to create an UniqueConstraint for M2M relationship table in Django ORM?
class MyChoices(models.IntegerChoices): CHOICE_A = 1 CHOICE_B = 2 class MyModelA(models.Model): choice = models.IntegerField(choices=MyChoices.choices) class MyModelB(models.Model): models_a = models.ManyToManyRelationshipField(MyModelA, ...) Is there a way I can create a UniqueConstraint on app_my_model_b_my_model_a table with both models pks? -
How can i allow users to edit there profile in django
I have a model in models.py like this class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.DO_NOTHING) phone_number = models.CharField(max_length=50, default='') Birthday = models.CharField(max_length=50, default='') city = models.CharField(max_length=50, default='') school = models.CharField(max_length=100, default='') course = models.CharField(max_length=50, default='') I want to allow my users to edit it so i made a function like this in my views.py if request.method == 'POST': profil = UserProfile.objects.get(user=request.user) profil.phone_number = models.CharField(max_length=50, default='') profil.Birthday = models.CharField(max_length=50, default='') profil.city = models.CharField(max_length=50, default='') profil.school = models.CharField(max_length=100, default='') profil.course = models.CharField(max_length=50, default='') profil.save() return redirect('profile') return render(request, 'edit_profile.html') my template: <form action="." method="post"> {% csrf_token %} Phone Number: <input type="text" name="phone_number" value="{{ profil.phone_number }}" /><br /> Birthday: <input type="text" name="Birthday" value="{{ profil.Birthday }}" /><br /> city: <input type="text" name="city" value="{{ profil.city }}" /><br /> school: <input type="text" name="school" value="{{ profil.school }}" /><br /> course: <input type="text" name="course" value="{{ profil.course }}" /><br /> <input type="submit" value="Save Changes" name="save" /> <input type="reset" value="Cancel" name="cancel" /> <br/> </form> I dont know but after filling the form i got an error saying page not found. And if i checked the existing user profile nothing got updated. Help please -
Invalid block tag on line 140: 'wagtailuserbar'. Did you forget to register or load this tag? Wagtail error
I am new to wagtail and I am not able to figure out why I am getting this error: Invalid block tag on line 140: 'wagtailuserbar'. Did you forget to register or load this tag?. I am attaching the needful code. --base.html-- {% load static from static %} <!doctype html> <html lang="en"> <head> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous"> <meta charset="utf-8" /> <title> {% block title %} Title {% if self.seo_title %}{{ self.seo_title }}{% else %}{{ self.title }}{% endif %} {% endblock %} {% block title_suffix %} {% with self.get_site.site_name as site_name %} {% if site_name %}- {{ site_name }}{% endif %} {% endwith %} {% endblock %} </title> <meta name="description" content="" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> {# Global stylesheets #} <link rel="stylesheet" type="text/css" href="{% static 'css/mysite_blog.css' %}"> {% block extra_css %} {# Override this in templates to add extra stylesheets #} {% endblock %} {% block head %} {% endblock head %} <style> </style> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> </head> <body class="{% block body_class %}{% endblock %}"> {% wagtailuserbar %} {% block content %}{% endblock %} {# Global javascript #} <script type="text/javascript" src="{% … -
ModuleNotFoundError, why manage.py is looking for a strange file? [duplicate]
I am new to Python and I was trying my first app using django, but I am facing a problem with runserver. Always when I try to run my project I get a message 'ModuleNotFoundError: No module named 'hellodjango'" This 'hellodjango' I do not understand why it is searching for this file... The full message I received is: Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/threading.py", line 932, in _bootstrap_inner self.run() File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/Users/simonestrijk/env1/lib/python3.8/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/Users/simonestrijk/env1/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "/Users/simonestrijk/env1/lib/python3.8/site-packages/django/utils/autoreload.py", line 76, in raise_last_exception raise _exception[1] File "/Users/simonestrijk/env1/lib/python3.8/site-packages/django/core/management/__init__.py", line 357, in execute autoreload.check_errors(django.setup)() File "/Users/simonestrijk/env1/lib/python3.8/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/Users/simonestrijk/env1/lib/python3.8/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/simonestrijk/env1/lib/python3.8/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/Users/simonestrijk/env1/lib/python3.8/site-packages/django/apps/config.py", line 116, in create mod = import_module(mod_path) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 961, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line … -
Django syntax error: unexpected token `('
I've installed Django and moved django-admin to usr/local/bin as suggested on the setup page. When I run django-admin.py startproject myproject It says django-admin permission denied. Django setup page suggests: sudo chmod +x django-admin This removes the permission error but introduces the following: django-admin.py startproject myproject from: can't read /var/mail/django.utils.version /usr/local/bin/django-admin.py: line 3: syntax error near unexpected token `(' /usr/local/bin/django-admin.py: line 3: `VERSION = (3, 0, 8, 'final', 0)' Any idea how to resolve the error? I am using a Mac. Django version 3.0.8. and Python3. Thanks! -
Django data migration: Pass argument to RunPython
I would like to use data migrations to add and delete groups. from django.db import migrations from django.contrib.auth.models import Group groups = ["Test Group"] def add_groups(apps, schema_editor): # https://code.djangoproject.com/ticket/23422 for group in groups: group, created = Group.objects.get_or_create(name=group) if created: print(f'Adding group {group}') class Migration(migrations.Migration): operations = [ migrations.RunPython(add_groups), ] The function uses the variable from outer scope. I would like to move the function somewhere else so I can reuse it in new migrations. However, it seems that I cannot pass any arguments to the function in RunPython. How can I achieve this with migrations.RunPython(add_groups(groups=groups))? -
how to add javascript for like/unlike in django?
views.py def like(req, pk): post = MyPost.objects.get(pk=pk) PostLike.objects.create(post=post, liked_by = req.user.myprofile) #return HttpResponseRedirect(redirect_to="/home/") #if req.is_ajax(): #html = render_to_string('Socialize/like_1.html',req=req,pk=pk) #return JsonResponse({'form':html}) return HttpResponseRedirect(redirect_to="/home/") def unlike(req, pk): post = MyPost.objects.get(pk=pk) PostLike.objects.filter(post=post, liked_by = req.user.myprofile).delete() return HttpResponseRedirect(redirect_to="/home/") in home.html: {% if x.liked %} <a href="{% url 'unlike' x.id %}" id="like"><i class="fa fa-heart" aria-hidden="true"style=" color:red;font-size:36px"></i> </a> {% else %} <a href="{% url 'like' x.id %}" id="like"><i class="fa fa-heart" aria-hidden="true" style="color: LightGray; font-size:25px"></i> </a> {% endif %} urls.py : path('mypost/like/<int:pk>', views.like, name="like"), path('mypost/unlike/<int:pk>', views.unlike, name="unlike"), I tried adding script tags but i don't have the clear idea on how to implement , please help! $(document).ready(function(event){ $(document).on('click', '#like', function(event){ event.preventDefault(): var pk = $(this).attr('x.id'): $.ajax({ type: 'POST', url:'{% url 'like' x.id%}' , data: {'pk':pk, }, dataType: 'json', success: function(response){ ${'#like-section'}.html(response['form']) console.log(${'#like-section'}.html(response['form'])); }, error: function(rs,e){ console.log(rs, responseTet); }, }); }); }); Also, how to add the json response. Any help will be appreciated. -
page not found : / Django
I'm new to Django and I want to add new url but I get this error: Watching for file changes with StatReloader System check identified no issues (0 silenced). July 14, 2020 - 20:19:51 Django version 2.2.2, using settings 'cineam.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Not Found: / here is my url.py: from django.contrib import admin from django.urls import path, include from ticketing import urls urlpatterns = [ path('admin/', admin.site.urls), path('ticketing/', include(urls)) ] ticketing/urls.py : from django.urls import path from ticketing.views import cinema_list urlpatterns=[ path('movies/list/', cinema_list), ] does anybody can help me? -
Accessing request object in django urls.py
I am using generic view (ListView) in Django in order to list out all the questions, current logged in user has asked. I was curious to do it without creating a View in views.py. So in urls.py I added a path like: urlpatterns += [ path('myqn/', views.ListView.as_view(model=models.Question, queryset=models.Question.objects.filter(user__id=request.user.id), template_name='testapp/question_list.html', context_object_name='questions'), name='myqn'), ] Its giving me that: NameError: name 'request' is not defined I know it. Since, request object is passed by the URLConf to the View class/function. So, is there a way, I can access the user.id in this scope. PS: The code works if I replace user__id=9. It lists out all the questions asked by user-9. :) -
Django model property get current_user id
I am trying to add a property in my model where I would like to check if current value like by the user or not. For that I have written the code: @property def current_user_like(self): looks = get_object_or_404(Looks, pk=self.id) user_likes_this = looks.like_set.filter(user=144) and True or False return user_likes_this So my question is can I do like this: @property def current_user_like(self): looks = get_object_or_404(Looks, pk=self.id) user_likes_this = looks.like_set.filter(user=request.user.id) and True or False return user_likes_this What would be the best way to achieve this functionality I am using Django rest framework so I added this property to the serializer. Can I do this if not what else I should do? -
Django url, admin path doesn't have /admin/ in it
Django==2.1 Python 3.5.7 I'm trying to save admin form and the url is /admin/landing/banner/add/ but in debug it says that it is landing/banner/add/ Page not found (404) Request Method: POST Request URL: http://********.****/admin/landing/banner/add/ Raised by: django.contrib.admin.options.add_view Using the URLconf defined in mainapp.urls, Django tried these URL patterns, in this order: ^$ [name='index'] contact/ demo/ success/ ^media/(?P<path>.*)$ ^static/(?P<path>.*)$ admin/ The current path, landing/banner/add/, didn't match any of these. urls.py from django.contrib import admin from django.urls import include, path urlpatterns = [ path('', include('landing.urls')), path('admin/', admin.site.urls), ] landing urls.py from django.urls import path from django.conf.urls import include, url from . import views from django.views.static import serve from django.conf import settings from django.conf.urls.static import static urlpatterns = [ url(r'^$', views.index, name='index'), path('', include('contact.urls')), url(r'^media/(?P<path>.*)$', serve, { 'document_root': settings.MEDIA_ROOT, }), url(r'^static/(?P<path>.*)$', serve, { 'document_root': settings.STATIC_ROOT, }), ] contact urls.py from django.contrib import admin from django.urls import path from .views import ContactView, SuccessView, DemoView urlpatterns = [ path('contact/', ContactView.as_view()), path('demo/', DemoView.as_view()), path('success/', SuccessView.as_view()), ]