Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django display error messages for default login backend
I am using Django's default authentication backend, and I cannot get the messages framework to work with it to show error messages (such as incorrect username, invalid password etc). Everything that I have searched through here to suggest to make a custom authentication backend, but is there any easier way to do it? I already have a form which is subclassing the AuthenticationForm to use form_valid method, is there anything I could do there? Any help would be really appreciated. -
ModuleNotFoundError at /api/social/convert-token No module named 'path.to'
Hi Im trying to Authenticate Users on an foodtasker project using POSTMAN, but I have an error, could anyone help me please. Error is the following: ModuleNotFoundError at /api/social/convert-token No module named 'path.to' Traceback: File "/Users/cfvs/Desktop/myvirtualenv/foodtasker/lib/python3.7/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/Users/cfvs/Desktop/myvirtualenv/foodtasker/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "/Users/cfvs/Desktop/myvirtualenv/foodtasker/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/cfvs/Desktop/myvirtualenv/foodtasker/lib/python3.7/site-packages/django/views/decorators/csrf.py" in wrapped_view 54. return view_func(*args, **kwargs) File "/Users/cfvs/Desktop/myvirtualenv/foodtasker/lib/python3.7/site-packages/django/views/generic/base.py" in view 71. return self.dispatch(request, *args, **kwargs) File "/Users/cfvs/Desktop/myvirtualenv/foodtasker/lib/python3.7/site-packages/django/utils/decorators.py" in _wrapper 45. return bound_method(*args, **kwargs) File "/Users/cfvs/Desktop/myvirtualenv/foodtasker/lib/python3.7/site-packages/django/views/decorators/csrf.py" in wrapped_view 54. return view_func(*args, **kwargs) File "/Users/cfvs/Desktop/myvirtualenv/foodtasker/lib/python3.7/site-packages/braces/views/_forms.py" in dispatch 30. return super(CsrfExemptMixin, self).dispatch(*args, **kwargs) File "/Users/cfvs/Desktop/myvirtualenv/foodtasker/lib/python3.7/site-packages/rest_framework/views.py" in dispatch 505. response = self.handle_exception(exc) File "/Users/cfvs/Desktop/myvirtualenv/foodtasker/lib/python3.7/site-packages/rest_framework/views.py" in handle_exception 465. self.raise_uncaught_exception(exc) File "/Users/cfvs/Desktop/myvirtualenv/foodtasker/lib/python3.7/site-packages/rest_framework/views.py" in raise_uncaught_exception 476. raise exc File "/Users/cfvs/Desktop/myvirtualenv/foodtasker/lib/python3.7/site-packages/rest_framework/views.py" in dispatch 502. response = handler(request, *args, **kwargs) File "/Users/cfvs/Desktop/myvirtualenv/foodtasker/lib/python3.7/site-packages/rest_framework_social_oauth2/views.py" in post 70. url, headers, body, status = self.create_token_response(request._request) File "/Users/cfvs/Desktop/myvirtualenv/foodtasker/lib/python3.7/site-packages/oauth2_provider/views/mixins.py" in create_token_response 124. return core.create_token_response(request) File "/Users/cfvs/Desktop/myvirtualenv/foodtasker/lib/python3.7/site-packages/oauth2_provider/oauth2_backends.py" in create_token_response 149. headers, extra_credentials) File "/Users/cfvs/Desktop/myvirtualenv/foodtasker/lib/python3.7/site-packages/oauthlib/oauth2/rfc6749/endpoints/base.py" in wrapper 116. return f(endpoint, uri, *args, **kwargs) File "/Users/cfvs/Desktop/myvirtualenv/foodtasker/lib/python3.7/site-packages/rest_framework_social_oauth2/oauth2_endpoints.py" in create_token_response 60. request, self.default_token_type) File "/Users/cfvs/Desktop/myvirtualenv/foodtasker/lib/python3.7/site-packages/oauthlib/oauth2/rfc6749/grant_types/refresh_token.py" in create_token_response 60. self.validate_token_request(request) File "/Users/cfvs/Desktop/myvirtualenv/foodtasker/lib/python3.7/site-packages/rest_framework_social_oauth2/oauth2_grants.py" in validate_token_request 91. user = backend.do_auth(access_token=request.token) File "/Users/cfvs/Desktop/myvirtualenv/foodtasker/lib/python3.7/site-packages/social_core/backends/facebook.py" in do_auth 153. return self.strategy.authenticate(*args, **kwargs) File "/Users/cfvs/Desktop/myvirtualenv/foodtasker/lib/python3.7/site-packages/social_django/strategy.py" … -
mock.patch() Not patching function in module call, but is in test function
So I am trying to mock a function and it is not being mocked in the module where it is being called, but it when called directly in the test function. I am unsure what I'm doing wrong. I use patch all the time without any problems. So in the test I have below from unittest.mock import patch from django.test import TestCase from web.utils.registration import test_render_mock class TestRenderMock(TestCase): @patch("django.shortcuts.render") def test_render_mock(self, render_mock): request = self.make_request() # Calls render in same way in function below test_render_mock(request) from django.shortcuts import render r = render(request, 'c') print(type(r)) which is calling the function in the file web/utils/registration.py from django.shortcuts import render def test_render_mock(request): r = render(request, 'registration/signup_link_error.html') print(type(r)) And it isn't mocking the render call in the function test_render_mock but it is in the test function test_render_mock(). The console output is below. <class 'django.http.response.HttpResponse'> <class 'unittest.mock.MagicMock'> I have no idea what I'm doing wrong. Any help would be appreciated. Using python version 3.8.2 and Django 3.0.5 -
Test a Django model that uses request.user in save_model
I have a Django model that overrides save_model in order to automatically save the current authenticated user into a field on save. The question is, how in a unit test can I test the creation of this model, without having to go through a view? The model: class SomeClass(models.Model): def save_model(self, request, obj, form, change): self.prevent_update() if not obj.pk: # Only set added_by during the first save. obj.created = request.user super().save_model(request, obj, form, change) The test just wants to set up SomeClass before doing some other stuff. class SomeClassTestCase(TestCase): def setUp(self): self.assertTrue(request.user) SomeClass.objects.create(name="abc") I know that there is a request getting set up automatically, since request.user doesn't fail with request being None; instead, the query constraint fails because the user is null. How do I set a user on the request that appears to have been passed into save_model Alternatively, I know I can setup a request using RequestFactory and generate a user. In that case, how do I get that into the test so that the SomeClass.objects.create actually sees it. -
Python/Django creating several classes from variable through looping
I'm working with Python Django and I'm trying to create a forum with several subpages - each subpage concerns another topic and should look the same but store different posts. I want to create several classes (not instances!) with a similar name and same attributes. Each class should have another template name and render other posts. Something like this: my_variable = 'part_of_class_name' for class_number in range(2, 5): class_name = my_variable + str(class_number) + '(SameParentClass)' class class_name: template_name = 'template' + str(class_number) + '.html' Of course, the code above doesn't work, is it a possibility to pass a variable to a class name? I want the following: part_of_class_name2(SameParentClass), part_of_class_name3(SameParentClass), part_of_class_name4(SameParentClass). How can I do it by looping? I want to avoid making three classes. -
Show model parent fields in Django's admin model details
I let most of my models inherit from: class TimeStampedModel(models.Model): created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: abstract = True get_latest_by = 'updated_at' Like this: class Sale(TimeStampedModel): ip_address = models.GenericIPAddressField(null=True) # ... However, if I visit /admin/myapp/sale/123/change/ I only see the ip_address field. How can I also get to see the created_at and updated_at fields? Possibly, without having to specify every single field of Sale in a list. -
need to understand the ur to path converter in Django
i am learn to Django . i have stuking the below URL . i use path but i went to convert it to my path URL pattern . This is my actual Path patrn path('', views.home,name='home'), path('topics/<int:id>/', views.board_topic, name='topics'), path('topics/<int:id>/new/', views.new_topic,name='new_topic'), path('signup/', accounts_views.signup, name='signup'), i went to convert below this comented url to the below path path('topics/<int:id>/topic_id', views.topic_posts, name='topic_posts'), # url(r'^boards/(?P<pk>\d+)/topics/(?P<topic_pk>\d+)/$', views.topic_posts, name='topic_posts'), This is Good Formate ? if not then which is best url to path formate ? Thank You -
How do I display search results on my URL on django. ex www.123.com/Search=THIS+IS+SEARCH+RESULTS
So i'm building a website scraper and so far I can scrape search results fine, the problem is my URL is always the same which is 127.0.0.1:8000/search_results I'd love to be able to make it look like 127.0.0.1:8000/search_results=Hello if I search for "Hello" in my search box. Thank you all -
How to solve "from _sqlite3 import * ImportError: DLL load failed: The specified module could not be found." error
I'm beginner in Django . I use pycharm but when I want to run server with "python manage.py runserver" in pycharm terminal It says "from _sqlite3 import * ImportError: DLL load failed: The specified module could not be found. ". -
how to 'ignore the data and leave the instance as it is' in a ModelSerializer update
I have a field in my models that is an ImageField and every time I try to update a data using the browsable API. The API returns an error for my ImageField which is The submitted data was not a file. Check the encoding type on the form. when it's empty but in the instance it is not. How can I ignore the data and leave the instance as it is when updating? But when I upload an image in the imagefield, no error returns. Model class Report(models.Model): # other fields image = models.ImageField(upload_to="reports/image-report/", max_length=1000, null=True, blank=True) Serializer class ReportSerializer(serializers.ModelSerializer): # other fields image = serializers.ImageField(max_length=None, allow_empty_file=True, use_url=True) class Meta: model = Report fields = "__all__" def update(self, instance, validated_data): # other fields instance.image = validated_data.get('image', instance.image) instance.save() return instance Viewset class ReportViewSet(viewsets.ModelViewSet): queryset = Report.objects.all() serializer_class = ReportSerializer permission_classes = [IsAuthenticated] parser_classes = (MultiPartParser, FormParser) # for uploading attachments pagination_class = LimitOffsetPagination -
How to pass current logged user in a form class in django
I am trying to create a form where one field is a ModelChoicefield. Im trying to populate that field with objects from a different model. I have ran into a problem as i need to get the current logged user within the form to filter the queryset. Here are the 2 models class UserExercises(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=50) Muscle = models.ForeignKey(Muscle, on_delete=models.CASCADE) class Exercise(models.Model): exercise = models.ForeignKey(UserExercises, on_delete=models.CASCADE) weight = models.DecimalField(max_digits=6, decimal_places=3) reps = models.PositiveIntegerField(validators=[MaxValueValidator(100)]) difficulty = models.CharField(max_length=30) date = models.DateTimeField(default=timezone.now) user = models.ForeignKey(User, on_delete=models.CASCADE) And here is my form class AddExerciseForm(forms.Form): exercise = forms.ModelChoiceField(queryset=UserExercises.objects.filter(user=1)) class Meta: model = Exercise fields = ['exercise', 'weight', 'reps', 'difficulty'] As you can see i am currently hard coding a filter in the ModelChoiceField, but want to replace that with the current users Id. Is there anyway of Going about this. Im new to django so any help would be Appreciated. -
ModuleNotFoundError: No module named 'django.contrib.admin' in p
hi i know this is repetitive question but i checked everywhere and i checkd my urls and import stuffs but it does not fix i don't know which file path is incorrect i clone my project from github and my project in localhost works all right but in pythonanywhere.com i have this error here is my wsgi.py code: import os import sys path = '/home/gazegan/blood-donor/bblood/' if path not in sys.path: sys.path.append(path) os.environ['DJANGO_SETTINGS_MODULE'] = 'bblood.settings' from django.core.wsgi import get_wsgi_application application = get_wsgi_application() and this is the full error: Error running WSGI app ModuleNotFoundError: No module named 'bblood' File "/var/www/gazegan_pythonanywhere_com_wsgi.py", line 57, in <module> application = get_wsgi_application() File "/home/gazegan/.virtualenvs/myenv/lib/python3.8/site-packages/django/core/wsgi.py", line 12, in django.setup(set_prefix=False) File "/home/gazegan/.virtualenvs/myenv/lib/python3.8/site-packages/django/__init__.py", line 19, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "/home/gazegan/.virtualenvs/myenv/lib/python3.8/site-packages/django/conf/__init__.py", line 76, in __getattr__ self._setup(name) File "/home/gazegan/.virtualenvs/myenv/lib/python3.8/site-packages/django/conf/__init__.py", line 63, in _setup self._wrapped = Settings(settings_module) File "/home/gazegan/.virtualenvs/myenv/lib/python3.8/site-packages/django/conf/__init__.py", line 142, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) please help me :( -
Form unable to center and max width
I have a form that I would like to center in a div, but also apply a max-width Here is what I have: HTML: <div class="site-section mb-5"> <div class="container"> <div class="form-register"> <form method="POST"> {% csrf_token %} <legend>Join Today</legend> {{ form|crispy }} <button class="btn btn-outline-info" type="submit">Sign Up</button> </form> </div> <p class="p-center">Already Have An Account? <a class="ml-2" href="{% url 'login' %}">Sign In</a> </p> </div> </div> CSS: .form-register { display: inline; margin: 0 auto; } form { width: 80%; max-width: 300px; display: inline; margin: 0 auto; } However if I switch the width and max-width between the two CSS classes, I get either of the following results: or -
Visual Studio Code Django project Error 404 Not Found
My project is named Travello, following this here: https://www.youtube.com/watch?v=Tt3mgy2ECug&list=PLsyeobzWxl7r2ukVgTqIQcl-1T0C2mzau&index=12) , When I runserver I get this error. Anybody have any clue how to fix this error: [16/Apr/2020 20:27:21] "GET / HTTP/1.1" 200 22122 [16/Apr/2020 20:27:21] "GET /static/styles/bootstrap4/bootstrap.min.css HTTP/1.1" 404 1731 [16/Apr/2020 20:27:21] "GET /static/images/destination_2.jpg HTTP/1.1" 404 1698 [16/Apr/2020 20:27:21] "GET /static/images/destination_5.jpg HTTP/1.1" 404 1698 Not Found: /images/intro.png Not Found: /images/travello.jpg [16/Apr/2020 20:27:21] "GET /images/intro.png HTTP/1.1" 404 2149 [16/Apr/2020 20:27:21] "GET /images/travello.jpg HTTP/1.1" 404 2158 [16/Apr/2020 20:27:21] "GET /static/styles/bootstrap4/bootstrap.min.js.map HTTP/1.1" 404 1740 [16/Apr/2020 20:27:21] "GET /static/styles/bootstrap4/popper.js.map HTTP/1.1" 404 1719 Not Found: /images/testimonials.jpg [16/Apr/2020 20:27:21] "GET /static/images/footer_1.jpg HTTP/1.1" 404 1683 [16/Apr/2020 20:27:21] "GET /images/testimonials.jpg HTTP/1.1" 404 2170 Not Found: /images/home_slider.jpg [16/Apr/2020 20:27:21] "GET /images/home_slider.jpg HTTP/1.1" 404 2167 My settings.py file looks like this: Django settings for telusko project. Generated by 'django-admin startproject' using Django 3.0.5. For more information on this file, see https://docs.djangoproject.com/en/3.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.0/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # SECURITY WARNING: keep the secret key used in production secret! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = … -
Django Error when calling to other project url to get data
I have gone into a bit of trouble. I have to call the url of Project 1 from Project 2 views to get the JSON data but when I am trying to call the url using requests it gives me "Max retries exceeded with url" error. Both the projects are using Django 3 Project 1 is running on port 8001 and the other is on port 8000 Please help me out i thought it was a simple task as everything is working fine when doing the same in terminal or python file. # Project 1 views.py def send_master_data(request): return JsonResponse(provide_master_data()) urls.py path('masterdata/', views.send_master_data, name='send_master_data'), # Project 2 views.py @decorators.login_required def export_master_excel(request): with requests.Session() as session: res = session.get("http://127.0.0.1:8001/masterdata/") data = res.json() response = HttpResponse(content_type='application/ms-excel') response['Content-Disposition'] = f'attachment; filename="{data["metadata"]["filename"]}"' wb = Workbook() -
how to pass form object to html and use each item in the object in django
I have a class called user form (UserMyProfilePersonalForm) class UserMyProfilePersonalForm(forms.ModelForm): username = forms.CharField(widget=forms.TextInput, max_length=50) first_name = forms.CharField(widget=forms.TextInput, max_length=100) last_name = forms.CharField(widget=forms.TextInput, max_length=100) email = forms.CharField(widget=forms.EmailInput, disabled=True) dob = forms.CharField(widget=forms.DateInput, required=True) profile_pic = forms.CharField(widget=forms.TextInput) def __str__(self): return f"{self.username},{self.first_name}, {self.last_name},{self.email},{self.dob}, self.profile_pic}" class Meta(): model = UserMyProfilePersonal fields = ("email", ) then in my view file, I created an object of this class newUserMyProfilePersonalForm = UserMyProfilePersonalForm.from_json(user_detail) print(newUserMyProfilePersonalForm.email) context_data = {"newUserMyProfilePersonalForm": newUserMyProfilePersonalForm} return render(request, "home.html", context_data) Now I don't know how to fetch the data in the HTML. I tried multiple things 1. below code prints all the value as dummyusername,fname, lname,email@gmail.com,10/05/1990... this output looks the same as str function {{newUserMyProfilePersonalForm}} I tried {{newUserMyProfilePersonalForm.as_p}} but this prints all the items as a form with textbox and label but without any value in the textbox. I want to have a textbox with values as user data e.g. email, username because I want to create "EDIT PRofile" section. -
Django form prefix returns an empty form on GET method
I'm trying to show multiple forms prefilled with data from model instances. Then I would like to use Django "prefix" kwarg for Forms. However as soon as I use that "prefix" argument in a form and send data to display with it it returns empty with no form error showing. I wrote a very simple example hereunder with 2 forms : the first has no prefix and works properly, the 2nd has a prefix and does not. I would love some help ! Many thanks ! models.py class Production_Plan_Data(models.Model): production_plan = models.ForeignKey( Production_Plan, on_delete=models.CASCADE, related_name="production_plan_data", verbose_name="production plan data" ) week_number = models.PositiveSmallIntegerField(verbose_name="Week Number") product = models.ForeignKey( Product, on_delete=models.PROTECT, related_name="production_plan_product", verbose_name="production plan product" ) value = models.PositiveIntegerField(verbose_name="Week Value") creation_date = models.DateTimeField(auto_now_add=True) update_date = models.DateTimeField(auto_now=True) class Meta: verbose_name = "Production Plan Data" ordering = ["production_plan", "product", "week_number"] def __str__(self): return self.production_plan forms.py class Production_Plan_Data_Form(forms.ModelForm): class Meta: model = Production_Plan_Data fields = ["product", "week_number", "value"] view.py class Tests_View(TemplateView): template_name = "load_mgmt/tests.html" def get(self, request, **kwargs): current_item = Production_Plan_Data.objects.get(pk=105) current_item_data = { 'product': current_item.product, 'week_number': current_item.week_number, 'value': current_item.value } form_prefix = "form" + str(current_item.pk) form1 = Production_Plan_Data_Form(instance=current_item) # form1 = Production_Plan_Data_Form(current_item_data, prefix="tt") current_item2 = Production_Plan_Data.objects.get(pk=106) current_item_data2 = { 'product': current_item2.product, 'week_number': current_item2.week_number, 'value': current_item2.value … -
Populate a DataBase from an API in Django
I am building a Django project with a postgresql in it. This databasa has to be populated from an API. This database doesn't have to be updated. As I understood, the tables inside my database have to be created in my Django models. But where should I populate it? In a script outside Django or inside my app views? -
Django failed with Authentication credentials were not provided
I have tried to use Django basic Authentication feature to verify username(test) and password(test). It works from my local: curl -H 'Accept: application/json; indent=4' -u test:test 'http://127.0.0.1:8000/api/checkuser/' { "detail": "Account authorized." } But it failed from production site: curl -H 'Accept: application/json; indent=4' -u test:test 'https://production.fake/api/checkuser/' { "detail": "Authentication credentials were not provided." } I have tried to enable WSGIPassAuthorization from production server, but it does not help. It seems to me that somehow the username and password did not really pass through, but cannot figure out how. Any advice to troubleshoot will be really appreciated. Thanks! -
Directing Output Paths of Altered Files
I am sorry if this is a dumb question, it seems like it would be simple but has been driving me nuts for days. How can I direct the destination of the output file "pdf01.pdf" to my db? PdfFileWriter().write(open("pdf01.pdf", "wb")) I have gotten the file to successfully output however, it output's to my src directory. My models.py is structured like so: class Model(models.Model): char = models.CharField(max_length=50, null=False, blank=False) file = models.FileField(upload_to=upload_location, null=True, blank=True) I have the user enter a value for 'char', and then the value of 'char' is printed on to a file. The process of successfully producing the file is working, however, the the file is outputting to my source directory. My goal is to have the output file 'pdf01.pdf' output to my db and be represented as 'file' so that the admin can read it. Much of the information in the django docs has been focussed on directing the path of objects imported by the user directly, not on files that have been created by m using the user's data. I have been reading mostly from these docs: Models-Fields Models File response objects I have seen it recommend to write to a buffer, not a file, then … -
Django Autocomplete-Light stuck on autocomplete input field
I've read almost all topics here related to autocomplete-light in django, and I'm still stuck on getting autocomplete input field in my form. Let me explain what I am trying to do. I am building contract template page, where user first input employees data, also populate partner company data and some other relevant data, and then goes to the Create Contract page, where they need to fill the form: search Employee and select, search partner company (which the employee will sign contract with), input other relevant data, and Insert contract details into the base. I am stuck on this "search Employee and select", because I can't get autocomplete input field, but only select field with populated data from my base. Here's my code: settings.py INSTALLED_APPS = [ 'dal', 'dal_select2', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'cargo_contracts', 'django_filters', ] models.py class Contracts(models.Model): employee = models.ForeignKey(Employee, on_delete=models.CASCADE, null=True) partner_company = models.ForeignKey(PartnerCompany, on_delete=models.CASCADE, null=True) contract_type = models.ForeignKey(ContractTypes, on_delete=models.CASCADE, blank=False) car = models.ForeignKey(Cars, on_delete=models.CASCADE, null=True) contract_number = models.IntegerField(default=0, null=True) signing_date = models.DateField(auto_now_add=False, blank=True, null=True) salary = models.IntegerField(default=0, null=True) contract_percentage = models.IntegerField(default=0, null=True) def __str__(self): return str(self.contract_type) class Meta: verbose_name_plural = 'Contracts' class Employee(models.Model): name = models.CharField(max_length=128, unique=False) jmbg_number = models.CharField(max_length=13) address = models.CharField(max_length=PartnerCompany.ADDRESS_NAME_MAX_LENGTH, unique=False) … -
remove default apps in INSTALLED_APPS
I'm new to Django and python in general and i'm trying to set up a RESTful api using Django and Django Rest Framework, so my problem is that i want to get rid of the default installed apps, something like this: INSTALLED_APPS = [ #'django.contrib.admin', #'django.contrib.auth', #'django.contrib.contenttypes', #'django.contrib.sessions', #'django.contrib.messages', #'django.contrib.staticfiles', 'rest_framework', 'myapp', ] since i want a simple api with no UI that provides me with some data. But when i run python manage.py makemigrations i get the followin error: LookupError: No installed app with label 'admin' does this mean these apps are essential? Thanks in advance. -
Django: Correct "url" tag for use in emails? (A complete "http://..." tag.)
I naively used the {% url tag in an email body, only to discover that it didn't include the site-name. What should I do to create a hyperlink, for use in an email body, that does include the proper site-name? Instead of /foo/bar ... which is the string that the tag returns ... I want: h-t-t-p-s://mysite.com/foo/bar (you know what I meant!) ... without having to hard-code the site-name as a literal in the template. -
Search Option inside category
I'm trying to make a feature where a user can click on a category, and then search within that category. My problem is I can't seem to get the category pk in the html. I've fried my brain trying to find a way, but no luck yet. <form class="searchfield" action="{% url 'posts:cat_search' pk= %}" method="get"> <button type="submit" name="button"> <i class="fa fa-search"></i> </button> <input class="searchfield" id="searchbox" name='q' type="text" placeholder="Search"> </form> I need to specify a category pk for the search, but how? I can grab all the category pks, but just not the one for the correct category class PostListView(LoginRequiredMixin, ListView): model = Post def categories(self): return Category.objects.all() def get_queryset(self): return Post.objects.filter(created_date__lte=timezone.now()).order_by('-created_date') class PostCatView(PostListView): template_name = 'posts/post_category.html' def get_queryset(self): result_pk = self.kwargs.get('pk') return Post.objects.filter(label=self.kwargs.get('pk')).order_by('-created_date') class CategorySearchView(PostCatView): def get_queryset(self): result = super(PostCatView, self).get_queryset() query = self.request.GET.get('q') if query: query_list = query.split() result = result.filter( reduce(operator.and_, (Q(title__icontains=q) for q in query_list)) | reduce(operator.and_, (Q(body__icontains=q) for q in query_list)) ) return result -
Annotating djagno queryset not returning annotations using backwards foreign key. Using geodjango
I have a mysterious problem where annotations are not showing up on queryset using backwards foreign key. Using Django 2.2. Models from django.contrib.gis.db import models class Hexgrid_10km2(models.Model): polygon = gismodels.MultiPolygonField(srid=4326) class Reply(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) reply_date = models.DateTimeField() ability = models.FloatField(default = 0) hexgrid_10km2 = models.ForeignKey(Hexgrid_10km2, related_name='replies', on_delete=models.CASCADE, null=True, blank=True) Problem I am first filtering the Hexgrid_10km2 to only those containing Replies as so: most_recent = Reply.objects.filter( reply_date=Subquery( (Reply.objects .filter(user=OuterRef('user')) .values('user') .annotate(most_recent=Max('reply_date')) .values('reply_date')[:1] ) ) ) hex_qs = Hexgrid_10km2.objects.filter(replies__in=most_recent) >>> hex_qs <QuerySet [<Hexgrid_10km2: Hexgrid_10km2 object (197028)>, <Hexgrid_10km2: Hexgrid_10km2 object (197028)>]> I check to see that they do contain replies as so: >>> hex_qs.aggregate(Sum('replies__ability')) {'replies__ability__sum': 2.0} Now the mystery... >>> hex_qs.annotate(avg_ability=Avg('replies__ability')) <QuerySet [<Hexgrid_10km2: Hexgrid_10km2 object (197028)>]> Where is the annotation? Does it have something to do with geodjango which I am using to build the models? I am feeling like a fool. Many thanks for your help as am completely stuck.