Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to count the content in databse django?
I am learning Django and my first project I am doing a To do application. My idea is that I put the content from the database(models.py) into tables in html ,but also on the side of the table I have put a number that starts from 1 and for every other task(content) that is put from customer in the web it also puts 2, 3 .... etc. The problem I have is that when I add a task number it becomes 2 for what I just added but also for the task that was before. This is a screenshot to understand it easily This is views.py: from django.shortcuts import render, redirect from django.utils import timezone from django.db.models import Count from .models import * from .models import __str__ # Create your views here. def home(request): count_item = todo.objects.count() all_items = todo.objects.all().order_by("created") context = {'all_items': all_items, 'count_item':count_item} return render(request, 'html/home.html', context) def add_todo(request): current_date = timezone.now() new_item= todo(content = request.POST["content"]) new_item.save() return redirect('/') def delete_todo(request, todo_id): item_to_delete = todo.objects.get(id=todo_id) item_to_delete.delete() return redirect('/') This is home.html: {% extends 'html/main.html' %} {% load static %} {% block content %} <style> </style> <nav class="navbar navbar-dark bg-dark"> <div class="container-fluid"> <a class="navbar-brand" href="#">TO DO APPLICATION</a> <form class="d-flex" … -
Django Admin does not encrypt password
I'm making a project that there will be an admin, and He/She will register the users. But when I create a user by admin interface, the password is not being encrypted. What could it be? user model from django.db import models from django.contrib.auth.models import AbstractUser from django.contrib.auth.models import BaseUserManager # Create your models here. class UsuarioManager(BaseUserManager): use_in_migrations = True def _create_user(self, email, password, **extra_fields): if not email: raise ValueError('Email é obrigatorio') email = self.normalize_email(email) user = self.model(email=email, username=email, **extra_fields) user.set_password(password) user.save(using=self._db) return def create_user(self, email, password=None, **extra_fields): extra_fields.setdefault('is_superuser', False) return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password, **extra_fields): extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_staff', True) if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser precisa ter is_superuser=True') if extra_fields.get('is_staff') is not True: raise ValueError('Superuser precisa ter is_staff=True') return self._create_user(email, password, **extra_fields) class Usuario(AbstractUser): USERNAME_FIELD = 'email' email = models.EmailField(('email address'), unique=True) REQUIRED_FIELDS = [] # removes email from REQUIRED_FIELDS funcionario = models.BooleanField("funcionario", null=True, blank=True) cliente = models.BooleanField("cliente", null=True, blank=True) def __str__(self): return super().first_name + " " + super().last_name objects = UsuarioManager() As I create a superuser on cmd, the password is encrypted normally. -
Django pagination not working. Object list is rendering items but not dividing into pages
I'm currently working on an e-commerce site and I'm trying to create a product list page that spans into another page after 4 items have been displayed. rendering the page doesn't produce any error but all items in the database are displayed on the same page and remains the same even after switching to another page. Here's my views.py: from django.shortcuts import render, get_object_or_404 from .models import Category, Item from django.core.paginator import Paginator def item_list(request, category_slug=None): category = None categories = Category.objects.all() items = Item.objects.filter(available=True) if category_slug: category = get_object_or_404(Category, slug=category_slug) items = items.filter(category=category) paginator = Paginator(items, 4) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) return render(request, 'item/list.html', {'category': category, 'categories': categories, 'page_obj': page_obj, 'items': items}) my urls.py file: from django.urls import path from . import views app_name = 'shop' urlpatterns = [ path('', views.item_list, name='item_list'), path('<slug:category_slug>/', views.item_list, name='item_list'), path('<int:id>/<slug:slug>/', views.item_detail, name='item_detail'), pagination snippet from the template <nav class="d-flex justify-content-center wow fadeIn"> <ul class="pagination pg-blue"> <!--Arrow left--> {% if page_obj.has_previous %} <a href="?page={{ page_obj.previous_page_number }}">Previous</a> {% endif %} <span class="current"> Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}. </span> {% if page_obj.has_next %} <a href="?page={{ page_obj.next_page_number }}">Next</a> {% endif %} </ul> </nav> and the logic that displays the products <div class="row … -
Django models: How to filter by multiple values at once?
I'm working on a social network project for learning purposes and I'm trying to figure out the best way to make this query: def following(request, user_username): user = User.objects.get(username=user_username) try: following_users = user.following.all() following_posts = [] for following_user in following_users: following_posts.append(Post.objects.filter(username=following_user.username)) except: return JsonResponse({"error": "There was an error loading the following posts"}, status=400) following_posts = following_posts.order_by("-timestamp").all() return JsonResponse([post.serialize() for post in following_posts], safe=False) I'm trying to get the posts of the users that the user is following in the social media, ordered by reverse chronological order ("timestamp"). And, to do that, I tried first getting all the users that the user follows (following_users = user.following.all()) and then getting all the posts these users has one by one (in the for loop). The problem is that the order_by function only works with QuerySet, and the following_posts is a list. Not only that, I don't think that this is a good way to make this query even if it worked. Can I get all these posts at once without a for loop? Anyway, these are the models that are involved in this query: class User(AbstractUser): profile_picture = models.CharField(max_length=100, default="https://cdn.onlinewebfonts.com/svg/img_568656.png") followers = models.ManyToManyField('self', blank=True) following = models.ManyToManyField('self', blank=True) join_date = models.DateTimeField(auto_now_add=True) def serialize(self): … -
Implementing Language switcher
I'm trying to implement language switcher a web-application using django. I have written the html part and it's showing the current language that I'm using but for some reason the dropdown menu which contains the flag list is not showing this is what I've written so far: $("#language-list a").on('click', function (event) { event.preventDefault(); var target = $(event.target); var url = target.attr('href'); var language_code = target.data('language-code'); $.ajax({ type: 'POST', url: url, data: {language: language_code}, headers: {"X-CSRFToken": getCookie('csrftoken')} }).done(function (data, textStatus, jqXHR) { reload_page(); }); }); <form class="d-flex"> <ul class="navbar-nav mx-0 me-auto mb-2 mb-lg-0"> <li class="nav-item dropdown"> {% get_current_language as LANGUAGE_CODE %} {% get_available_languages as LANGUAGES %} {% get_language_info_list for LANGUAGES as languages %} <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown"><img src="/static/img/flags/{{LANGUAGE_CODE}}.png">&nbsp;<span class="caret"></span></a> <ul class="dropdown-menu" role="menu" id="language-list"> {% for language in languages %} <li> <a href="" data-language-code="{{ language.code }}"> {% if language.code == LANGUAGE_CODE %}&#10003;{% else %}&nbsp;&nbsp;{% endif %} <img src="/static/img/flags/{{ language.code }}.png"> {{ language.name_local }} </a> </li> {% endfor %} </ul> </li> </ul> </form> -
How to insert data with create in Django
How to insert data with create in Django thank you Model class Cliente(models.Model): seguimento = models.PositiveIntegerField() Form class ClienteForm(forms.Form): seguimento = forms.IntegerField() def create(self, validated_data): client = Cliente.objects.create(**validated_data) view form = ClienteForm(request.POST) if form.is_valid(): form.create(validated_data=request.POST) Errors: TypeError: int() argument must be a string, a bytes-like object or a number, not 'list' TypeError at /admin/cliente Field 'seguimento' expected a number but got [3]. -
React.js: posts.map is not a function
I'm getting this error when running my app and i don't know why! i have this react component that's getting data from a djagno api that's consists of a title, body for the post, slug, image, date (day and month) and a category. i have defined posts as an array but it's still giving me an error that's posts.map is not a function. i hope someone can help me with this on cuz i have spent 3 days trying to figure out what's wrong with this code import React, { useState, useEffect } from 'react'; import axios from 'axios'; import { Link } from 'react-router-dom' const Post = () => { const [posts, setPost] = useState([]); useEffect(() => { const fetchPost = async () => { try { const res = await axios.get(`${process.env.REACT_APP_API_URL}/api/post/`); setPost(res.data); console.log('data', res.data); } catch (err) { } } fetchPost(); }, []); const capitalizeFirstLetter = (word) => { if (word) return word.charAt(0).toUpperCase() + word.slice(1); return ''; }; const getPost = () => { let list = []; let result = []; posts.map(blogPost => { return list.push( <div className="row no-gutters border rounded overflow-hidden flex-md-row mb-4 shadow-sm h-md-250 position-relative"> <div className="col p-4 d-flex flex-column position-static"> <strong className="d-inline-block mb-2 text-primary">{capitalizeFirstLetter(blogPost.komite)}</strong> … -
url from UpdateView is not working in CreateView django
The question is that why can't I put a link(redirect to post_edit.html, using UpdateView) in the post_new.html(CreateView)? However, it works to put the link in the post_detail.html(DetailView). Is there any restrcition between Views? -
How to generate a PDF from content on the page - Django
I've got a model with a field for a EULA (it's kind of long, maybe about 8500 characters). This EULA is rendered to the page like so: <div class="collapse" id="library-eula"> <div class="card"> <div class="card-body"> {{ library.eula|markdownify|safe }} <a href="#" class="btn btn-primary" role="button"> Download PDF </a> </div> </div> </div> That Download PDF button is meant to be for downloading the content in the card (library.eula) as a PDF. I started with the example from Django's docs. I copied the code directly from that page. When I use this code as is in a CBV with a get method (eg, as a test -> p.drawString(100, 100, "Test page")) and then hook up a URLconf: # Download a PDF path('download/pdf', DownloadPDFView.as_view(), name='download-pdf'), And add this to the template: <a href="{% url 'download-pdf' %}" class="btn btn-primary" role="button"> Things work fine... But I'm having a hard time figuring out how to actually stick the library.eula string into the PDF. I've tried a few things but I feel like I'm going nowhere. -
Django templates url - differentiate between same url names
in my application I've got a view called download_document which works fine using {% url 'download_document' some_id %} . Installing a 3rd party app into the virtual environment cause trouble because this app has also the download_document view (also accepting one ID parameter) with the same urlname. If I'd like to use both with this name, can I somehow make the difference between them? For instance using both cases in the same template file? Python: 2.7 Django: 1.11.16 Debian . -
Two different table (nested loop?) in django template
Could you help me, please? I have two tables and I want to display different data from them on the template, here is my code: models.py: from django.db import models from suppliers.models import Company class Product(models.Model): product_name = models.CharField(max_length=200, blank=True, null=True) product_ean = models.CharField(max_length=50, blank=True, null=True) def __str__(self): return f'{self.product_name} {self.product_ean}' class Product_company(models.Model): product_name = models.ForeignKey(Product, null=True, on_delete=models.SET_NULL) company_name = models.ForeignKey(Company, null=True, on_delete=models.SET_NULL) product_price = models.CharField(max_length=50, blank=True, null=True) def __str__(self): return f'{self.product_name} {self.company_name}' views.py: from .models import * def products_list(request): product = Product.objects.all() product_company = Product_company.objects.all() context = { 'product': product, 'product_company': product_company, } return render(request, 'products/products_list.html', context) products_list.html: <table class="table"> <thead> <tr> <th>Termék neve</th> <th>Termék EAN száma</th> <th>Kihez tartozik?</th> <th>Termék ára</th> <th>Műveletek</th> </tr> </thead> <tbody> {% for i in product %} {% for x in i.product_company_set.all %} <tr> <td>{{ i.product_name }}</a></td> <td>{{ i.product_ean }}</td> <td>{{ x.company_is_registered }}</td> <td>{{ i.company_name }}</td> <td>{{ i.company_give_list }}</td> </tr> {% endfor %} {% endfor %} </tbody> </table> Unfortunately, nothing display in the Product_company table, what could be the problem? Thank you! -
Should you access cleaned_data directly in views or have a method belonging to the given form that handles working with cleaned_data?
I started experimenting with django few afternoons ago and I have an app with a custom form in which I authenticate user the following way: if form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password'] ... work with username and password ... However, I also read on some webpage (witch I no longer have in my search history :/) that you should not access cleaned_data like that and that it is better to hide using of cleaned_data to a custom method. And do something like this: if form.is_valid(): form.process() I don't think that it should matter much. Nonetheless, I'm curious which way is more preferable and django-like. Thanks! -
Django Improper URL NoReverseMatch
URL urlpatterns = [ #PAPER PROJECTS path('create-paper-project/', PTCreateView.as_view(), name='pt-create'), path('list-paper-projects/', PTListView.as_view(), name='pt-list'), path('pproj<str:pk>/', PTDetailView.as_view(), name='pt-detail'), path('pprojp<str:pk>/update/', PTUpdateView.as_view(), name='pt-update'), path('pproj<str:pk>/delete/', PTDeleteView.as_view(), name='pt-delete'), ] VIEWS class PTCreateView(generic.CreateView): model = PaperTool template_name = 'papertools/pt_create.html' success_url = '/paper-tools/list-paper-projects/' fields = ['title'] class PTListView(generic.ListView): model = PaperTool template_name = 'papertools/pt_list.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) return context class PTDetailView(generic.DetailView): model = PaperTool template_name = 'papertools/pt_detail.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) return context class PTUpdateView(generic.UpdateView): model = PaperTool fields = ['title'] template_name = 'papertools/pt_update.html' success_url = reverse_lazy('paper:pt-detail', kwargs={'pk': model.pk}) class PTDeleteView(generic.DeleteView): model = PaperTool template_name = 'papertools/pt_delete.html' success_url = reverse_lazy('paper:pt-detail') HTML <a class="nav-link" href="{% url 'pt-detail' object_list.paper.pk %}"> Paper Project Home </a> I continuously get the following error: "Reverse for 'pt-detail' with arguments '('',)' not found. 1 pattern(s) tried: ['paper\-tools/pproj(?P[^/]+)/$']" In the HTML portion if I replace the "object_list.paper.pk" portion with just a pk (say 6). This works just fine. I do not understand why this is giving off an error. There seem to be similar problems on StackOverflow but none exactly like this. -
Save data from form into 2 models using .save()
I'm creating a registration and login app with Django. I get the data using a form and POST. I want to save the form data into two Django models: class Customer(models.Model): username = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE) name = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200) def __str__(self): return self.name And the Django User model. forms.py from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from .models import * class CreateUserForm(UserCreationForm): class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] Registration View.py def registerPage(request): form = CreateUserForm() if request.method == 'POST': form = CreateUserForm(request.POST) form2 = Customer print(form) if form.is_valid(): form.save() user = form.cleaned_data.get('username') name = form.cleaned_data.get('username') email = form.cleaned_data.get('email') form2.save(user, name, email) messages.success(request, 'Account was created for ' + user) return redirect('login') context = {'form': form} return render(request, 'login/register.html', context) Now my question is, how do I save the form data into the user models AND save the data(user, name, email) into the Customers model? I tried using form2.save(user, name, email) but i get an error message: 'str' object has no attribute '_meta' Thank for any help! -
The view ecommerceapp.views.checkout didn't return an HttpResponse object. It returned None instead
I'm trying to build an ecommerce app and I'm building a form that when a particular payment option is clicked, the url is pointed to a particular one. But whenever I try to run the website, this error pops out: The view ecommerceapp.views.checkout didn't return an HttpResponse object. It returned None instead. Views.ps def checkout(request): def get(self, *args, **kwargs): if request.method == 'POST': form = checkoutForm(request.POST) if form.is_valid(): # here is the place where your find the values in: if form.cleaned_data['payment_option'] == 'Stripe': return redirect('core:payment', payment_option='Stripe') elif form.cleaned_data['payment_option'] == 'Paypal': return redirect('core:payment', payment_option='Paypal') return redirect(reverse('core:index')) else: form = checkoutForm() return render(request, 'ecommerceapp/checkout.html', {'form': form,'items': OrderItem.objects.all(), 'orders': Order.objects.all()}) -
Celery+Django+RabbitMQ - I believe tasks will queue but do not execute
Following this: https://docs.celeryproject.org/en/stable/django/first-steps-with-django.html I have a project called 'ursa' and some apps one of which is called 'core_app'. Problem: I start the task: # ./manage.py shell frPython 3.8.7 (default, Dec 22 2020, 18:46:25) [GCC 8.3.0] on linux Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> from core_app.tasks import update_gsb_status >>> update_gsb_status.apply_async(args=['https://somedomain.tld/dir/dir/file.html']) <AsyncResult: 85625fec-beea-48c0-9c7e-c9a3bd9caa2e> Nothing happens in the celery worker: [2021-02-02 12:26:00,102: INFO/MainProcess] Connected to amqp://user:**@rabbitmq:5672// [2021-02-02 12:26:00,115: INFO/MainProcess] mingle: searching for neighbors [2021-02-02 12:26:01,146: INFO/MainProcess] mingle: all alone [2021-02-02 12:26:01,168: INFO/MainProcess] celery@77267d507aec ready. ...nothing else This is the second day of banging my head against the wall on this. Notes: I am using RabbitMQ for celery but I'm also using Redis for caching. Is celery adding my tasks to the Redis queue? How can I tell? How do I not do that? If I change the ursa/ursa/settings.py file to use BROKER_URL instead of CELERY_BROKER_URL then the celery worker uses the default transport instead of the correct URL. I've also tried using the @app.task decorator instead of @shared_task by importing the celery app in ursa/core_app/tasks.py via from ursa.celery import app but the same result happens - nothing. I've also checked the celery worker to see what tasks are … -
Cannot query field \"serviceTechnician\" on type \"WorkOrderType\"
When querying for all workorders I can't access the service_technician assigned to the workorder. { "errors": [ { "message": "Cannot query field \"serviceTechnician\" on type \"WorkOrderType\".", "locations": [ { "line": 21, "column": 5 } ] } ] } This query works if you remove serviceTechnician: query workOrders { workorders { id, sameAsCustomerAddress, relatedCustomer {id, customerName, customerCity {id, locationCity}, customerZip}, serviceZip serviceCity {id, locationCity} serviceTechnician } } UserType and WorkOrderType: class UserType(UserNode): class Meta: model = get_user_model() filter_fields = app_settings.USER_NODE_FILTER_FIELDS exclude = app_settings.USER_NODE_EXCLUDE_FIELDS interfaces = (graphene.relay.Node,) skip_registry = True pk = graphene.Int() archived = graphene.Boolean() verified = graphene.Boolean() secondary_email = graphene.String() class WorkOrderType(DjangoObjectType): class Meta: model = WorkOrder fields = ('id', 'same_as_customer_address', 'service_address', 'service_city', 'service_state', 'service_zip', 'service_unit_number', 'service_technician', 'status', 'description', 'computer_brand_type', 'computer_password', 'related_customer') WorkOrderInput class WorkOrderInput(graphene.InputObjectType): id = graphene.ID() same_as_customer_address = graphene.Boolean() service_address = graphene.String() service_city = LocationInput() service_state = graphene.String() service_zip = graphene.String() service_unit_number = graphene.String() service_technician = graphene.InputField(UserInput) status = graphene.String() description = graphene.String() computer_brand_type = graphene.String() computer_password = graphene.String() related_customer = CustomerInput() Query resolve_workorder: def resolve_workorder(self, info, **kwargs): id = kwargs.get('id') if id is not None: return WorkOrder.objects.get(pk=id) return None I really have no clue why I'm unable to query this field, I have defined it in my … -
VS Code does not see sqlite3
I am building a website using Django and wanted to inspect my database using command: python manage.py dbshell however surprisingly I got CommandError: You appear not to have the 'sqlite3' program installed or on your path. I am using VS Code for my project and got the error in command prompt terminal of VS Code. I am saying surprisingly because I have already created my models before with commands python manage.py makemigrations and python manage.py migrate. These commands also don't work right now. It is impossible that sqlite3 is not installed because python installs it inherently. I assume PATH variable is also not an issue as I added it and can run sqlite3 outside of VS Code if I open command prompt from the start menu of windows. What can be the reason of this corruption/problem and how can I fix it ? This is screenshot of start menu command prompt : This is screenshot of VS Code : -
All records displayed in many to many django app
Here my models: django_zoom2/meetings/models.py from django.db import models from participants.models import Participant class Meeting(models.Model): topic = models.CharField(max_length=100) uuid = models.CharField(max_length=100, default='xxxx') participants = models.ManyToManyField(Participant) def __str__(self): return self.topic django_zoom2/participants/models.py from django.db import models # from meetings.models import Meeting class Participant(models.Model): name = models.CharField(max_length=100) email = models.CharField(max_length=100) def __str__(self): return self.email ..and the admin views: django_zoom2/meetings/admin.py from django.contrib import admin from .models import Meeting @admin.register(Meeting) class MeetingAdmin(admin.ModelAdmin): list_display = ['topic', 'uuid'] django_zoom2/meetings/admin.py from django.contrib import admin from .models import Participant @admin.register(Participant) class ParticipantAdmin(admin.ModelAdmin): list_display = ['name', 'email'] I have a single association with the meeting blarg: >>> from meetings.models import Meeting >>> m= Meeting.objects.get(id=1) >>> m <Meeting: blarg> >>> m.participants.all() <QuerySet [<Participant: molly@myorg.org>]> ...but in the view here is what I see: Why am I seeing all the participants email addresses in this view? I only want to see the associated email addresses; in this case, there should be one. Molly. -
Django / GeoDjango / PostGis - Filter FeatureCollection
Currently i have a very basic django model containing a PointField: from django.contrib.gis.db import models from django.utils.translation import gettext_lazy as _ from api.models import AbstractModel class SampleEntity(AbstractModel): point = models.PointField(_('point')) My goal is to filter all rows and check if the point is in a certain polygon... In order to create a polygon i receive the following payload (FeatureCollection): { "type": "FeatureCollection", "crs": { "type": "name", "properties": { "name": "urn:ogc:def:crs:OGC:1.3:CRS84" } }, "source": "© GeoBasis-DE / BKG 2013", "features": [{ "type": "Feature", "properties": {}, "geometry": { "type": "Polygon", "coordinates": [ [ [10.453980128926366, 47.55557895879648], [10.438876535127962, 47.52349211089603], [10.44055084477551, 47.5135694350795], [10.431323512106337, 47.5036776164676], [10.442767953986108, 47.4846168990274], [10.45131095387671, 47.485685093946636], [10.463220692620368, 47.48277492286606], [10.468022327337152, 47.47691846929882], etc.. ] ] } }, { "type": "Feature", "properties": {}, "geometry": { "type": "Polygon", "coordinates": [ [ [9.617342617593987, 47.568803310179476], [9.628007474077956, 47.570911279233016], [9.628870213746309, 47.56638028461108], [9.638605938479984, 47.56693417152559], [9.653552559008789, 47.55698746615904], [9.679038885003902, 47.55702134414172], [9.682804387548277, 47.55244003193477], [9.675623645853232, 47.54522412435771], etc.. ] ] } }] } Next i need to somehow convert my FeatureCollection to a valid "GeoDjango" Polygon in order to filter in the database: geoms = [] for feature in payload["features"]: geoms.append(GEOSGeometry(str(feature["geometry"]))) geometry = GeometryCollection(geoms) rows = SampleEntity.objects.filter(point__within=geometry) print(rows) # <- Error Raises: django.db.utils.InternalError: Relate Operation called with a LWGEOMCOLLECTION type. This is unsupported. HINT: Change argument 1: … -
django ValueError : attribute has no file associated with it
I have an annoying error that I'm not able to fix it. If the article has all 4 photos it's ok, if it doesn't have all 4 photos I got ValueError. I tried to solve this with an if statement but it seems it doesn't work. Any tips? html <div class="other"> {% if object.photo_1 %} <div class="list-one-images"> <img class="hover-shadow cursor" onclick="openModal();currentSlide(1)" src = "{{ object.photo_1.url }}"> </div> {% endif %} {% if object.photo_2 %} <div class="list-one-images"> <img onclick="openModal();currentSlide(2)" class="hover-shadow cursor" src = "{{ object.photo_2.url }}"> </div> {% endif %} {% if object.photo_3 %} <div class="list-one-images"> <img onclick="openModal();currentSlide(3)" class="hover-shadow cursor"src = "{{ object.photo_3.url }}"> </div> {% endif %} {% if object.photo_4 %} <div class="list-one-images"> <img onclick="openModal();currentSlide(4)" class="hover-shadow cursor" src = "{{ object.photo_4.url }}"> </div> {% endif %} </div> model: class Oglas(models.Model): agent = models.ForeignKey(Agent, on_delete = models.DO_NOTHING) title = models.CharField(max_length=120) address = models.CharField(max_length = 120) area = models.CharField(max_length=120) description = models.TextField(blank = True) price = models.IntegerField() bedrooms = models.DecimalField(max_digits=2, decimal_places=1) bathrooms = models.DecimalField(max_digits=2, decimal_places=1, blank = True, null = True) garage = models.IntegerField(default = 0) sqft = models.IntegerField() kategorii = (('prodava', 'prodava'),('iznajmuva','iznajmuva')) kategorija = models.CharField(max_length = 10, choices= kategorii, null = True) lot_size = models.DecimalField(max_digits=5, decimal_places=1) photo_main = models.ImageField(upload_to = 'photos/%Y/%m/%d/') … -
How to solve 'module' object is not iterable in django
I have created a Django application and initially the code worked perfectly but when I restarted the development server I started having 'module' object not iterable exception. This is my code views.py import datetime from django.contrib import messages from django.shortcuts import render from forms.forms import * from django.core.mail import send_mail from django.http import HttpResponse from patients.models import * def doctor_view(request, id): patients = Patients.objects.get(id=id) if request.method == "POST": form = DoctorForm(request.POST) if form.is_valid(): f = form.save(commit=False) date = datetime.datetime.now() f.date_seen = date f.save() messages.info(request, 'patient profile was successfully updated !!!') else: form = DoctorForm(instance=patients) date = datetime.datetime.now() return render(request, 'doctors/templates/patient_registration.html', {'form': form, 'title': 'Patient Treatment', 'patients': patients, 'date': date, 'messages': messages}) ``` urls.py from django.urls import path from . import views urlpatterns = [ path('<int:id>/', views.doctor_view, name='doctor-views'), ]``` Exception Traceback Internal Server Error: /doctor/1/ Traceback (most recent call last): File "C:\Users\SERU\Desktop\School Projects\DAS_project\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\SERU\Desktop\School Projects\DAS_project\venv\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\SERU\Desktop\School Projects\DAS_project\doctors\views.py", line 42, in doctor_view {'form': form, 'title': 'Patient Treatment', 'patients': patients, 'date': date, 'messages': messages}) File "C:\Users\SERU\Desktop\School Projects\DAS_project\venv\lib\site-packages\django\shortcuts.py", line 19, in render content = loader.render_to_string(template_name, context, request, using=using) File "C:\Users\SERU\Desktop\School Projects\DAS_project\venv\lib\site-packages\django\template\loader.py", line 62, in render_to_string return … -
Generic detail view PostDetailsText must be called with either an object pk or a slug in the URLconf
I am stuck trying to figure out how to fix this error. I'm trying to list all available categories and to display post a single overview. I know what the error is referring to (path), but I don't understand how to fix it. Here is my main url.py file urlpatterns = [ path('', PostDetailsText.as_view(), name='post_more_details'), ] These are my views for lisitng and details: class CategoryListing(TemplateResponseMixin, View): model = Post template_name = 'publications/posts/listing_posts.html' def get(self, request, category=None): categories = Category.objects.annotate(total_posts=Count('posts')) posts = Post.objects.annotate(total_modules=Count('modules')) if category: category = get_object_or_404(Category, slug=category) posts = posts.filter(category=category) return self.render_to_response({'categories': categories, 'category': category, 'posts': posts}) class PostDetailsText(DetailView): model = Post template_name = 'publications/posts/posts_details.html' The urls of the app: urlpatterns = [ path('category/<slug:category>/', views.CategoryListing.as_view(), name='categories_listing'), path('<slug:slug>/', views.PostDetailsText.as_view(), name='post_details'), ] This is how it looks like my html for listing the items: <div class="contents"> <h3>Categories</h3> <ul id="modules"> <li {% if not category %}class="selected"{% endif %}> <a href="{% url 'post_more_details' %}">All</a> </li> {% for s in categories %} <li {% if category == s %}class="selected"{% endif %}> <a href="{% url 'categories_listing' s.slug %}"> {{ s.subject }} <br><span>{{ s.total_posts }} posts</span> </a> </li> {% endfor %} </ul> </div> <div class="module"> {% for post in posts %} {% with category=post.category %} … -
Webpack configuration for react and django app
I am planning to make a boilerplate in GitHub between React and Django To facilitate me later When I start a project I chose the connection method React as Django app django-admin startapp frontend The problem I am facing now is that I am using the Django templates. I cannot split packages using wepback because there must be {load static} {static ''index.js"} However, I cannot use Splitchuncks in configuring a webpack or HTML plugin to insert script tags into HTML. The entire code must be inside one js file and that too with CSS webpack.config.js const path = require("path"); const webpack = require("webpack"); // const TerserPlugin = require('terser-webpack-plugin'); const HtmlWebpackPlugin = require("html-webpack-plugin"); const MiniCssExtractPlugin = require("mini-css-extract-plugin"); const devMode = process.env.NODE_ENV !== "production"; module.exports = { entry: "./src/index.js", output: { path: path.resolve(__dirname, "./static/frontend"), filename: "[name].js", }, module: { rules: [ { test: /\.js$/, exclude: /node_modules/, use: { loader: "babel-loader", }, }, { test: /\.css$/, use: [ devMode ? "style-loader" : MiniCssExtractPlugin.loader, "css-loader", "postcss-loader", ], }, { test: /\.(ttf|eot|woff|woff2|jpg|jpeg|png|gif|mp3|svg|ico)$/, loader: "file-loader", options: { outputPath: path.resolve(__dirname, "./static/images"), }, }, ], }, optimization: { minimize: true, // splitChunks: { // chunks: 'all', // name: false, // }, }, plugins: [ new HtmlWebpackPlugin( Object.assign( {}, … -
Django- update a DateField model entry to be a string as a default
I have a function in my Django model: def add_default_date This function, if called from the view, checks to see if publish_date is None and if it is, I'd like to change publish_date to be text: "Date Needed". However right now when I do this I get an error: "'Date Needed' value has an invalid date format. It must be in YYYY-MM-DD format.". It appear that I'm trying to assign a string to a DateField but it's not working. Is there anyway to do this? Models.py: class Byte(models.Model): """Model for databyte content.""" publish_date = models.DateField(blank=True, null=True) def add_default_date(self): if self.publish_date is None: self.publish_date = "Date Needed" Views.py: bytes = Byte.objects.order_by( F('publish_date').desc(nulls_last=True) ) for b in bytes: Byte.add_default_date(b) b.save()