Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to import a csv file from the admin side in django without the foreignkey column
For the moment I can import csv file using Django's import_export package. However I need to provide a csv with the id corresponding to my foreign key. Here is my modele.py : class Category(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name class Cause(models.Model): name = models.CharField(max_length=50) category = models.ForeignKey(Category, on_delete=models.DO_NOTHING, null=True) def __str__(self): return self.name And here is admin.py : from import_export.admin import ImportExportModelAdmin # Register your models here. class CategoryAdmin(admin.ModelAdmin): list_display = ("name", ) class CauseAdmin(ImportExportModelAdmin): list_display = ("name",) pass admin.site.register(Category, CategoryAdmin) admin.site.register(Cause, CauseAdmin) If I want to import a csv containing the names of the causes I need to add a column with the id of the corresponding categories. However, I would like to be able to import a csv containing only the names of the causes and choose the category on the admin side. For the moment this is what it looks like when I import a csv file: I would like to know if it is possible using the import_export package that it looks more like this: (like when I add only one cause) Instead of the "Name" there would be as in the first screenshot " File to import " and the category could be … -
Web application with a lot of excel data
this is my first time posting here so excuse (or even correct if you would like) any mistakes I make in presenting my question and details. As my first development job ever I have been tasked to create a web application and I would greatly appreciate your opinion and insight on the way I have decided to approach this. There's no specific issue, I just want to make sure I start my career in the best way possible, being aware of course that mistakes are unavoidable in my first steps. I will present the requirements for the app, my current knowledge and the way I have thought to approach development Requirements: Web application with login functionality A considerable amount of data which has to be accessible in the form of dependent select options The data is in excel form and the tables have the following structure: table screenshot . It's basically 2 values, height and width, and to each combination of those two, corresponds a unique price. Some parts of the data could possibly have an extra variable, so it would be: height + width + colour corresponds to a unique price. Additionally not all combinations of these variables necessarily … -
ValueError at /brands/some-brand/ Cannot query Must be "Category" instance
So one of my filters in my category nav link is a list of brands. When you click the brand, it is supposed to take you to a similar page as brand but only with those specific products. Here is my models.py class Brand(models.Model): #category = models.ForeignKey(Category, on_delete=models.CASCADE) title = models.CharField(max_length=100) slug = models.SlugField() description = models.TextField() image = models.ImageField() is_active = models.BooleanField(default=True) def __str__(self): return self.title def get_absolute_url(self): return reverse("core:brand", kwargs={ 'slug': self.slug }) class Category(models.Model): #brands = models.ForeignKey(Brand, on_delete=models.CASCADE) title = models.CharField(max_length=100) slug = models.SlugField() description = models.TextField() image = models.ImageField() is_active = models.BooleanField(default=True) def __str__(self): return self.title def get_absolute_url(self): return reverse("core:category", kwargs={ 'slug': self.slug }) class Item(models.Model): title = models.CharField(max_length=100) price = models.FloatField() discount_price = models.FloatField(blank=True, null=True) category = models.ForeignKey(Category, on_delete=models.PROTECT, null=True, related_name='category') #brands = models.ForeignKey(Brand, on_delete=models.PROTECT, null=True, related_name='brands') label = models.CharField(choices=LABEL_CHOICES, max_length=1) slug = models.SlugField() stock_no = models.CharField(max_length=10) description_short = models.CharField(max_length=50) description_long = models.TextField() image = models.ImageField() is_active = models.BooleanField(default=True) def __str__(self): return self.title def get_absolute_url(self): return reverse("core:product", kwargs={ 'slug': self.slug }) def get_add_to_cart_url(self): return reverse("core:add-to-cart", kwargs={ 'slug': self.slug }) def get_remove_from_cart_url(self): return reverse("core:remove-from-cart", kwargs={ 'slug': self.slug }) This is the error I keep getting. Even when I uncomment the changes in my modules.py, I still … -
How do I attach a file to my django email project? Sending a HTML Template out with images as attachments
class createLot(LoginRequiredMixin,generic.CreateView): form_class = LOTForm model = LOT def form_valid(self,form): user = form.cleaned_data['user'] lot_nr = str(form.cleaned_data['lot_nr']) agent_nr = form.cleaned_data['agent_nr'] verkoper = form.cleaned_data['verkoper'] verkoper_sel = form.cleaned_data['verkoper_sel'] laai_datum = form.cleaned_data['laai_datum'] laai_gewig = form.cleaned_data['laai_gewig'] laai_qty = form.cleaned_data['laai_qty'] prys_kg = form.cleaned_data['prys_kg'] prys_kop = form.cleaned_data['prys_kop'] laai_strokie = form.cleaned_data['laai_strokie'] image = form.cleaned_data['image'] lot_info = { "lot_nr": lot_nr, "agent_nr": agent_nr, "verkoper": verkoper, "verkoper_sel": verkoper_sel, "laai_datum": laai_datum, "laai_gewig" : laai_gewig, "laai_qty" : laai_qty, "prys_kop": prys_kop, "prys_kg":prys_kg, "weegbrug": weegbrug, 'user': User, } subject = "Email" html_message = render_to_string('mailto/email2.html',lot_info ) plain_message = strip_tags(html_message) from_email = 'From <123@123.co.za>' to = ['to_email@123','to_email2123@123'] send_mail(subject, plain_message, from_email, to, html_message=html_message) self.object = form.save(commit = False) self.object.user = self.request.user self.object.save() return super().form_valid(form) I Know my forms and models are set up correctly I just cant seem to find a way to attach a file using this method of send_mail. Either it goes back to HTML format or it doesnt attach anything at all. -
How to save correct path to django image
I want render image in home page, but i can't specify to the correct path to it, when i upload image, it is saved as static/images/product_pic/filename but I need to save image with a custom path that I specify in the save function static/images/product_pic/customfilename. How can i specify a custom path in the database? my model: class Product(models.Model): name = models.CharField(max_length=40) price = models.FloatField() description = models.TextField(null=True) image = models.ImageField(null=True, default='placeholder.png', upload_to='static/images/product_pic') def __str__(self): return self.name def save(self): super().save() initial_path = self.image.path img = Image.open(initial_path) self.image.name = f'{self.name} - {self.id}.jpg' new_path = 'static/images/product_pic/' + self.image.name if img.height > 360 or img.width > 640: output_size = (360, 640) img.thumbnail(output_size) os.rename(initial_path, new_path) img.save(new_path) path in database: correct path to image: -
Django Form add class to div, input field and label
This is the html django form generated for an ImageField <div id="div_id_image" class="form-group"> <label for="id_image" class=""> Image </label> <div class=""> <input type="file" name="image" accept="image/*" class="clearablefileinput form-control-file" id="id_image"> </div> Now, I can write custom html code to customize this field. But, my use-case is just to add 3 classes, one for the outer div, one for the label and one for the input field itself. Is it possible to add these 3 classes in django form without writing any custom html code -
Scrapy Help: How can I get medical Centre data which medical are selected before make a payment.? this web automatically assign medical center [closed]
https://v2.gcchmc.org/book-appointment/ This is the website when I select country Bangladesh & city any one of this (Dhaka, Chittagong or sylhel) 3 cities are included this website, I currently trying to see which medical centre is selected.. when I fill up all information and submit then redirect the payment option after payment completed, automatically generates a pdf where is showing whose medical centre is appointed. Before making a payment how can I see which medical centre is selected..? Booking Appointment form Generated PDF Sample -
How to override formatmonth function of python HTMLcalendar?
I would like to override the HTMLcalendar of python. I am currently trying to do it like this: class CustomCalendar(HTMLCalendar): def formatmonth(self, theyear, themonth, w=0, l=0): """ Return a month's calendar string (multi-line). """ w = max(2, w) l = max(1, l) s = self.formatmonthname(theyear, themonth, 7 * (w + 1) - 1) s = s.rstrip() s += '\n' * l s += self.formatweekheader(w).rstrip() s += '\n' * l for week in self.monthdays2calendar(theyear, themonth): s += self.formatweek(week, w).rstrip() s += '\n' * l return s I would like to add the month, day, and year to each day so that I am able to add an event listener to redirect to different Django URLs/views. How can I do that? Furthermore, I would like to highlight the selected day in the calendar with background color as well as today's day with a background color. How do I do that? Thanks a lot for your help. -
Django Custom Auth create Object with foreign key from another table AbstractBaseUser
I think the title is a little bit confusing, but nevermind. So I have created my models in MySQL Workbench, thats why I have (way -> not yet) a lot of different tables. I have a table called Account with a AbstractBaseUser and two other AbstractBaseUsers tables. The Account table has a onetoone field to the Residence. Now, if I create a User I want, that the user also can input the data for the Residence field and not only the foreign key. Here is my code: user/models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager from phonenumber_field.modelfields import PhoneNumberField from django.conf import settings from django.db.models.signals import post_save from django.dispatch import receiver from rest_framework.authtoken.models import Token class MyAccountManager(BaseUserManager): def create_user(self, username, firstname, lastname, email, verified, jobs, password=None): if not username: raise ValueError("Users must have a userid") if not lastname: raise ValueError("Users must have a lastname") if not email: raise ValueError("Users must have a email") user = self.model( username = username, firstname = firstname, lastname = lastname, email = email, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, username, firstname, lastname, email, password): user = self.model( username = username, firstname = firstname, lastname = lastname, email = email, password = password, … -
I'm getting this error when i try to send email with django ,can any body help me?
I'm trying to send an email from django using gmail smtp I've set insecure source ON in my account's setting also this is my settings.py file can anybody help me ? EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com ' EMAIL_USE_TLS = True EMAIL_PORT = 587 EMAIL_HOST_USER =' my email' EMAIL_HOST_PASSWORD = 'my password' and I'm getting this error in terminal for res in _socket.getaddrinfo(host, port, family, type, proto, flags): socket.gaierror: [Errno 11001] getaddrinfo failed -
redirect to another page with information about the new user after creating this user in Django
I'm creating an appointment application using Django for register and non register user for the non register user the doctor needs to create a temporary user and add his information after that he can book an appointment for this user the best i can get to is this @login_required def create_appointment_non_register_P(request): form_user = UserEditForm() if request.method=='POST' : form_user = UserEditForm() if form_user.is_valid(): new_T_user = form_user.save(commit=False) form_user.save() messages.success(request, 'appointment added') else: messages.error(request, 'Error') return render(request, 'appointement/add_appointement2.html', {'user_form':form_user, }) @login_required def create_appointment_D(request): if request.method=='POST' : user = User() if request.user.is_doctor() or request.user.is_reception(): appointment = request.POST['type'] if appointment=='register patient': form_appointment = AppointmentForm_2() if form_appointment.is_valid(): form_appointment.save(commit=False) form_appointment.user = request.user form_appointment.end_time = form_appointment.start_time + timedelta(minutes=30) form_appointment.save() messages.success(request, 'appointment added') else: messages.error(request, 'Error') return render(request, 'appointement/add_appointement1.html', {'user_form':form_appointment, }) else: return HttpResponseRedirect(reverse("create_appointment_non_register_P")) return render(request, 'appointement/add_appointement1.html', {'user_form':form_user, }) else: return HttpResponseRedirect(reverse("create_appointment_P")) return render(request,'appointement/add_appointement_options.html') but the it did not create a new user and how after creating this user and redirect to a new page with the appointment form can book an appointment for him -
Create a model object after creation of related model object using model manager
I have three models as follows, models.py: class Activity(models.Model): # ... objects = models.Manager() activity = ActivityManager() kind = models.CharField(max_length=10, choices=KIND_CHOICES) # ... class ActivtyA(models.Model): # ... activity = models.OneToOneField( Activity, on_delete=models.CASCADE, related_name='A', ) # ... class ActivtyB(models.Model): # ... activity = models.OneToOneField( Activity, on_delete=models.CASCADE, related_name='B', ) # ... and a model manager, managers.py: class ActivityManager(models.Manager): def create_activity(self, validated_data): # ... data = validated_data.pop(kind) act = self.create(**validated_data) if act.kind == 'A': # Create ActivityA(act, **data) elif act.kind == 'B': # Create ActivityB(act, **data) # ... # ... In model manager's create_activity method I wand to create Activty and either ActivityA or ActivtyB based on Activity.kind. How can I achieve this? I tried to do this by using signals but could make it. @receiver(post_save, sender=Activity) def create_activity_details(sender, instance, using, **kwargs): if instance.kind == 'FOOD': ActivityDetailsFood.objects.create(activity=instance, data=????) # Need data to create this object -
FilterView, get_context_data() does not work. No attribute 'object_list' but there is one
I am using django_tables2 with django_filter. When trying to edit context in def post(), so first getting actuall context (context=get_context_data(self)) it shows error: 'FilteredZamTableView' object has no attribute 'object_list' But it does have object_list attribute! This is ridiculous. I printed it inside get_context_data() declaration def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) print(context) return context It shows: {'paginator': <django.core.paginator.Paginator object at 0x0000024EBAABE7F0>, 'page_obj': <Page 1 of 2>, 'is_paginated': True, 'object_list': <QuerySet [---CONTENT---]>... Here's my class based view with post method. class FilteredZamTableView(LoginRequiredMixin, SingleTableMixin, FilterView): table_class = ZamTable template_name = 'home.html' paginate_by = 10 filterset_class = ZamFilter def post(self, request, *args, **kwargs): if request.POST.get('accept'): try: context = get_context_data(self) <--------------------------- ERROR return redirect('home') except Exception as e_msg: print(e_msg) return redirect('home') It honestly looks like an error in django_filters. -
how create multiple choice plus with custom choice in django
i'am trying to creating model which one will be for product. it must create information for example. [Male(static)][Female(static)] [Enter how you want to describe(editable)] but when i want to add choice to charfield my choicefield is dublicated. from django.db import models class Pricetab(models.Model): choice = models.CharField(max_length=200,default='test') content = models.TextField() button = models.CharField(max_length=100,default='test') MONTH_YEAR_CHOICE = ( (True, 'male'), (False, 'female') ) gender = models.Charfield(maxl_length=100, choices=MONTH_YEAR_CHOICE,default=True) def __str__(self): return self.title -
OperationalError at / no such column:core_item.brands_id
I am having a tricky database problem. I have a set of categories that display on the nav bar, once you click on those categories, there is a filter called brand, and this brand filter is supposed to take you to a page where they have products under that category (e.g. makup) and display those items. So I tried to have two foreign keys in my items module as below. Models.py class Category(models.Model): title = models.CharField(max_length=100) slug = models.SlugField() description = models.TextField() image = models.ImageField() is_active = models.BooleanField(default=True) def __str__(self): return self.title def get_absolute_url(self): return reverse("core:category", kwargs={ 'slug': self.slug }) class Brand(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) title = models.CharField(max_length=100) slug = models.SlugField() description = models.TextField() image = models.ImageField() is_active = models.BooleanField(default=True) def __str__(self): return self.title def get_absolute_url(self): return reverse("core:brand", kwargs={ 'slug': self.slug }) class Item(models.Model): title = models.CharField(max_length=100) price = models.FloatField() discount_price = models.FloatField(blank=True, null=True) category = models.ForeignKey(Category, on_delete=models.PROTECT, null=True, related_name='category') brands = models.ForeignKey(Brand, on_delete=models.PROTECT, null=True, related_name='brands') label = models.CharField(choices=LABEL_CHOICES, max_length=1) slug = models.SlugField() stock_no = models.CharField(max_length=10) description_short = models.CharField(max_length=50) description_long = models.TextField() image = models.ImageField() is_active = models.BooleanField(default=True) def __str__(self): return self.title def get_absolute_url(self): return reverse("core:product", kwargs={ 'slug': self.slug }) def get_add_to_cart_url(self): return reverse("core:add-to-cart", kwargs={ 'slug': self.slug }) def … -
OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: '<frozen importlib._bootstrap>' for a django project
this is my first submession here, so whenever i try to run python manage.py runserver for a django project it didn't and it give an error i never saw before Any ideas about what is this and how to fix it? it give me the following error: The Error i get Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "D:\GitHub\herafi\manage.py", line 22, in <module> main() File "D:\GitHub\herafi\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\vreoo\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\vreoo\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\vreoo\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\vreoo\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\commands\runserver.py", line 61, in execute super().execute(*args, **options) File "C:\Users\vreoo\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 371, in execute output = self.handle(*args, **options) File "C:\Users\vreoo\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\commands\runserver.py", line 96, in handle self.run(**options) File "C:\Users\vreoo\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\commands\runserver.py", line 103, in run autoreload.run_with_reloader(self.inner_run, **options) File "C:\Users\vreoo\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\autoreload.py", line 618, in run_with_reloader start_django(reloader, main_func, *args, **kwargs) File "C:\Users\vreoo\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\autoreload.py", line 603, in start_django reloader.run(django_main_thread) File "C:\Users\vreoo\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\autoreload.py", line 318, in run self.run_loop() File "C:\Users\vreoo\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\autoreload.py", line 324, in run_loop next(ticker) File "C:\Users\vreoo\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\autoreload.py", line 364, in tick for filepath, mtime in self.snapshot_files(): File "C:\Users\vreoo\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\autoreload.py", line 380, in snapshot_files for file in self.watched_files(): File "C:\Users\vreoo\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\autoreload.py", line 278, in watched_files yield from iter_all_python_module_files() File "C:\Users\vreoo\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\autoreload.py", line 105, … -
How to get the result of a textfield in django?
i am making a python editor, and i have a model called NewJax. In this model, i have a field called space. The space field executes the python code i typed in there. for example, if i did print('hello') in the space field, it should take me to a detail page, and return the result. Which is hello. but when it takes me to the details page for now, it results in None. Could you someone please let me know, how this should execute? models.py class NewJax(models.Model): title = models.CharField(max_length=60) description = models.TextField(max_length=140) space = models.TextField() user = models.ForeignKey(User, on_delete=models.CASCADE) date_created = models.DateTimeField(default=timezone.now) class Meta: ordering = ['-date_created'] verbose_name_plural = "New Jax" def __str__(self): return str(self.title) forms.py class CreateNewJaxForm(forms.ModelForm): class Meta: model = NewJax fields = ('title', 'description', 'space') widgets = { "title": forms.TextInput( attrs={ 'class': 'form-control', 'placeholder': 'name your jax' } ), 'description': forms.Textarea( attrs={ 'class': 'form-control', 'placeholder': 'add a brief description for jax', 'rows': 4, } ), 'space': forms.Textarea( attrs={ 'class': 'form-control', } ) } views.py def create_new_jax(request): if request.user.username == "Assasinator": logout(request) return redirect('banned_user') if request.method == "POST": form = CreateNewJaxForm(request.POST or None) if form.is_valid(): title = form.cleaned_data.get('title') description = form.cleaned_data.get('description') space = form.cleaned_data.get('space') obj = form.save(commit=False) … -
Django+Rest and later React without Docker?
I would like to ask an advice... I did the project with Django+Rest... But never thought about adding to them React... But I would like to do React... I did it, but it runs as a local version... So I have Django which runs as https and React which runs as http://localserver:3000... Which is not really good... I went through about 6 or 7 tutorials... But they all using Docker... To use Docker I have to restructure the project completely... When I structured project first time I didn't think about React. Now generally the structure is like this: -files and folders for Djago -frontend files and folders for React -in the root of the server: /etc... files and folders for gunicorn and nginx So the question is: Is it possible to serve React, only by tuning gunicorn and nginx, without changing the site itself... So url will be something like this: https://address/home/django_url https://address/home/React_url Similar to Rest api, which I run like so:https://address/home/api/Rest_url Or so React will be as frontend based on the Django as backend... I'm kind of confused about if I can do it and how... -
Django m2m workaround relationship reverse relation
So I have three models like this. class Member(models.Model): class Meta: constraints = [ models.UniqueConstraint( fields=('user', 'locker'), name='unique_locker_member_check' ), ] locker = models.ForeignKey( to='uploads.Locker', verbose_name=_('locker'), on_delete=models.CASCADE, editable=False ) user = models.ForeignKey( to=settings.AUTH_USER_MODEL, verbose_name=_('user'), on_delete=models.CASCADE, editable=False ) class Role(CoreModel): class Meta: ordering = ('position', 'locker') permission_flags = ( 'ADD_STARS', 'DOWNLOAD_FILES', 'SEND_UPLOADS', 'MANAGE_UPLOADS', 'MANAGE_ROLES', 'MANAGE_LOCKER', 'MANAGE_INVITES', 'KICK_MEMBERS', 'BAN_MEMBERS' ) default_flags = ( 'ADD_STARS', 'DOWNLOAD_FILES', 'SEND_UPLOADS', ) def __str__(self): return self.name is_default = models.BooleanField( verbose_name=_('default'), help_text=_("whether the role is default"), default=False ) locker = models.ForeignKey( to='uploads.Locker', verbose_name=_('locker'), on_delete=models.CASCADE ) permissions = BitField( verbose_name=_('permissions'), help_text=_("permission bit set"), flags=permission_flags, default=default_flags ) REQUIRED_FIELDS = (name, locker) class MemberRole(CoreModel): class Meta: verbose_name = _('member role') default_related_name = 'member_role_set' constraints = [ models.UniqueConstraint( fields=('user', 'role', 'locker'), name='unique_member_role_check' ), ] def __str__(self): return self.role.name role = models.ForeignKey( to='roles.Role', verbose_name=_('role'), on_delete=models.CASCADE ) user = models.ForeignKey( to='users.User', verbose_name=_('user'), on_delete=models.CASCADE ) locker = models.ForeignKey( to='uploads.Locker', verbose_name=_('locker'), on_delete=models.CASCADE ) Members can have multiple Roles of their own, with the through model being MemberRole. So normally, there would be a m2m field on Member through MemberRole. However, I want the role data to persist even after a member is created. Since locker and user are unique identifiers for the member, My model structure is … -
open_note() missing 1 required positional argument: 'docid'
I appreciate that this question has been asked multiple times before, and I have looked at basically all of the answers and the official documentation for django, but I still can not figure out why I am getting the Exception Value of: open_note() missing 1 required positional argument: 'docid'. I am trying to get the page to display the selected document from the database, when it loads it should show the title and the content, along with an edit and delete button (neither of which function yet, but they're not important right now). The request url is http://localhost:8000/notes/open-notes/?docid=1, and it leads to the error mentioned above. If I change my urls.py path to path('open-notes/<int:id>/', views.open_note, name='open-notes'), then the error I get instead is Reverse for 'open-notes' with no arguments not found. 1 pattern(s) tried: ['notes/open\\-notes/(?P<id>[0-9]+)/$'] which I assume is because the id isn't actually an int and needs converting in the views.py, or I need to use a different converter in the urls.py. Or equally entirely possible, I've misunderstood the other answers in which case I apologise for asking the same question that already has an answer I should be able to implement. I am relatively new to django and … -
How to use for loop counter with a nested if loop?
I created a for loop with a nested if statement for counting specific types of customers in my Django project. What I need is the final number of the for loop counter. I try: {% if forloop.last %} {{ forloop.counter }} {% endif %} But it displays nothing. But when try just {{ forloop.counter }} it displays 2 number. One of them is what I want but the other one is all for loops I think. How can I solve this problem? list.html {% for customer in customer_list %} {% if customer.country.country_name == country %} {% if customer.risk_rating == "Low Risk" %} {% if forloop.last %} {{ forloop.counter }} {% endif %} {% endif %} {% endif %} {% endfor %} views.py def test_customer_list(request): current_user = request.user userP = UserProfile.objects.get_or_create(username=current_user) customer_list = Customer.objects.filter(company=userP[0].company) countries = Customer.objects.values_list('country__country_name', flat=True).distinct() country_links = Country.objects.filter() context = { 'customer_list': customer_list, 'countries': countries, 'country_links': country_links } return render(request, 'test.html', context) -
NoReverseMatch error on password reset. The error only occurs on remote server and NOT on the local server
I am getting the following error when trying to reset a password. The error occurs only on the remote server (i.e. heroku). I can change the password just fine in my local server. Reverse for 'password_reset_confirm' with keyword arguments '{'uidb64': 'MTI', 'token': 'ak0pf1-d978cc8242a65cef3803f25c240c6996'}' not found. 1 pattern(s) tried: ['user_accounts/reset/(?P[0-9A-Za-z_\-]+)/(?P[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$'] from urls.py url(r'^reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', PasswordResetConfirmView.as_view(template_name='password_reset_confirm.html'), name='password_reset_confirm'), What exactly could be causing this? If the problem is in the code then how come I can reset the password in my local environment. I am bit confused here, any help will be appreciated. -
How can I resolve this type error in my project blogpost object not iterable?
This is my views.py. I suspect that i need to create a another model to handle entries. But which i think will not neccesary. from django.shortcuts import render, redirect from . models import BlogPost def index(request): return render(request, 'blogs/index.html') def posts(request): '''displays all blogs''' all_posts = BlogPost.objects.order_by('-date_added') context = { 'posts': all_posts } return render(request, 'blogs/all_posts.html', context) def post (request, posts_id): single_post = BlogPost.objects.get(id = posts_id) context = { 'single_post':single_post } return render(request, 'blogs/post.html', context) This is my html file {% extends "blogs/base.html" %} {% block body %} <h1>Posts</h1> {% for posts in single_post %} <h3>{{posts.title}}</h3> <p>{{posts.text}}</p> <p>{{posts.date_added}}</p> {% endfor %} {% endblock body %} and this is my urls.py from django.urls import path from . import views app_name = 'blogs' urlpatterns = [ path('all_posts/<int:posts_id>/', views.post, name = 'post'), path('all_posts/', views.posts, name = 'all_posts'), path('', views.index, name = 'index'), Here is my model definition for the project. The various fields have be defined correctly from django.db import models class BlogPost(models.Model): title = models.CharField(max_length = 150) text = models.TextField() date_added = models.DateField(auto_now=False, auto_now_add=True) def __str__(self): return f'{self.title}' class Meta: db_table = 'Blog_Post' managed = True verbose_name = 'BlogPost' verbose_name_plural = 'BlogPosts' -
Order by for a method in django
I would like to show the top 10 of clients with balance from bigger to smaller. but the prob is that balance is method. class ClientsBalance(models.Model): client = models.OneToOneField('Client', on_delete=models.CASCADE,related_name='Client') def inputs(self): total = self.client.invoice_set.aggregate(sum=Sum('total_general')) return round(total[("sum")] or 0, 2) def outputs(self): total = self.client.clientpayment_set.aggregate(sum=Sum('total_paid')) return round(total[("sum")] or 0, 2) def balance(self): return self.outputs() - self.inputs() def Dashboard(request): clientsbalances = clientsbalance_set.all()[:10] context = {'clientsbalances': clientsbalances} return render(request, 'dashboard.html', context) -
Django class based views- handle redirect to the same view, add new context
After POST request I want to redirect user to the same view, adding something to the context. I have no idea how to do it. I tried using get_context_data(**kwargs) but I think I don't really understand the concept. If I do not add anything into context I simply redirect to the same view, which sounds dumb but works. Here's my code: (the class is "home.html" view) class FilteredZamTableView(LoginRequiredMixin, SingleTableMixin, FilterView): table_class = ZamTable template_name = 'home.html' paginate_by = 10 filterset_class = ZamFilter def post(self, request, *args, **kwargs): if request.POST.get('accept_zam'): try: ... return redirect('home') except Exception as e_msg: context = self.get_context_data(**kwargs) context['error'] = e_msg return render(response, "home.html", context) I get this error msg at self.get_context_data(**kwargs) django.urls.exceptions.NoReverseMatch: Reverse for 'home' with keyword arguments '{'e_msg': AttributeError("'FilteredZamTableView' object has no attribute 'object_list'")}' not found. 1 pattern(s) tried: ['$']