Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django redirect user to shopping cart after item is added
In a Django / python website, I have a button that adds the selected item to the shopping cart but I need the user to then be redirected to the cart, but nothing I've tried has worked. Any help would be appreciated. I'm a novice at this. The button code: <button data-product="{{product.id}}" data-action="add" class="btn button button--primary add-btn update-cart"> Book this event </button> -
how to automatically update daily datetime in django
Hi I want to automatically update datetime daily in my database and put the today date as now then it show the subtract the start day and no and give me the delta is there any way to do this? -
django HttpResponseRedirect broken when accessing external url
I'm experiencing strange behaviour with my django app. I'm trying to use basic HttpResponseRedirect() but redirect to url outside of my application. This works flawlessly on django development server but is broken in my production environment. Namely, it does not redirect to external url but only applies relative path of the url to base url of my app (trying to redirect from facebook.com to google.com/maps, ends up in facebook.com/maps). I gutted my backend but there is nothing suspicious, therefore combined with issue appearing only in production env I suspect its problem of apache config. I inherited this app and have very little insight into server configuration, so I'm posting what seems important and will be grateful for any of your insights. I replaced some lines which seemed confidential with "// removed before sending to public". fyi rule in RewriteEngine does not trigger it LoadModule expires_module modules/mod_expires.so LoadModule ssl_module modules/mod_ssl.so LoadModule proxy_module modules/mod_proxy.so LoadModule proxy_http_module modules/mod_proxy_http.so LoadModule rewrite_module modules/mod_rewrite.so LoadModule socache_shmcb_module modules/mod_socache_shmcb.so Listen 443 SSLPassPhraseDialog builtin SSLSessionCache shmcb:/var/cache/mod_ssl/scache(512000) SSLSessionCacheTimeout 300 Mutex default SSLRandomSeed startup file:/dev/urandom 256 SSLRandomSeed connect builtin SSLCryptoDevice builtin <VirtualHost *:80> ServerName // removed before sending to public Redirect / // removed before sending to public </VirtualHost> <VirtualHost *:443> … -
Why Do I Need Cors Headers For One App But Not For Another Identical App?
I have two (almost) identical Angular PWA apps that are inside ASPNET wrappers. One is hosted at port 5000 and the other is hosted at 5002. location /app1/ { proxy_pass http://localhost:5000/; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection keep-alive; proxy_set_header Host $host; proxy_cache_bypass $http_upgrade; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } location /app2/ { proxy_pass http://localhost:5002/; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection keep-alive; proxy_set_header Host $host; proxy_cache_bypass $http_upgrade; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } The app downloads data from a Django server at /home/apps/djangoapp/media/JSON: ### Upload App ### MEDIA_ROOT = '/home/apps/djangoapp/media' MEDIA_URL = '/media/' JSON_URL = 'JSON/' DATA_UPLOAD_MAX_NUMBER_FIELDS = 100000 CORS_ALLOW_ALL_ORIGINS = True DATA_UPLOAD_MAX_MEMORY_SIZE = 10242880 The file is created with a post request and is owned by www-data after creation, no matter which app creates the file. For some reason, I can't download on the app2 (at port 5002) without passing Access-Control-Allow-Origin' '*' from NGINX for the media folder. location /media { alias /home/apps/djangoapp/media; add_header 'Access-Control-Allow-Origin' '*'; } It doesn't seem like this is the way to do it, especially since the other app apparently doesn't need the cors headers. And to further complicate things, app1 doesn't even complain about the headers being there when I put … -
How to render my formset using django-formtools?
I am using a form that will appear in multiple steps and in some cases with the formset button, everything was fine until I put django-formtools and if several forms appear in multiple steps. The problem is that what I had in JS does not appear to me, for example I had an "add form" button that when I clicked, the forms I wanted to add appeared, and now with django-formtools it no longer appears. I don't know if it's more because of the template, maybe I'm not rendering it as it should new-customer.html (this is how it looks with form-tools) <p>Step {{ wizard.steps.step1 }} of {{ wizard.steps.count }}</p> <form action="" method="post">{% csrf_token %} <table> {{ wizard.management_form }} {% if wizard.form.forms %} {{ wizard.form.management_form }} {% for form in wizard.form.forms %} {{ form }} {% endfor %} {% else %} {{ wizard.form }} {% endif %} </table> {% if wizard.steps.prev %} <button name="wizard_goto_step" type="submit" value="{{ wizard.steps.first }}">first step</button> <button name="wizard_goto_step" type="submit" value="{{ wizard.steps.prev }}">prev step</button> {% endif %} <input type="submit" value="submit"/> </form> new-customer.html (example of what it looks like without formtools and what works) <tbody> {{ manoObra_formset.management_form }} {% for form in manoObra_formset %} <div class="form-rows"> <tr> <td> {{form.codigo}} </td> … -
in Django how do I make my product page display only the variations in stock, when a user has selected 1 variation?
I am new to Django and trying to create an e-commerce website as a learning project. I am building the page for viewing the details of a single product and my problem is this: -the product has two variation types for users to select (size and color). These are HTML elements, showing the different ProductVariations as options. One has the options of small, medium, large and the other has red, green. blue. -when the user selects one variation (Color: Red), then I want the other select element to ONLY display the sizes in stock for that product, in that color. And likewise, if the user chooses Size: Medium then I want the Select element for color to only show the colors available in medium. Here are my models: class Product(models.Model): category_fk = models.ForeignKey(to=Category, on_delete=models.CASCADE) subcategory_fk = models.ForeignKey(to=SubCategory, on_delete=models.CASCADE) product_name = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200,unique=True) description = models.TextField(max_length=500, blank=True) price = models.IntegerField() image = models.ImageField(upload_to='photos/products') class VariationCategory(models.Model): name = models.CharField(max_length=50,unique=True) class ProductVariation(models.Model): product_id = models.ForeignKey(to=Product, on_delete=models.CASCADE) variation_category = models.ForeignKey(to=VariationCategory,on_delete=models.CASCADE,null=True) variation_value = models.CharField(max_length=100,) date_created = models.DateTimeField(auto_now_add=True) class ProductStock(models.Model): product_fk = models.ForeignKey(to=Product,on_delete=models.CASCADE, related_name="productstock") variation_mtm = models.ManyToManyField(to=ProductVariation,blank=True,) quantity = models.IntegerField() date_created = models.DateField(auto_now_add=True,null=True) date_updated = models.DateField(auto_now=True) for clarity: examples of VariationCategory would be … -
UUID breaking the ws connect
I've been using a websockets connection with django-channels for a chatroom app with the following routing: re_path(r'ws/chat/(?P<room_name>\w+)/participant/(?P<user>\w+)/$', consumers.ChatConsumer.as_asgi()) So if the id of my chatroom is 1, to connect to WS I would use the following url with 2 being the id of the participant that wants to enter the room: ws/chat/1/participant/1/ Now i changed the id of my room model to UUID so now to connect to a room I need to use the following url ValueError: No route found for path 'ws/chat/84f48468-e966-46e9-a46c-67920026d669/participant/1/ where "84f48468-e966-46e9-a46c-67920026d669" is the id of my room now, but I'm getting the following error: raise ValueError("No route found for path %r." % path) ValueError: No route found for path 'ws/chat/84f48468-e966-46e9-a46c- 67920026d669/participant/1/'. WebSocket DISCONNECT /ws/chat/84f48468-e966-46e9-a46c-67920026d669/participant/1/ [127.0.0.1:50532] My consumers: class ChatConsumer(WebsocketConsumer): def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.user = self.scope['url_route']['kwargs']['user'] self.room_group_name = 'chat_%s' % self.room_name # Join room group async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) self.accept() def disconnect(self, close_code): delete = delete_participant(self.room_name, self.user) if delete == 'not_can_delete_user': pass else: # Leave room group channel_layer = get_channel_layer() async_to_sync(channel_layer.group_send)( f'chat_{self.room_name}', { 'type': 'receive', 'message': "USER_DISCONNECT", 'body': { 'participant': delete, 'idParticipant': self.user } } ) async_to_sync(self.channel_layer.group_discard)( self.room_group_name, self.channel_name ) def receive(self, text_data=None, type='receive', **kwargs): if isinstance(text_data, dict): text_data_json = text_data message = text_data_json['message'] … -
Django js tabs keep selected tab on page refresh
I'm working with js tabs (https://www.w3schools.com/howto/howto_js_tabs.asp) in Django and they work fine but I'd like to keep the selected tab active on that moment on page refresh. Is there an easy way to do it? I found similar questions but they are not valid for my case... This is the script I'm using: function openTab(evt, tabName) { var i, tabcontent, tablinks; tabcontent = document.getElementsByClassName("tabcontent"); for (i = 0; i < tabcontent.length; i++) { tabcontent[i].style.display = "none"; } tablinks = document.getElementsByClassName("tablinks"); for (i = 0; i < tablinks.length; i++) { tablinks[i].className = tablinks[i].className.replace(" active", ""); } document.getElementById(tabName).style.display = "block"; evt.currentTarget.className += " active"; } -
How to fix css in django cycle?
I want to do div titleblog and do magrin-top:100px,but it isnt working in django cycle..Idk why.I tried to do <a class='titleblog',but it wasnt working). P.S css file is attached at html file.CSS file is working,because navigation panel is displaying. blog.html <div class="titleblog"> {% for i in objects %} <a href="{{i.id}}">{{i.titleblog}}</a> <b>{{i.message | lower}}</b> {% endfor %} </div> home.css .titleblog{ margin-top: 100px; } -
Exposing simple types on WSDL with Spyne
We are trying to build a SOAP app with Django + Spyne building specific required endpoints. The exposed WSDL has to precisely match a predetermined XML file, including the custom simpleType definitions. We're currently failing to show the simple type definitions on our WSDL, everything else matches up precisely. A simple example is the following hello world app: import logging logging.basicConfig(level=logging.DEBUG) from spyne import Application, rpc, ServiceBase, \ Integer, Unicode, SimpleModel from spyne import Iterable from spyne.protocol.xml import XmlDocument from spyne.protocol.soap import Soap11 from spyne.interface.wsdl import Wsdl11 from spyne.server.django import DjangoApplication from django.views.decorators.csrf import csrf_exempt class IdType(SimpleModel): __type_name__ = "IdType" __namespace__ = 'spyne.examples.hello' __extends__ = Unicode class Attributes(Unicode.Attributes): out_type = 'TxnIdType' class HelloWorldService(ServiceBase): @rpc(IdType, Integer, _returns=Iterable(Unicode)) def say_hello(ctx, TxnIdType, times): for i in range(times): yield 'Hello, %s' % TxnIdType application = Application([HelloWorldService], tns='spyne.examples.hello', interface = Wsdl11(), in_protocol=Soap11(validator = 'lxml'), # out_protocol=XmlDocument(validator='schema') out_protocol=Soap11() ) hello_app = csrf_exempt(DjangoApplication(application)) Which yields the following WSDL: <wsdl:definitions xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:plink="http://schemas.xmlsoap.org/ws/2003/05/partner-link/" xmlns:wsdlsoap11="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:wsdlsoap12="http://schemas.xmlsoap.org/wsdl/soap12/" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:soap11enc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:soap11env="http://schemas.xmlsoap.org/soap/envelope/" xmlns:soap12env="http://www.w3.org/2003/05/soap-envelope" xmlns:soap12enc="http://www.w3.org/2003/05/soap-encoding" xmlns:wsa="http://schemas.xmlsoap.org/ws/2003/03/addressing" xmlns:xop="http://www.w3.org/2004/08/xop/include" xmlns:http="http://schemas.xmlsoap.org/wsdl/http/" xmlns:tns="spyne.examples.hello/types" xmlns:s0="spyne.examples.hello" targetNamespace="spyne.examples.hello/types" name="Application"> <wsdl:types> <xs:schema targetNamespace="spyne.examples.hello/types" elementFormDefault="qualified"> <xs:import namespace="spyne.examples.hello" /> <xs:complexType name="say_helloResponse"> <xs:sequence> <xs:element name="say_helloResult" type="xs:string" minOccurs="0" nillable="true" /> </xs:sequence> </xs:complexType> <xs:complexType name="say_hello"> <xs:sequence> <xs:element name="IdType" type="s0:IdType" minOccurs="0" nillable="true" /> <xs:element name="times" type="xs:integer" minOccurs="0" … -
Django - Pathing Issue (I think!)
I've created a restuarant booking system using Django. Trying to achieve full Crud functionality. Just trying to sort out the update and delete. So basically when i open the user account it comes up with the reservations they've made and the option to edit or Delete them. Where my issue is is when i have my url paths as follows: urlpatterns = [ path('', views.ReservationsFormView.as_view(), name='reservations'), path('edit/<slug:pk>/', EditReservationView.as_view(), name="edit_reservation"), path('view/<slug:pk>/', ReservationCompleteView.as_view(), name="reservation_complete"), path('reservations_account/', ReservationAccountView.as_view(), name="reservations_account"), path('delete/<slug:pk>/', DeleteReservationView.as_view(), name="delete_reservation"), ] It won't load the account screen as it says: error screen 1 and when I change my paths to as follows: urlpatterns = [ path('', views.ReservationsFormView.as_view(), name='reservations'), path('edit_reservation', EditReservationView.as_view(), name="edit_reservation"), path('view_reservation/', ReservationCompleteView.as_view(), name="reservation_complete"), path('reservations_account/', ReservationAccountView.as_view(), name="reservations_account"), path('delete_reservation/', DeleteReservationView.as_view(), name="delete_reservation"), ] It does load the account screen but when i hit the Edit or Delete button i get the following: error screen 2 Relatively new to Django so any help is grealy appreciated. Thanks in adance -
RuntimeError: Model class mainpage_authentication.models.User doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS
Before applying models to my project everything was okay. But when I just applied them, the system crushed. I'm a freshmen learning Django, so will be grateful for an explanation, and a solution, if possible. My code: admin.py from django.contrib import admin from .models import User admin.site.register(User) apps.py from django.apps import AppConfig class AuthenticationPageConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'mainpage_authentication' forms.py from django import forms from .models import User class AuthenticationLoginForm(forms.Form): class Meta: model = User fields = ['username', 'password'] models.py from django.db import models class User(models.Model): username = models.CharField(max_length=100) password = models.CharField(max_length=100) settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'mainpage_authentication', ] views.py from django.shortcuts import render from django import views from mainpage_authentication.forms import AuthenticationLoginForm class MainPageView(views.View): def get(self, request): return render(request, 'mainpage.html') class AuthenticationLoginPageView(views.View): def get(self, request): form: AuthenticationLoginForm = AuthenticationLoginForm() return render(request, 'authentication-page.html', {"form": form}) -
how to upload all type of file to cloudinary using django with filefield
hello guys i want to upload all type of file to cloudinary this is my model i don't want to upload a specific kind of file but all type pleaze help me class post(models.Model): titre=models.CharField(unique=True,null=True,max_length=100) description=models.TextField(null=True,blank=True,max_length=400) T=models.CharField(default="image",blank=True,max_length=50) image=models.FileField(null=True) cat=models.ForeignKey(categorie,on_delete=models.CASCADE,null=True) datepost=models.DateTimeField(auto_now_add=True,blank=True) user=models.ForeignKey(myuser,on_delete=models.CASCADE,null=True) vue=models.IntegerField(default=0,blank=True) def __str__(self): return self.titre def save(self, *args ,**kwargs): #cette partie permet de generer un identifiant unique f=self.image.read(1000) self.image.seek(0) mime=magic.from_buffer(f,mime=True) if "video" in mime : self.T="short" super(post,self).save(*args,**kwargs) thanks for your helps and sorry for my bad english -
How can i join two prefetch related in Django query
i have to do a django filter with complex form query and i don't have experience with select_related and prefetch_related methods. models.py: class User(models.Model): class Park(models.Model): class Plot(models.Model): owner = models.ForeignKey(get_user_model(), verbose_name=_('Owner'), on_delete=models.SET_NULL, null=True, related_name='plots') park = models.ForeignKey('Park', verbose_name=_('Park'), on_delete=models.SET_NULL, null=True, related_name='plots') class Building(models.Model): plot = models.ForeignKey('Plot', verbose_name=_('Plot'), on_delete=models.SET_NULL, blank=True, null=True, related_name='plot_buildings') owner = models.ForeignKey(get_user_model(), verbose_name=_('Owner'), on_delete=models.SET_NULL, blank=True, null=True, related_name='owner_buildings') tenant = models.ForeignKey(get_user_model(), verbose_name=_('Tenant'), on_delete=models.SET_NULL, blank=True, null=True, related_name='tenant_buildings') I need to get all de user that are owner of a plot or a building or tenant of a building. i have this for now... filters.py: class UserApiFilter(filters.FilterSet): park_id = filters.CharFilter(method='filter_by_park') def filter_by_park(self, queryset, name, value): params = {name: value} result = queryset.prefetch_related(Prefetch('plots', queryset=app_models.Plot.objects.filter(**params))) Anybody could help me please? Thanks in advance. -
AttributeError at /media/.. when requesting file in media folder Django development stage
When I am reqeuesting media files (.png in this case) in the media folder in development I get this error: AttributeError at /media/test.png This FileResponse instance has no content attribute. Use streaming_content instead. Request: http://localhost:8000/media/test.png I added below to the url patterns: urlpatterns += staticfiles_urlpatterns() urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) And below to the settings: STATIC_ROOT = BASE_DIR / 'static' STATIC_URL = '/static/' MEDIA_ROOT = BASE_DIR / 'media' MEDIA_URL = '/media/' Static files are working just fine. What do I overlook? Thanks! -
Django How to display either an image or pdf
I have a model with file upload field where users can upload either an image or a pdf. What is the best way to display the upload in a template when it can be either an image or a pdf. I have seen a fairly complex ajax based solution. Is there a better way? -
django error: The value of 'ordering[0]' refers to 'username', which is not an attribute of 'accounts.clinic_staff'
I extended my accounts custom user model using a one-to-one field and it worked fine. But when I tried customizing it to display more info such as the staff_number and location, the following error is returned: <class 'accounts.admin.staffAdmin'>: (admin.E033) The value of 'ordering[0]' refers to 'username', which is not an attribute of 'accounts.clinic_staff'. the staffAdmin class doesn't have username listed as a list_display and the clinic_staff is just returning the username. I'm stuck on what to do? this is my accounts>models.py code: from datetime import date import email import imp from pyexpat import model from tkinter import CASCADE from tkinter.tix import Tree from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager class MyAccountManager(BaseUserManager): def create_user(self, email, username, password=None,): if not email: raise ValueError('Email address is required') if not username: raise ValueError('Username is required') user = self.model( email=self.normalize_email(email), username = username, ) user.set_password(password) user.save(using = self.db) return user def create_superuser(self, email, username, password): user = self.create_user( email=self.normalize_email(email), password = password, username = username, ) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using = self.db) return user class Account(AbstractBaseUser): email = models.EmailField(verbose_name="email", max_length=60, unique=True) username = models.CharField(max_length=30, unique=True) date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True) last_login = models.DateTimeField(verbose_name='last login', auto_now=True) is_admin = … -
How can I migrate my existent sqlite db to postgres on heroku?
I deployed my django app on heroku and I can't see my database on the site(users, posts..). If i create a new superuser(couldn't log in with my old superuser so I had to create another one) or any other user, content disappears after some time.. Correct me if I'm wrong I thought heroku converts that for me automatically when I deploy my app, anything I missed? And I did migrate from the heroku CLI Setting: import os import django_heroku from decouple import config # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = secretkey # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ["network50web.herokuapp.com"] # Application definition INSTALLED_APPS = [ 'crispy_forms', 'network', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', 'import_export' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', ] ROOT_URLCONF = 'project4.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': (BASE_DIR, 'network/templates'), 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'project4.wsgi.application' # Database # https://docs.djangoproject.com/en/3.0/ref/settings/#databases … -
Passing multiple parameters to django url template
I am trying to pass multiple url parameters from a django templated to be used by a view function. Below are my codes : A snippet from the template from where the parameters will be passed onto : <a href="{% url 'coordinator_assign_project_recommendations' group_id=row.group client_id=row.client project_id=row.project_id %}" class="btn btn-primary">Assign</a> The view function : def assign_recommended_project(request, group_id, client_id, project_id): group = StudentGroup.objects.get(id=group_id) group.client = client_id group.project = project_id group.save() project = Project.objects.get(id=project_id) project.is_assigned = True project.save() return redirect("coordinator_view_groups") The url of the view function : path( "coordinator/assign_recommended_project/<str:group_id/str:client_id/str:project_id", assign_recommended_project, name="coordinator_assign_project_recommendations", ), This is the error that is shown : Can someone please help me solve this. Thanks. -
NoReverseMatch at when calling url
I can't work out why im getting this error NoReverseMatch at / when calling <a href="{% url 'show_token_details' token.id %}"> def show_token_details(request,token_id): token = Token.objects.get(token_id == token_id) return render(request, 'ecommerceproductdetails.html', {}) path("token/<int:token_id>", views.show_token_details, name='show_token_details'), What am I missing here? Thanks -
How can I pass in the login/register data for my django-rest api in the form of a url?
I am following along with a book on the django-rest framework and I am having issues grasping a certain concept. The book uses the built-in Browsable API feature to do basic CRUD and LOGIN/LOGOUT/REGISTRATION functionality. What it fails to mention is how I can achieve such functionality using only the URL, which would be needed for, say connecting the API to the frontend of a REACT app. Example: I have an API which displays Posts and this path shows all posts: path('api/v1/', include('posts.urls')), I want to use this path for example, to register. path('dj-rest-auth/registration/', include('dj_rest_auth.registration.urls')), How would the URL look like ? -
Why are my images not showing at the index page?
I am trying to create an auction website where the users can input an image url and bid on the entries. The issue I am currently having is that my images are not reflecting on my index page except I hard code it. I'm not sure what I am doing wrong as I have tried using different options such as using an imageField and trying to convert the URL to an image(This didn't work) and I have tried tweaking the codes but still having the same issue. Please assist a newbie URL.PY path("create/", views.create_listing, name="create_listing"), MODELS.PY class Auction(models.Model): ABSTRACT = 'AB' MODERN = 'MN' ILLUSTRATION = 'IN' select_category = [ ('ABSTRACT', 'Abstract'), ('MODERN', 'Modern'), ('ILLUSTRATION', 'Illustration') ] title = models.CharField(max_length=25) description = models.TextField() current_bid = models.IntegerField(null=False, blank=False) # image_upload = models.ImageField(upload_to='images/') image_url = models.URLField(verbose_name="URL", max_length=255, unique=True, null=True, blank=True) category = models.CharField( choices=select_category, max_length=12, default=MODERN, ) created_at = models.DateTimeField(auto_now_add=True) FORMS.PY class AuctionForm(forms.ModelForm): class Meta: model = Auction fields = ['title', 'description', 'current_bid', 'image_url', 'category'] VIEWS.PY def create_listing(request): form = AuctionForm() user = request.user if request.method == 'POST': form = AuctionForm(request.POST, request.FILES) images = Auction.objects.get('image_url') if form.is_valid: context = { 'user': user, 'images': images } form.save() return redirect('index', context) else: form = … -
Symmetrical link between two objects in Django
I have a model with all the info of a plant and another model which consists of creating links between these plants. But when I create a link between two plants for example I create an ideal link between basil and garlic in the Django admin, I don't have the symmetrical link between garlic and basil. Should we add symmetrical = true in the model? Here is Plant model : from django.db import models class Plant(models.Model): class LEVEL(models.TextChoices): NONE = None EASY = 'easy', MEDIUM = 'medium', HARD = 'hard' class SUNSHINE(models.TextChoices): NONE = None FULL_SUN = 'full_sun', SHADOW = 'shadow', SUNNY = 'sunny', MODERATE = 'moderate' class IRRIGATION(models.TextChoices): NONE = None WET = 'wet', WEAKLY = 'weakly', MOIST = 'keep_soil_moist', GENEROUSLY = 'generously', SLIGHTLY_DAMP = 'slightly_damp', COVERED_WITH_WATER = 'covered_with_water' class SOIL_N(models.TextChoices): NONE = None HUMUS = 'humus', LIGHT = 'light', CLAY = 'clay', DRAINED = 'drained', ALL_TYPE = 'all_types' class SOIL_T(models.TextChoices): NONE = None POOR = 'poor', MEDIUM_SOIL = 'medium_soil', RICH = 'rich', FERTILE = 'fertile', DRAINED = 'drained', ADD_PEBBLES = 'add_pebbles', ALL_TYPE = 'all_types' class HARDINESS(models.TextChoices): NONE = None VERY_FRAGILE = 'very_fragile', FRAGILE = 'fragile', RUSTIC = 'rustic', MEDIUM = 'medium', SUPPORT_FRESHNESS = 'support_freshness', # COLD_RESISTANT = 'cold_resistant' … -
HTML show image if it exists and show nothing if it doesn't
I need to display an image on my HTML page but only if it exists in my directory. If it doesn't, then show nothing. How can I write a function that checks if the image exists, then if yes, display it if no, don't show anything? I am using django as a back end. -
Django channels Disconect after closing the tab
I'm new to Django channels and I'm building a simple chatroom. With this chatroom, I want to disconnect a user if he closes the browser tab and if he reopens the tab with the same link, I want to reconnect him to the same chat that he was. How can I do that?