Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Looping through database to display images in Django template
I am new to Django, I have read the documentation and other's questions here on Stackoverflow, but I have not been able to resolve the error on my own. This is for development only as of now. When I try to loop through and pull images from the database to display in my template, I get the error: "GET /images/tokyo.jpg HTTP/1.1 404 Not Found: /images/tokyo.jpg" However, I have saved the images to the database and they are listed in media/images. I am creating an app that displays bucket list travel destinations. The other fields from my database such as city, country, and flight time display as intended, I am only having issues with the image. What am I getting wrong? I have included all of my code to be thorough. Thank you in advance! My settings.py STATIC_URL = 'static/' STATIC_ROOT = BASE_DIR / "staticfiles" STATICFILES_DIRS = [BASE_DIR / "static"] STATICFILES_STORAGE = "django.contrib.staticfiles.storage.StaticFilesStorage" MEDIA_URL = '/media/' MEDIA_ROOT = BASE_DIR / 'media' My urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', include('travel.urls')), ] urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) My models.py ADVENTURE_CHOICES = ( ('beach', 'Beach'), ('diving', 'Diving'), ('city', 'City'), ('hiking', 'Hiking'), ) CLIMATE_CHOICES = ( ('tropical', 'Tropical'), ('cold', … -
How to save multiple data in database by Django query set from Html table
I am creating sales invoice where I create one form with two database table connections like sales details are saving in Sales_Invoice table and Items which we add in invoice will save in Item_Details table. So here in html form I am creating table for add items after adding that I items I wish to save sales invoice in sales_details and all items in Item_Details by using sales_invoice foreign key My data is saving but only one row is saving How can I save multiple data in django by using queryset Html Form <form method="post"> {% csrf_token %} <!-- Estimate Details --> <div class="row pb-3 pt-3"> <div class="col-md mb-2"> <label>Invoice Number</label> <input type="text" class="form-control" placeholder={{invoice_number}} name="invoice_number"> </div> <div class="col-md mb-2"> <label>Date</label> <input type="date" class="form-control" placeholder="Invoive_Date" name="invoice_date"> </div> <div class="col-md mb-2"> <label>Select Customer</label> <select id="customer_id" class="form-control" name="customer_id"> <option value="">Select Customer</option> {% if all_customers %} {% for c in all_customers %} <option value="{{c.customer_id}}">{{c.first_name}} {{c.surname}}</option> {% endfor %} {% endif %} </select> </div> </div> <div class="row pb-3"> <div class="col-md-4 mb-2"> <label>Contact Person Name</label> <input type="text" class="form-control" id="contact_person_name" name="contact_person_name" placeholder="Contact Person"> </div> <div class="col-md-4 mb-2"> <label>Phone</label> <input type="number" class="form-control" placeholder="Phone" id="phone" name="phone"> </div> </div> <div class="row pb-3"> <div class="col-md mb-2"> <label>Bill To</label> <textarea type="text" … -
Django Size (Dropdown) and Color (Buttons) change product prices of color button data JQuery
Product color dose not change according to size but price change according to color and selected size default selected size Views.py File vies.py detail page -
Django Show all posts from a single user
I'm building an instagram-ish clone in Django. I have the basic functionality working, where a user can post an image, and this is displayed on the main page. I would like to make a 'user page' that only displays posts from a user. For example, example.com/foobar would only display posts from the user 'foobar'. I believe i have the urls.py and template working correctly, but I can not figure out how to only iterate through items and pull out ones of a specific user. I realize this should be a queryset of some kind, but other than that I'm stumped. Should this be its own class, or could I extend the existing PostList class to pull out a single author's posts? post_detail.html - gets all the images stored in the database, this works fine. {% for post in object_list %} <td><a href="{% url 'detail' pk=post.pk %}"><img src="{{ post.image.url }}" width="300"></a></td> {% if forloop.counter|modulo:4 %} </tr><tr> {% endif %} {% endfor %} profile.html - shows all posts from a user (as in example.com/foobar) <table> <tr> {% for post in object_list %} <td><a href="{% url 'detail' pk=post.pk %}"><img src="{{ post.image.url }}" width="300"></a></td> {% if forloop.counter|modulo:4 %} </tr><tr> {% endif %} {% endfor … -
I keep getting the error: no such table: blog_category even when i try running python3 manage.py makemigrations and python3 manage.py migrate
i have checked over a lot of posts and they all say to run python3 manage.py makemigrations and python3 manage.py migrate or even python3 manage.py migrate --run-syncdb but the problem is that i get this error when i run those commands as well as when i run python3 manage.py runserver: return Database.Cursor.execute(self, query, params) django.db.utils.OperationalError: no such table: blog_category the other problem is that i don't every have any code that says blog_category so i don't even know where django is getting that from. i'v tried different venv's to see if other installed programs were the problem but the error persists. Please help. -
how can i save images files in Django
I want to receive several image groups in one form and save them. I want to save each image group with the same main title and different title. How can I save and target images files on views.py? I didn't hand over the form to the request from views.py because the user could add and delete the content. Is there a way to use a form tag when I want to receive data that I don't know how many? views.py def debate_create(request): if request.method == "POST": content = request.POST.items() for k,v in content: if k == 'sup_title': sup_title = SuperTitle() sup_title.author = request.user sup_title.super_title = v sup_title.save() sup_title_id = sup_title.id elif 'img' not in k and 'opt' not in k and 'section' in k: sub_title = Subtitle() sub_title.super_title = get_object_or_404(SuperTitle, pk = sup_title_id) sub_title.sub_title = v sub_title.save() elif 'img' in k and v != '': stg = Images() # imgs = request.FILES.getlist("?????") # for image in imgs stg.sub_title = get_object_or_404(Subtitle, pk = sub_title.id) stg.save() elif 'section' in k and 'opt' in k: opt = SelectOption() opt.sub_title = get_object_or_404(Subtitle, pk = sub_title.id) opt.option = v opt.save() return render(request, 'polls/test.html') else: pass html <form method="POST" id="debate_form" action="{% url 'polls:debate_create' %}"> {% csrf_token … -
How to re-search the results of a Q object (django-q)
I am currently trying to display search results in the Q object, but the search results do not contain the values specified in the search. The cause is unknown, but the search is mainly in the following form. result = resultObject.filter(conditions) Contents of conditions <Q: (AND: ('search__icontains', '3'), ('search__icontains', '5'))> The above results in results that do not contain 3 or 5, so I would like to re-search again and extract only the results that contain the target value. I am looking for a way to re-search the results returned by result as above. Is there any way to re-search from the following situation? result = resultObject.filter(conditions) -
How should I save, process and update textarea data (while the user is still editing it) in Django?
I need to process (on the server) and save constantly changing text data from a texarea to the database and update the textarea with the processed data at the same time. I also need to do this automatically, without the user submitting the data explicitly by clicking a button. I am making a grammar checker like Grammarly and trying to replicate its functionality. So I am looking for some guidance, some hints. I am using Postgres on Heroku. -
How do I add content to my Django blog application?
I created a simple Django app part of which is a blog. It is easy enough to create the models , views, and templates for this, and most tutorials stop here. I'm trying to go to the next level and add proper html formatted content to my website. So far I have been writing html and rendering it before logging into the admin panel and copying the raw html into the blog post model. It is tedious to do it this way and I feel like there should be a better way. Any suggestiong? This is what I use to show the content of the post model <div class="card-body"> <h1>{% block title %} {{ object.title }} {% endblock title %}</h1> <p class=" text-muted">{{ post.author.get_full_name }} | {{ post.created_on }}</p> <p class="card-text ">{{ object.content | safe }}</p> </div> Notice the use of Django template system's | safe flag. object.content is raw html which I write for each blog post. -
Fetch user details from another model
I have a model(Poll) which contains another model(User) with user details. I want to get the Username of who posted a poll but the below is error occurred I/flutter (21892): type 'int' is not a subtype of type 'String' this is my model class(flutter) import 'dart:convert'; class Poll { Poll({ required this.id, required this.choices, required this.question, required this.pubDate, required this.createdBy, }); late final int id; late final List<Choices> choices; late final String question; late final String pubDate; late final User createdBy; Poll.fromJson(Map<String, dynamic> json) { id = json['id']; choices = List.from(json['choices']).map((e) => Choices.fromJson(e)).toList(); question = json['question']; pubDate = json['pub_date']; createdBy = User.fromJson(jsonDecode(json['created_by'])); } Map<String, dynamic> toJson() { final _data = <String, dynamic>{}; _data['id'] = id; _data['choices'] = choices.map((e) => e.toJson()).toList(); _data['question'] = question; _data['pub_date'] = pubDate; _data['created_by'] = createdBy.toJson(); return _data; } } class Choices { Choices({ required this.id, required this.choiceText, required this.poll, }); late final int id; late final String choiceText; late final int poll; Choices.fromJson(Map<String, dynamic> json) { id = json['id']; choiceText = json['choice_text']; poll = json['poll']; } Map<String, dynamic> toJson() { final _data = <String, dynamic>{}; _data['id'] = id; _data['choice_text'] = choiceText; _data['poll'] = poll; return _data; } } class User { User({ required this.id, required this.password, … -
what's the best way to deal with inheritance in django
i have three types of products Course,Book, Paint, and i have A Cart and CartItem models,i was thinking of using multitable inheritance in Django which will be something like this: class Product(models.Model): name = models.CharField(max_lenght=50) ...... class Course(Product): ...... class Book(Product): ...... class Cart(models.Model): ..... class CartItem(models.Model): cart = models.ForeignKey(Cart) product = models.ForeignKey(Product) but i was reading that multitable inheritance is not good to use due to it's impact on the performance, so what's the best approach to deal with this? -
Questions regarding Flutter Web and Django Rest API
I am trying to make this blog website for my university, I am using flutter for the frontend and DRF for the backend. I have some questions regarding these. Do I need to host my DRF API in order to fetch data from the server? will it work if I use the free version of heroku? Is there a way I can access the Django admin panel from the flutter frontend? like, assign new users using the admin panel that Django offers? Thank you -
Serving django application via apache and development server results different character encoding
I've the following setup: Django: 4.0.5 Python: 3.9.2 Debian: 11.1 Apache2: 2.4.53-1~deb11u1 libapache2-mod-wsgi-py3: 4.7.1-3+b1 mariadb-server-10.5: 1:10.5.15-0+deb11u1 . When I run my application from the development server (same virtualenv, same code), it runs without any error, but when I run the same via apache2, it throws some kind of encoding error here: strx = 'sth %s' % name f = open('/tmp/somerandomfile', 'w') f.write(strx) . The name variable is coming from the database and contains a national character. When I print it via the development server and apache2, I got these: #development server - to the console print(strx, type(strx)) Kiadások <class 'str'> #apache2 - to the apache log file print(strx, type(strx)) Kiad\xc3\xa1sok <class 'str'> . So it seems the 2 str differs in encoding. The development server serves with 200, however, apache2 serve fails with the following error: UnicodeEncodeError: 'ascii' codec can't encode character '\\xe1' in position 5: ordinal not in range(128) To fix it's easy, however, I'm rather interested why do I get a different result via the development server and apache2? How can I set it to have the same result. As mentioned, I'm using wsgi. Any idea where I could check for differences? And how could I have the … -
How do I pass 'user_id' to CustomerSerializer?
tldr; I don't know how to pass user_id from requests.user.id and use it in the CustomerSerializer to save the object to the database. The error stems from the fact user_id exists in the customer table, in the database but it does not show up as a field to be passed in the rest_framework api frontend (only phone and profile_image do). Here is the Customer model: class Customer(models.Model): phone = models.CharField(max_length=14) profile_image = models.ImageField(blank=True, null=True) user = models.OneToOneField( settings.AUTH_USER_MODEL, on_delete=models.CASCADE) Here is the ViewSet: class CustomerViewSet(ModelViewSet): queryset = Customer.objects.all() permission_classes = [permissions.IsAdminUser] serializer_class = CustomerSerializer # Only admin users can make requests other than 'GET' def get_permissions(self): if self.request.method == 'GET': return [permissions.AllowAny()] return [permissions.IsAdminUser()] @action(detail=False, methods=['GET', 'PUT']) def me(self, request): customer, created = Customer.objects.get_or_create(user_id=request.user.id) if request.method == 'GET': serializer = CustomerSerializer(customer) return Response(serializer.data) elif request.method == 'PUT': serializer = CustomerSerializer(customer, data=request.data) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data) ... and here is the Serializer: class CustomerSerializer(serializers.ModelSerializer): class Meta: model = Customer fields = ['id', 'user_id', 'profile_image', 'phone'] ...and when I try to save a new customer by sending a POST request to the endpoint with the following data: { "profile_image": "Images/image.png", "phone": "009293930" }, I get the following error: IntegrityError at /api/customers/ (1048, … -
unable to access related objects with generic foreign key in Django and content types
hey guys i don't know if what i am doing is right but i have these class or model class CartItem(models.Model): cart = models.ForeignKey(Cart, on_delete=models.CASCADE) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.UUIDField() content_object = GenericForeignKey('content_type','object_id') and i have this related model using the generic foreign key class MstProduct(PhysicalProduct): user = models.ForeignKey(User, models.PROTECT) purposes = models.ManyToManyField(ProductPurpose, null = True, blank = True, related_name='products') madeOf = models.ManyToManyField(AffeliateProduct, null = True, blank = True) category = models.ForeignKey(Category, on_delete=models.PROTECT, related_name = "physical_products") theme = models.ForeignKey(Theme, on_delete= models.SET_NULL, null = True, blank = True, related_name = 'physical_products') art_type = models.ForeignKey(ArtType, on_delete=models.SET_NULL, null = True,blank = True) cart_items = GenericRelation(CartItem,related_query_name='product') what i wanna do is to access the product related to CartItem instance from the generic foreign key field, i tried to do it using the related_query_name argument but after trying this: CartItem.objects.first().product i get an error like this: Traceback (most recent call last): File "/home/alaa/.local/lib/python3.10/site-packages/django/db/models/fields/related_descriptors.py", line 678, in get_queryset return self.instance._prefetched_objects_cache[ AttributeError: 'CartItem' object has no attribute '_prefetched_objects_cache' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "", line 1, in File "/home/alaa/.local/lib/python3.10/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/alaa/.local/lib/python3.10/site-packages/django/db/models/fields/related_descriptors.py", line 683, in get_queryset return self._apply_rel_filters(queryset) … -
Issue with deleting Items in a list in another list in python
I have a code that essentially deletes any item in a list that is present in another list which contains more items that the list which deletes. The list which deletes contains image name of images i want to delete from the image upload input by user This is the first code: for i in images: if i.name in adi: # del images[images.index(i)] images.pop(images.index(i)) This works for small file inputs but whenever i try to upload up to 21 or 20 image inputs then it errors in the amount it deletes whilst not deleting some items to be deleted in the list. So i tried running the same code twice: for i in images: if i.name in adi: # del images[images.index(i)] images.pop(images.index(i)) for k in images: if k.name in adi: images.pop(images.index(k)) Still with this, after accepting user input, there's still going to be at least one image remaining in the list that is meant to be deleted. Is anything wrong with the logic i'm using for implementation and if something is, how should i implement it instead -
Any reason Django not getting the hostname? Django multi tenancy
I am having an issue with displaying database items within my our_team template. I am able to get all of the items from members (using .all()), but when I filter using tenant, I am not getting anything at all. Am I getting the hostname (subdomain) in the wrong way? Here is my code: views.py from django.shortcuts import render from .models import Member from .utilities import get_tenant def our_team(request): tenant = get_tenant(request) members = Member.objects.filter(tenant=tenant) return render(request, 'tenant/our_team.html', {'tenant': tenant, 'members': members}) utilities.py from .models import Tenant def get_hostname(request): return request.get_host().split(':')[0].lower() def get_tenant(request): hostname = get_hostname(request) subdomain = hostname.split('.')[0] return Tenant.objects.filter(subdomain=subdomain).first() models.py from django.db import models class Tenant(models.Model): name = models.CharField(max_length=100) subdomain = models.CharField(max_length=100, unique=True) def __str__(self): return self.name class TenantAwareModel(models.Model): tenant = models.ForeignKey(Tenant, on_delete=models.CASCADE) def __str__(self): return self.tenant class Member(TenantAwareModel): name = models.CharField(max_length=100) def __str__(self): return self.name template (HTML) - used right now for testing <h1>{{ tenant.name }}</h1> <h2>Our Members</h2> <ul> {% for member in members %} <li>{{ member.name }}</li> {% endfor %} </ul> -
Is multitable inheritance that bad in django?
hey guys i was reading a lot about how we should avoid multi table inheritance in Django, i tried to use content types instead but i couldn't access the related object from the genericforeignkey field, please if anyone can help me with some information i really appreciate it -
Static files not loading on Amazon Bean Stalk for Django app
I know this question has been asked many times and I have tried all solutions mentioned on Stackoverflow but I didnt get mine to work. So here is my question: My dbmigrate.config file (under.ebextensions) has the following entries: option_settings: aws:elasticbeanstalk:environment:proxy:staticfiles: /static: static container_commands: 03_collect_static: command: "source /var/app/venv/*/bin/activate && python3 manage.py collectstatic" leader_only: true The static files are not loaded at run time. When I looked at the logs, the log file (/var/log/cfn-init-cmd.log) showed me that the static files were copied to this folder: [INFO] 398 static files copied to '/var/app/staging/platform-site/settings/static' However when I looked at the logs of NGNIX (/var/log/nginx/error.log) I saw that it was trying to load the static files from another folder: [error] 1717#1717: *11 open() "/var/app/current/static/platform/images/sensitive_data.png" failed (2: No such file or directory), client: 172.31.26.84, server: , request: "GET /static/platform/images/sensitive_data.png HTTP/1.1", host: "xxxx.elasticbeanstalk.com My code is located under: /var/app/current So i dont get it as to why the script from EB is putting all my static files under a folder called var/app/staging/platform-site My folder structure is as follow: .ebextensions platform platform_site manage.py settings.py -
Django query filtering in paginated search_view
I have an issue to filter my queryset with following view: def innovation_search_result_view(request, *args, **kwargs): context = {} searched = '' # Search if request.GET: searched = request.GET.get('eWords', '') context['searched'] = searched lookup=(Q(ttg__icontains=searched)) searched_innovations = Innovationdb.objects.filter(lookup) searched_items = searched_innovations.count() # Pagination page = request.GET.get('page', 1) p = Paginator(searched_innovations, 50) try: searched_innovations = p.page(page) except PageNotAnInteger: searched_innovations = p.page(10) except EmptyPage: searched_innovations = p.page(p.num_pages) return render(request, 'web_page/innovation-search-result.html', {'searched':searched, 'searched_items':searched_items, 'searched_innovations':searched_innovations}) I just do not understand why it does not do a trick. It simply renders full list of instances. Any hints please... -
Django not Redirecting due to Page not Found Error
I am creating an edit profile function that updates the profile and redirects back to the profile page of the current user. Currently, the updating works fine, but the redirection is giving me a page not found error. Why is that happening? url patterns: urlpatterns = [ path('change-profile/', users_views.change_profile, name='change_profile'), path('user/<str:username>/', UserProfileView.as_view(), name='user-profile'), ... ] views.py @login_required def change_profile(request): if request.method == 'POST': u_form = UserUpdateForm(request.POST, instance=request.user) p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile) if u_form.is_valid() and p_form.is_valid(): u_form.save() p_form.save() messages.success(request, 'Profile Updated') return redirect('user-profile', {'username':request.user.username}) else: u_form = UserUpdateForm(instance=request.user) p_form = ProfileUpdateForm(instance=request.user.profile) context = { 'u_form' : u_form, 'p_form' : p_form } return render(request, 'users/change_profile.html', context) Error message -
Django Saas and Multi Tenant
I am really struggling on how I should start this new project. This will be my first SaaS/Multi Tenant app. The app is an inventory management application. The way the app will work, the user will sign up and make an account. Once the user is signed up, they can create a Inventory Management portal. Now, I am struggling if it would be best to do the Multi Tenant (Shared Database, Isolated Schema) approach, or do it to where I just assign the the request.user to the Inventory Management portal that they had just created. Would it be better to go the Multi Tenant approach where they get their own subdomain, or better to just display data that is associated with the users/portal id? -
Django simplejwt + django-allauth how to issue personal access token for social media authentication
I'm implementing a service that allows users to sign up via normal username + password, google, facebook and github. I have the authentication working on my decoupled frontend and backend, but here's my issue. I am developing some python CLI tool which uploads data to the backend, but users must be authenticated to do so. I have had no issue authenticated users via the normal username + password endpoint, but i'm struggling to see how to achieve this with the social media authentication. I have been thinking that users should be able to issue personal access tokens via the frontend (similar to github's personal access token), but my question would be how can I do that? I would imagine this requires extending the login endpoint for django-simplejwt package? -
Django conditional many-to-many relation exists check
The model is: class RecordModel(BaseModel): visibility_setting = models.PositiveIntegerField() visible_to = models.ManyToManyField(UserModel, blank=True) I need to return rows depending on row visibility_setting: if visibility_setting == 0 - return row without any checks, if visibility_setting == 1 - I need to check if user is in visible_to m2m relation exists. In second case query works okay, but in first case my approach of setting None on first case not working (as expected): Feed.objects.filter( visible_to=Case( When(visibility_setting=0, then=None), # no data returned in this case, but I want to # return all rows with visibility_setting=0 When(visibility_setting=1, then=user.id), # rows with visibility_setting=1 are queried okay ) ) I am a little bit stuck which way to use in this situation? Can we not apply case at all in some conditions or use some specific default to skip visible_to relations check? -
serializer not being called AttributeError: 'str' object has no attribute '_meta'
I modified the Auth User by using AbstractUser Class. Registered it in settings. Everything else is working I can create an instance using the User Model BUT The Problem comes during the serialization. My serializer doesn't throw any error, but any time I try and use the serializer.data I get AttributeError: 'str' object has no attribute '_meta'. User Model class User(AbstractUser): # Add additional fields here email = models.EmailField(max_length=254, unique=True) name = models.CharField(max_length=100) username = models.CharField(max_length=100) password = models.CharField(max_length=100) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=False) date_joined = models.DateTimeField(auto_now_add=True) last_login = models.DateTimeField(auto_now=True) first_name=None last_name=None USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['name', 'username', 'password'] objects = CustomUserManager() def __str__(self): return self.email # Ensure that the password is hashed before saving it to the database def save(self, *args, **kwargs): self.password = make_password(self.password) super(User, self).save(*args, **kwargs) Custom Manager from django.contrib.auth.base_user import BaseUserManager from django.utils.translation import gettext_lazy as _ class CustomUserManager(BaseUserManager): def create_user(self, email, password, **extra_fields): """ Create and save a User with the given email and password. """ if not email: raise ValueError(_('The Email must be set')) email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save() return user def create_superuser(self, email, password, **extra_fields): """ Create and save a SuperUser with the given email and password. …