Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ERROR: Command errored out with exit status 1:
ERROR: Failed building wheel for mysqlclient ERROR: Command errored out with exit status 1 error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools": https://visualstudio.microsoft.com/downloads/ RROR: Command errored out with exit status 1: 'c:\python\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\Users\Admin\AppData\Local\Temp\pip-install-sxz0ni7x\mysqlclient\setup.py'"'"'; file='"'"'C:\Users\Admin\AppData\Local\Temp\pip-install-sxz0ni7x\mysqlclient\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' install --record 'C:\Users\Admin\AppData\Local\Temp\pip-record-li2rtx7t\install-record.txt' --single-version-externally-managed --compile Check the logs for full command output -
Django form instance test fail
I used datetime picker in front end. author creation form class AuthorCreationForm(forms.ModelForm): class Meta: model = Author fields = ('first_name', 'last_name', 'born', 'died', 'image', ) ====================================================================== FAIL: test_author_form (book.tests.test_view.TestAuthorCreatePage) Traceback (most recent call last): File "/home/kaung/workspace/library-management-system/config/book/tests/test_view.py", line 460, in test_author_form self.assertIsInstance(form, self.creation_form) AssertionError: is not an instance of -
i am getting an NoreverseMatch at / ,
I am trying to improve my models and html files for my project and while finding the solution on internet ive got this particular error. i've tried importing render and resolvers, and also trying looking out for solution on stackoverflow but nothing works for me. #here's urls.py from django.contrib import admin from django.urls import path from accounts import views as accounts_views from django.contrib.auth import views as auth_views from boards import views urlpatterns = [ path('boards/<int:pk>/topics/<topic_pk>/', views.topic_posts, name='topic_posts'), path('boards.<int:pk>/topics/<topic_pk>/reply/', views.reply_topic, name='reply_topic'), ] #here's line from base.html where its showing error <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#mainMenu" aria-controls="mainMenu" aria- expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> #here are my models.py file from django.contrib.auth.models import User from django.db import models from django.utils.text import Truncator class Board(models.Model): name = models.CharField(max_length=30, unique=True) description = models.CharField(max_length=100) def __str__(self): return self.name def get_posts_count(self): return Post.objects.filter(topic__board=self).count() def get_last_post(self): return Post.objects.filter(topic__board=self).order_by('- created_at').first() and i am getting this error "Reverse for 'topic_posts' with arguments '(2, '')' not found. 1 pattern(s) tried: ['boards/(?P<pk>[0- 9]+)/topics/(?P<topic_pk>[^/]+)/$']" -
How to alter label tag of fieldset in admin.tabularinline
I customized my add user form in my django admin, using admin.tabularinline. So whenever the admin adds a user, information about Usermodel and UserProfile model is saved at the same time. However, the label tag of the UserProfile form says 'Staff Profiles'(with 's'). And it doesn't look good because there is only one profile for one user. Any ideas how to change the "Staff Profiles" into "Staff Profile"? See the picture for refenrce: -
Normalize Django Field's Value
I wrote a custom django field to normalize the urls our system received. However, the url will only return normalized value after reload. from django.db import models def _rewrite_internal_url(url): # return 'http://www.google.com/1.jpg' class NormalizedURLField(models.URLField): def to_python(self, value): value = super().to_python(value) return _rewrite_internal_url(value) def from_db_value(self, value, expression, connection): if value is None: return value return _rewrite_internal_url(value) class DjangoTest(models.Model): url = NormalizedURLField() instance = DjangoTest.objects.create(url="http://www.google.com/2.jpg") print(instance.url) # still http://www.google.com/2.jpg instance.referesh_from_db() print(instance.url) # update to http://www.google.com/1.jpg -
How to remove the error when migrate in django?
I have a code which is to show the balance 0 in html page by default when someone new register itself. After makemigrations it works but after typing migrate it didn't work. Instead it gives me error. How to deal with this? models.py class Balance(models.Model): amount = models.DecimalField(max_digits=12, decimal_places=2, default=0) owner = models.OneToOneField(get_user_model(), on_delete=models.CASCADE) views.py @login_required def balance(request): try: balance = request.user.balance except Balance.DoesNotExist: balance = None return render(request, 'nextone/balance.html', {'balance': balance}) Html page {% if balance.amount %} <h2>Your Balance is Rs. {{balance.amount}}</h2> {% else %} <h2>Your Balance is Rs. 0</h2> {% endif %} Error after I migrate File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\Bilal\Envs\trial\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\Bilal\Envs\trial\lib\site-packages\django\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Bilal\Envs\trial\lib\site-packages\django\core\management\base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\Bilal\Envs\trial\lib\site-packages\django\core\management\base.py", line 364, in execute output = self.handle(*args, **options) File "C:\Users\Bilal\Envs\trial\lib\site-packages\django\core\management\base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\Bilal\Envs\trial\lib\site-packages\django\core\management\commands\migrate.py", line 234, in handle fake_initial=fake_initial, File "C:\Users\Bilal\Envs\trial\lib\site-packages\django\db\migrations\executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "C:\Users\Bilal\Envs\trial\lib\site-packages\django\db\migrations\executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "C:\Users\Bilal\Envs\trial\lib\site-packages\django\db\migrations\executor.py", line 245, in apply_migration state = migration.apply(state, schema_editor) File "C:\Users\Bilal\Envs\trial\lib\site-packages\django\db\migrations\migration.py", line 124, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File … -
How to force to use new database when run python manage.py test in Django?
When I type python manage.py test Sometimes I get asked if I want to delete the test database. Type 'yes' if you would like to try deleting the test database 'test_replicate_live', or 'no' to cancel: yes WHen I want to keep the test database, I know the command is : python manage.py test --keepdb I would like to know if there's a way to force the deletion of test database without waiting for the question to appear. Sometimes I just know ahead of time, I want to delete the test database. Is tehre a python manage.py test --nokeepdb -
Bootstrap theme disappears when passing pk parameter, but uses Bootstrap4 default design
I'm using a bootstrap theme, Looper. Everything was going great on my "prescription_request_review.html" page, which contains a Bootstrap table and a Bootstrap form, until I added a pk parameter to the page. Instead of displaying my bootstrap theme as every other page does, it displays what I assume are Bootstrap4 defaults (bright blue button, plain white background, simple design.) I tried removing part or all of the {% block extrahead %} in prescription_request_review.html, but all it does is remove ALL Bootstrap components. Why would my theme change just because I'm passing a pk to the page? vhome.html Page where user can click prescription in rxtable.html, redirecting to the page I'm having the issue with: {% extends 'app/main/base.html' %} {% block extracss %} <link rel="stylesheet" type="text/css" href="static/assets/DataTables/datatables.css"/> {% endblock extracss %} {% block content %} {% include "app/veterinary/snippets/rxtable.html" %} {% endblock content %} {% block extrascripts %} <script type="text/javascript" src="static/assets/DataTables/datatables.min.js"></script> <script type="text/javascript"> $(document).ready( function () { $('#vrxTable').DataTable({ "order": [[ 6, "desc" ]], "paging": false, "info": false, "searching": false, "columnDefs": [ { "targets": 0, "orderable": false } ] }); }) </script> {% endblock extrascripts %} rxtable.html (actual table where the buttons are that lead to my problem page: <!-- list of open … -
Cannot redirect to correct URL after login using allauth get_login_redirect_url
I have a custom user model and am using django-allauth to manage the login ,sign up, logout functions. I have 5 user types and after each type login, they will be directed to separate pages. The usual LOGIN_REDIRECT_URL is not suitable for me since it can only redirect to one page no matter what type of users login. I found out that by using Custom Account Adaptor and override get_login_redirect_url()can make it work, so I implemented it. users.adaptor.py from django.conf import settings from allauth.account.adapter import DefaultAccountAdapter from django.http import HttpResponseRedirect, HttpResponse from django.shortcuts import resolve_url, redirect class MyAccountAdapter(DefaultAccountAdapter): def get_login_redirect_url(self, request): # path = super(MyAccountAdapter, self).get_login_redirect_url(request) current_user=request.user if current_user.user_type == 1: path='doc/dochome/' elif current_user.user_type == 2: path='lab/labhome/' elif current_user.user_type == 3: path='recep/recephome/' elif current_user.user_type == 4: path='patient/patienthome/' elif current_user.user_type == 5: path='admini/adminhome/' else: return HttpResponse("Your Rango account is disabled.") return path # .format(username=request.user.id) settings.py 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__))) STATIC_DIR = os.path.join(BASE_DIR, 'static') TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates') MEDIA_DIR = os.path.join(BASE_DIR, 'media') MEDIA_ROOT = MEDIA_DIR # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'e$w4_d)z(z)4+5r98#@c4%52ymmd@96fv@x6#zzc7vs-aznqdo' # … -
Django delete error when foreignKey on_delete=CASCADE
I see the following errors occasionally and don't understand why. query DELETE FROM "cart_cart" WHERE "cart_cart"."id" IN (211244) 23:13:27 exception ForeignKeyViolation: update or delete on table "cart_cart" violates foreign key constraint "cart_cartline_cart_id_c7b9981e_fk_cart_cart_id" on table "cart_cartline" DETAIL: Key (id)=(211244) is still referenced from table "cart_cartline". When my cart_cartline table definition has the following line.. class CartLine(ItemLine): cart = models.ForeignKey( "Cart", on_delete=models.CASCADE, related_name='cart_line_set', ) Shouldn't django just delete the cart and the related cart lines? -
Creating page for individual product
I have a "Category", "Subcategory" and "Product" model. I want to be able to click on a category and have it load a page of subcategories then click on a subcategory and have it load page of products and finally load a page for an individual product when clicked on. Rather than having a view for each category, subcategory and product. models.py class Category(models.Model): category_title = models.CharField(max_length=200) category_image = models.ImageField(upload_to="category") category_description = models.TextField() category_slug = models.SlugField(max_length=200, default=1) class Meta: verbose_name_plural = "Categories" def __str__(self): return self.category_title class Subcategory(models.Model): subcategory_title = models.CharField(max_length=200) subcategory_image = models.ImageField() subcategory_category = models.ForeignKey( Category, default=1, verbose_name="Category", on_delete=models.SET_DEFAULT) class Meta: verbose_name_plural = "Subcategories" def __str__(self): return self.subcategory_title class Product(models.Model): product_title = models.CharField(max_length=200) product_image = models.ImageField() product_base_price = models.DecimalField(max_digits=12, decimal_places=2) product_addons = models.CharField(max_length=200, blank=True) product_description = models.TextField() product_date_added = models.DateTimeField(default=datetime.now, blank=True) product_slug = models.SlugField(max_length=200, default=1) product_subcategory = models.ForeignKey( Subcategory, default=1, verbose_name="Subcategories", on_delete=models.SET_DEFAULT) product_available = models.BooleanField(default=True) -
Don't update avatar image in Django
I would like to update a profile image as if it were not saved in the project. What could be wrong? views.py @login_required def edit_profile(request): if request.method == 'POST': form = EditProfileForm(request.POST,request.FILES,instance=request.user) if form.is_valid(): form.save() return redirect('/perfil') else: form = EditProfileForm(instance=request.user.usuario) context = {'form': form} return render(request, 'polls/edit_profile.html', context) forms.py class EditProfileForm(forms.ModelForm): avatar = forms.ImageField(label='Foto de perfil') class Meta: model = User fields = ['username','first_name', 'last_name','matricula','email','avatar','tipoUsuario'] models.py class Usuario(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) avatar = models.ImageField('Foto de perfil',upload_to='static/img/uploads/profile_photo',default="static/img/user.jpg") -
How do I save Korean in the database when I use wagtail?
If I create a form in Korean while using wagtail form, how do I solve the problem of storing data in English? I can solve this problem by changing dependencies, but I want to solve this by changing the code in app model. return str(slugify(str(unidecode(self) in site-packages/wagtail/contrib/forms/models.label)) This part is returned str(self).label) This change is saved, but I don't want to change the code of the Dependency. class FormField(AbstractFormField): page = ParentalKey('FormPage', on_delete=models.CASCADE, related_name='form_fields') class FormPage(AbstractEmailForm, Page): intro = RichTextField(blank=True) thank_you_text = RichTextField(blank=True) content_panels = AbstractEmailForm.content_panels + [ FieldPanel('intro', classname="full"), InlinePanel('form_fields', label="Form fields"), ] def get_context(self, request, *args, **kwargs): context = super(FormPage, self).get_context(request, *args, **kwargs) results = dict() data_fields = [ (field.label, field.label) for field in self.get_form_fields() ] user = int(request.user.id) data_list = [] submissions = self.get_submission_class().objects.filter(page=self, user_id=user) for submission in submissions: data = submission.get_data() data_list.append(data) data_list.reverse() for name, label in data_fields: answer = data.get(label) if answer is None: continue if type(answer) is list: answer = u', '.join(answer) question_stats = results.get(label, {}) question_stats[answer] = question_stats.get(answer, 0) + 1 results[label] = question_stats context.update({ 'results': results, 'data_list': data_list, }) return context def get_data_fields(self): data_fields = [ ('username', 'Username'), ] data_fields += super().get_data_fields() def get_submission_class(self): return CustomFormSubmission def process_form_submission(self, form): self.get_submission_class().objects.create( form_data=json.dumps(form.cleaned_data, ensure_ascii=False), … -
add line number on django-summernote
I want to use summernote on django framework. and I will use summernote by codeview only. than, I want to add line count at the left side of textarea. what shoud I do? $(document).ready(function() { $('#summernote').summernote('codeview.toggle'); $('.note-toolbar').remove(); $('.note-toolbar-wrapper').remove(); $('.note-resizebar').remove(); $('.note-statusbar').remove(); $('textarea').css("height", "100%"); $('#summernote').summernote({ codeviewFilter: true, codeviewIframeFilter: true }); $('#summernote').summernote({ focus: true, // set focus to editable area after initializing summernote callbacks: { onImageUpload: function(files, editor, welEditable) { for (var i = files.length - 1; i >= 0; i--) { sendFile(files[i], this); } } /* onMediaDelete : function($target, editor, $editable) { alert($target.context.dataset.filename); } */ }, lang: 'ko-KR', placeholder: '이제 게시글에 사진을 업로드할 수 있습니다.', codemirror: { // codemirror options theme: 'monokai' } }); }); -
Reverse for 'communication-detail' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['communication/communication/(?P<pk>[0-9]+)/$']
I wanted to create a new app (communication) in my project that shared very similar properties to my original app (surveys). I essentially copy and pasted the same code into the new app and renamed everything. Unfortunately, now the details page of Communication is broken. The correct pk is showing up in the URL of the page and the views is being accessed correctly. However, the Django debug page is claiming that the pk that has passed through is nothing (''). When I print item.id, it all is correctly displayed. I've tried changing the view referenced in the urls.py to be a different view that I know works and it is successful. My theory is that somehow my specific view doesn't work? views.py class CommunicationView(LoginRequiredMixin, View): model = Communication fields = ('name', 'language', 'prompt_type') def get_success_url(self, **kwargs): return self.object.get_prompt_url() return reverse_lazy('communication-prompts', args = (self.object.id,)) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) if self.request.GET.get('project'): context['project'] = Project.objects.get(id=self.request.GET.get('project')) return context def get_initial(self): initial = super().get_initial() # context = self.get_context_data(**kwargs) if self.request.GET.get('project'): initial['project'] = Project.objects.get(id=self.request.GET.get('project')) return initial.copy() class CommunicationDetail(CommunicationView, DetailView): template_name='communication/communication_detail.html' def get_context_data(self, **kwargs): self.object = self.get_object() context = super().get_context_data(**kwargs) context['project'] = self.object.project print(context) return context urls.py app_name = 'communication' urlpatterns = [ path('', … -
How to Pass a Value From Class Based View to a Function Based View Using JS in Django
I have a class based UpdateView which has a form value 'reference' that needs to be passed on to a function based view. This updateview is in a bootstrap modal and is being submitted using JS. I need to know how I can amend the code I have to grab the 'reference' value in this form, and pass it on to the function based view 'manifest' forms.py class UpdateManifestForm(BSModalForm): class Meta: model = Manifests fields = ('reference', 'cases', 'product_name', 'count', 'CNF', 'FOB') views.py class ManifestUpdate(BSModalUpdateView): model = Manifests template_name = 'manifest_update.html' form_class = UpdateManifestForm success_message = 'Success: Manifest was updated.' success_url = reverse_lazy('manifest') #something like Reference_Nos = form.cleaned_data.get('reference') def manifest(request): form = CreateManifestForm(request.POST) if request.method == "POST": if form.is_valid(): form.save() reference_id = form.cleaned_data.get('reference') data = Manifests.objects.all().filter(reference__reference=reference_id) form = CreateManifestForm(initial={ 'reference': Orders.objects.get(reference=reference_id), }) total_cases = Manifests.objects.filter(reference__reference=reference_id).aggregate(Sum('cases')) context = { 'reference_id': reference_id, 'form': form, 'data': data, 'total_cases': total_cases['cases__sum'], } return render(request, 'manifest_readonly.html', context) #return redirect('manifest') #else: reference_id = request.POST.get('Reference_Nos') data = Manifests.objects.all().filter(reference__reference=reference_id) form = CreateManifestForm(initial={ 'reference': Orders.objects.get(reference=reference_id), }) total_cases = Manifests.objects.filter(reference__reference=reference_id).aggregate(Sum('cases')) context = { 'reference_id': reference_id, 'form': form, 'data': data, 'total_cases': total_cases['cases__sum'], } return render(request, 'manifest_readonly.html', context) jquery.bootstrap.modal.forms.js (function ($) { // Place the form at formURL to modalContent element of modal … -
what is the best django app for executinng realtime notification?
I am new to Django & building my own application. I want to add notification system to my projects. Now I want to create real time notifications when some commented someone else's post or replayed or liked. So what is the best notification app or the best way to do that? -
Extending field permission - Django
I have this field, on my models, which is an alteration of the localflavors one: class MYField(models.CharField): def __init__(self, *args, **kwargs): kwargs.setdefault('max_length', 34) self.default_validators = [MyValidator()] super().__init__(*args, **kwargs) def to_python(self, value): value = super().to_python(value) if value in self.empty_values: return self.empty_value return value.upper().replace(' ', '').replace('-', '') def prepare_value(self, value): if value is None: return value grouping = 4 value = value.upper().replace(' ', '').replace('-', '') return ' '.join(value[i:i + grouping] for i in range(0, len(value), grouping)) What I want, is for this field, to show it's value in case current user is_superuser() otherwise, show a string, ie: <mystring> Do You think is a good idea to do this on the field itself, or maybe it is better on a form or something. Also, in any case, could You provide an example of this? Thank You very much -
Django: ImportError "doesn't look like a module path
I just started to learn Django and I tried to add a middleware to my application. Under ProjectFolder/app I have the following files: an empty init.py file settings.py file - the content of this file is default except for: MIDDLEWARE = ( 'SimpleMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ) SimpleMiddleware.py file: class SimpleMiddleware(MiddlewareMixin): def __init__(self, get_response): print("***********************************SIMPLE MIDDLEWARE") self.get_response = get_response # One-time configuration and initialization. def __call__(self, request): # Code to be executed for each request before # the view (and later middleware) are called. print("***********************************SIMPLE MIDDLEWARE") response = self.get_response(request) # Code to be executed for each request/response after # the view is called. return response def process_request(self, request): print("***********************************SIMPLE MIDDLEWARE") return None url.py file: from app import views urlpatterns = [ path('hello', views.index, name='index'), path('core', include('core.urls')), ] However, when I run the application by the command "python manage.py runserver", I get the error: ImportError: SimpleMiddleware doesn't look like a module path Do you know what I'm doing wrong? -
in django smtp sending emails from wrong user
i have configured in settings.py like this EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'now@gmail.com' EMAIL_HOST_PASSWORD = '*******' EMAIL_PORT = 587 EMAIL_USE_TLS = True I am using this setting to send email for user registration and everything working fine. Now I have to make a page of contact-us in which user will send mail to my this id 'now@gmail.com' I am trying to send email to like this if request.method == 'POST': name = request.POST.get('name') sender_email = request.POST.get('email') subject = request.POST.get('subject') message = request.POST.get('message') try: send_mail(subject= subject,message= message,from_email=email ,recipient_list = [settings.DEFAULT_FROM_EMAIL],fail_silently = True,) except BadHeaderError: return HttpResponse('Invalid header found.') render(request, 'MainApp/ContactUs.html') but it still sending using 'now@gmail.com' .. why its the case ? cant i send email on 'now@gmail.com' from user ? -
Cannot locate base.html in root directory. Suspect template loader as problem
I have a base.html file in my root directory. I have a hello_world.html file in my personal_portfolio app's template file that contains {% extends base.html %} in hello_world.html. I have the appropriate entry in the 'DIRS': settings of my personal_portfolio project. I get a template not found error for base.html. In the debug info I see reference to 'django.template.loaders.app_directories.load_template_source'. My impression is that when 'APP_DIRS': is True, this loader is responsible for automatically loading each apps template file in a list of directories to search for templates. I see no reference to ' 'django.template.loaders.filesystem.load_template_source' which I understand is responsible for adding directories in the 'DIRS': setting to the search list. This is how base.html should be located. However, it seems that no matter what I do only the django.template.loaders.app_directories.load_template_source' loader is used. I even tried including a setting for TEMPLATE_LOADERS in settings.py. What I did as a work-a-round is modify the the app_directories.py module to add the directory I am pointing to in the 'DIRS': setting. Here is the app_directories modification in E:\Python Programs\Web Projects II\rp_portfolio\venv\Lib\site-packages\django\template\loaders\app_directories.py. enter code here #************** Revised app_directories.py """ Wrapper for loading templates from "templates" directories in INSTALLED_APPS packages. from django.template.utils import get_app_template_dirs from .filesystem import … -
How to modify url for pagination with aditional get parameters
I'm realising a search list using a simple form using GET. After that, I'm trying to introduce pagination to the list of objects that has been found using that form. The problem is that, inside of the template, I'm using the attribute request.get_full_path and then, adding the attribute 'page' with the following number of the paginator; I use that method because I don't want to loose all the information that the URL contains (csrfmiddlewaretoken, and my others form's parameters). The problem comes when I click more than once on the pages links, because my url has converted in something like: 'URL-WITH-GET-PARAMETERS'&page=X&page=N. The variable called 'worker list is the list of objects returned after the search. {% if workers_list.has_previous %} <a href="{{ request.get_full_path }}&page=1"> First </a> <a href="{{ request.get_full_path }}&page={{ workers_list.previous_page_number }}"> Previous </a> {% endif %} <span class="current"> Page {{ workers_list.number }} of {{ workers_list.paginator.num_pages }}. </span> {% if workers_list.has_next %} <a href="{{ request.get_full_path }}&page={{ workers_list.next_page_number}}"> Next </a> <a href="{{ request.get_full_path }}&page={{ workers_list.paginator.num_pages }}"> Last </a> {% endif %} I expect the output of 'my-url-pah-&formparameters=results&page=N'. -
How to fix: TypeError: QuerySet.annotate() received non-expression(s): eqmunir
I am adding a like functionality in my website where users can like each others posts. I have done this successfully, however have one issue. This is checking whether the user has already liked the post, which has to be performed specifically in my HOME view. This is so I can render my home page. To encounter this issue, I perform a .annotate() on my posts when retrieving them, and see if a user has liked a post. I then pass this onto my home template and check if the user exists within the posts likes property. Here's the related code. models.py: class Post(models.Model): file = models.ImageField(upload_to='images/') summary = models.TextField(max_length=600) pub_date = models.DateTimeField(auto_now=True) user = models.ForeignKey(User, on_delete=models.CASCADE) likes = models.ManyToManyField(User, through='Like', related_name='likes') def __str__(self): return self.user.username def pub_date_pretty(self): return self.pub_date.strftime('%b %e %Y') def summary_pretty(self): return self.summary[:50] @property def total_likes(self): return self.likes.count() class Like(models.Model): status = models.BooleanField() post = models.ForeignKey(Post, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) views.py: def home(request): posts = Post.objects.all() liked_or_not = Post.objects.annotate(likes__user=request.user) return render(request, 'posts/home.html', {'posts': posts, 'liked_or_not': liked_or_not}) home.html: {% if liked_or_not == True %} <a href="javascript:{document.getElementById('likepost{{ post.id }}').submit()}"><button class="btn btn-primary btn-lg btn-block"><span class="oi oi-caret-top"></span> Unlike {{ post.total_likes }} </button></a> {% else %} <a href="javascript:{document.getElementById('likepost{{ post.id }}').submit()}"><button class="btn … -
TemplateDoesNotExist users/login.html
I'm testing my site on linode port 8000 and it works...but I am getting a TemplateDoesNotExist error when I try to access certain links under my Users application from settings.py import os INSTALLED_APPS = [ 'blog.apps.BlogConfig', 'users.apps.UsersConfig',] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ]''' from project urls.py from users import views as user_views urlpatterns = [ path('login/', auth_views.LoginView.as_view(template_name='users/login.html'), name='login'), ] Project Directory: django_project -> django_project -> urls.py - __init__.py - settings.py -> users -> templates - login.html - urls.py - views.py ```TemplateDoesNotExist at /login/ users/login.html Request Method: GET Request URL: http://45.33.127.12:8000/login/ Django Version: 2.2.4 Exception Type: TemplateDoesNotExist Exception Value: users/login.html Exception Location: /home/nnmott/django_project/venv/lib/python3.7/site-packages/django/template/loader.py in select_template, line 47 Python Executable: /home/nnmott/django_project/venv/bin/python Python Version: 3.7.3 Python Path: ['/home/nnmott/django_project', '/usr/lib/python37.zip', '/usr/lib/python3.7', '/usr/lib/python3.7/lib-dynload', '/home/nnmott/django_project/venv/lib/python3.7/site-packages'] Server time: Thu, 22 Aug 2019 21:07:49 +0000``` Any help is appreciated! -
arranging bootstrap cards with for loop
I'm trying to make 2 cards per one line. I want them to align them with some space between them. I tried but it looks like only the first row have the way I want. Can someone please help me... {% for post in post %} {% if forloop.first %}<div class="row">{% endif %} <div class="col-sm-6"> <div class="card" > <img class="card-img-top" src="https://images.unsplash.com/photo-1556740758-90de374c12ad?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1050&q=80" alt="Card image cap"> <div class="card-body"> <h5 class="card-title">{{post.title}}</h5> <p class="card-text">With supporting text below as a natural lead-in to additional content.</p> </div> </div> <br> </div> {% if forloop.counter|divisibleby:3 %}</div><div class="row">{% endif %} {% if forloop.last %}</div>{% endif %} {% endfor %}