Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Use Django ORM to take values from field that have some Set of values in enother field
How to get bellow by using django ORM myset = {2, 3} I need names from field 'name' that have '2'&'3' only in 'value' field: Table in DB (model.Mytable) 'name'|'value' -------------- 'Ann' |'2' 'Ann' |'3' 'Ann' |'5' 'John'|'2' 'John'|'3' 'Jim' |'3' 'Jim' |'2' 'Pit' |'7' 'Pit' |'8' Needed output: ['John', 'Jim'] # value '2','3' only So, I try to get construction like: QuerySet [('Ann', ['2','3','5']), ('John', ['2', '3']), ... using .annotatte(), .values() But i don't know how get it using Django ORM. Or i can use some filterin .filters()? -
Django allauth error. what can i do for this error
django.core.exceptions.ImproperlyConfigured: Application labels aren't unique, duplicates: account and then when i define app_label give me that error: django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'account.User' that has not been installed how can i fix it -
How to auto arrange height width media file inside HTML?
I have multiple files contain photo and video also. I want the file to auto adjust without creating the list of files and show a proper display with proper adjustment like facebook or instagram. I would be grateful for any help. HTML <div class="col-lg-12" id="post-box"> {% for object in newss %} <div class="hpanel blog-box"> <div class="panel-heading"> <div class="media clearfix"> <a class="pull-left"> <img src="{{ object.author.profile.image.url }}" alt="profile-picture"> </a> </div> </div> <div class="panel-image" id="media-output"> {% for i in object.filemodel_set.all %} {% if ".jpeg" in i.file.url or ".jpg" in i.file.url or ".png" in i.file.url %} <img src="{{i.file.url}}" alt="article" class="img-responsive card-img-top"> {% endif %} {% if ".mp4" in i.file.url or ".mpeg" in i.file.url or ".mov" in i.file.url %} <video class="afterglow" id="myvideo" width="1280" height="720" data-volume=".5"> <source type="video/mp4" src="{{i.file.url}}#t=0.9" /> </video> {% endif %} {% endfor %} </div> <div class="panel-body"> <div class="title"> <a href="{% url 'news-detail' pk=object.pk %}"> <h4>{{ object.title|slice:":100" }}</h4> </a> </div> </div> </div> {% endfor %} </div> -
How to embed img from external hosting in Django Template?
I am trying to use Gdrive image url in django template Django Template <li class="post"><a href="{{post.href}}"><img src="{{post.src}}" alt="{{post.alt}}" width=auto height="300px"><h4>{{post.name}}</h4></a></li> Django Model from django.db import models class Post(models.Model): catname = models.CharField(max_length=15) href = models.CharField(max_length=100) scr = models.CharField(max_length=100) alt = models.CharField(max_length=100) name = models.CharField(max_length=100) But actual url of scr is scr="https://drive.google.com/uc?id=xyz" There is a error in loading in image from external source (gdrive img link) <img src(unknown) alt="#img3" width="auto" height="300px"> How to pass a external img url as src url in Django -
How to remove username field and password2 field from RegisterSerializer in django rest framework?
When I call the api/seller/register api, the fields appear are username, password1 and password2. I want these removed and only want simple password, email and phone_num. How to remove this? I am trying to make a seller registration using RegisterSerializer. I tried with ModelSerailzers and provided fields as I want but this will lead to me the error saying save() only takes 1 argument.So, I just want these unnecessary fields removed using RegisterSerializer. My model: class CustomUserManager(BaseUserManager): """ Custom user model manager with email as the unique identifier """ def create_user(self, first_name, last_name, email, password, **extra_fields): """ Create user with the given email and password. """ if not email: raise ValueError("The email must be set") first_name = first_name.capitalize() last_name = last_name.capitalize() email = self.normalize_email(email) user = self.model( first_name=first_name, last_name=last_name, email=email, **extra_fields ) user.set_password(password) user.save() return user def create_superuser(self, first_name, last_name, email, password, **extra_fields): """ Create superuser with the given email and password. """ extra_fields.setdefault("is_staff", True) extra_fields.setdefault("is_superuser", True) extra_fields.setdefault("is_active", True) if extra_fields.get("is_staff") is not True: raise ValueError("Superuser must have is_staff=True.") if extra_fields.get("is_superuser") is not True: raise ValueError("Superuser must have is_superuser=True.") return self.create_user(first_name, last_name, email, password, **extra_fields) class CustomUser(AbstractUser): username = models.CharField(max_length=255,blank=False) first_name = models.CharField(max_length=255, verbose_name="First name") last_name = models.CharField(max_length=255, verbose_name="Last name") … -
<li><a href="{% url 'detail' question.id %}">{{ question.question_text }}</a></li> not working
I tried this code : <li><a href="{% url 'detail' question.id %}">{{ question.question_text }}</a></li> and it gives me an error -
How to find by ObjectId Django, MongoDB
How to find by ObjectId (id field) record = Record.objects.filter(_id=id).first() -> None record = Record.objects.get(_id=id) -> Error DoesNotExists -
How do I get the first Item from this get?
Hi I'm trying to get the first item of a Django Model. How can I get it? I'm looking for the object with the same customer name as the customer (I'm building a webshop btw). Here is my model: class MessageItem(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True) mItem = models.CharField(max_length=255, null=True) mQuantity = models.CharField(max_length=255, null=True) mOrderItem = models.CharField(max_length=255, null=True) Here is the create function: createModel = MessageItem for item in items: createModel.objects.create(customer=customer, mItem=item.product.name, mQuantity=str(item.quantity), mOrderItem=str(items)) And here is the Get function: orderMessage = MessageItem.objects.get(customer=customer) message_to_send = str(message) + " " + orderMessage Thanks for the Help! -
SCORM from chamilo Platform
I´m developing and e-learning platform in Django based on Chamilo LMS services and databases. Currently I´m facing a problem with course content because of cookies (I think is that). The data extracting using the api is used to fill an url with parameters to be passed on PHP file but in the iFrame nothing is shown, only shows a login form. -
CartItem matching query does not exist django
So i'm trying to remove an item from cart when user checkouts, When i click on checkout I get CartItem matching query does not exist. error. I'm using makeorder function as getting request and createorder function for creating an order. views.py from django.shortcuts import render, redirect from django.contrib.auth.forms import UserCreationForm, AuthenticationForm from django.contrib.auth.models import User from django.contrib.auth import login, logout, authenticate from django.db import IntegrityError from .models import Book, CartItem, OrderItem from django.contrib.auth.decorators import login_required from .forms import BookForm from django.core.exceptions import ObjectDoesNotExist # Create your views here. removederror = '' def calculate(request): oof = CartItem.objects.filter(user=request.user) fianlprice = 0 for item in oof: fianlprice += item.book.price def signupuser(request): if request.user.is_authenticated: return render(request, 'main/alreadyloggedin.html') elif request.user != request.user.is_authenticated: if request.method == "GET": return render(request, 'main/signupuser.html', {'form':UserCreationForm()}) elif request.method == "POST": if request.POST['password1'] == request.POST['password2']: try: user = User.objects.create_user(request.POST['username'], password=request.POST['password1']) user.save() login(request, user) return render(request, 'main/UserCreated.html') except IntegrityError: return render(request, 'main/signupuser.html', {'form':UserCreationForm(), 'error':'That username has already been taken. Please choose a new username'}) else: return render(request, 'main/signupuser.html', {'form':UserCreationForm(), 'error':'Passwords did not match'}) def signinuser(request): if request.user.is_authenticated: return render(request, 'main/alreadyloggedin.html', {'error':'You are already logged in'}) elif request.user != request.user.is_authenticated: if request.method == "GET": return render(request, 'main/signinuser.html', {'form':AuthenticationForm()}) elif request.method == "POST": user = … -
custom role based login in Django
I am working on a project in Django 3.1.2 I have created customer and admin site separately, but the designer has some functionalities to modify some files, and entries in database from admin side, you can consider designer as staff. I can use @login_required validator to restrict unauthenticated user to access the pages, but I also want to make stop the designer to use all the functionalities of the admin site pages which admin can do, so I have taken a field role in user table so that I can easily identify the type of user, but don't know how to use is to create it in login so that I don't have to check in every view for the user role. My user models is as shown below : models.py class User(AbstractUser): GENDER = ( (True, 'Male'), (False, 'Female'), ) USER_TYPE = ( ('Admin', 'Admin'), ('Designer', 'Designer'), ('Customer', 'Customer'), ) user_id = models.AutoField("User ID", primary_key=True, auto_created=True) avatar = models.ImageField("User Avatar", null=True, blank=True) gender = models.BooleanField("Gender", choices=GENDER, default=True) role = models.CharField("User Type", max_length=10, choices=USER_TYPE, default='Customer') now here I want a function that will identify the user's role and according to role it redirects to the desired page and access contenet … -
Error "No Models matches the given query" after using get_next_by_FOO django
When using get_next_by_Foo, it doesnt show content in template file. I get data from this query: request.session['contract_posts_search'] is results I get from filtering in another view. def contract_detail_test(request, contract_id=None): context = {} contract_posts_search=request.session['contract_posts_search'] contract_filtered=[] for i in range(len(contract_posts_search)): contract_filtered.append(contract_posts_search[i]["fields"]["contract"]) contract_posts_search= Contracts.objects.filter(contract__in=contract_filtered).distinct() contract_posts = get_object_or_404(contract_posts_search, contract=contract_id) After having contract_post, I use get_next_by_created_at: if contract_posts is not None: print(contract_posts) try: the_next = contract_posts.get_next_by_created_at() except: the_next=None try: the_prev = contract_posts.get_previous_by_created_at() except: the_prev=None context = { "contract_posts": contract_posts, "the_next" : the_next, "the_prev": the_prev, } return render(request, "contract_detail_test.html", context) For example: I filter contract contain "2016" and get 10 results, using request_session in another view, I can print out 10 results. Then I use get_next_by_created_at, It will show first result correctly, but after clicking, it will show this error. There is no contract number 20170709-0010161 in contract_posts Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/contract_detail_test/20170709-0010161/ Raised by: test_upload_filter.views.contract_detail_test No Contracts matches the given query. -
Django Admin custom field in list_editable without fk
i have models class Supplier_items(models.Model): si_name = models.CharField(max_length=200, blank=True, null= True, verbose_name='Название поставщика') si_url = models.CharField(max_length=200, blank=True, null= True, verbose_name='URL поставщика') si_ean = models.CharField(max_length=200, blank=True, null= True) si_price = models.FloatField( blank=True, null= True, verbose_name='Price') def __str__(self): return self.si_name class Order(models.Model): order_id = models.CharField(max_length=50, blank=True, null= True) shop = models.CharField(max_length=50, blank=True, null= True) created = models.DateTimeField('Дата добавления', default=timezone.now) price = models.CharField(max_length=50, blank=True, null= True) price_real = models.CharField(max_length=50, blank=True, null= True) order_ean = models.CharField(max_length=100, blank=True, null= True) variant = models.CharField(max_length=50, blank=True, null= True) def __str__(self): return self.item_name def variant(self, *args, **kwargs): queryset = Supplier_items.objects.filter(si_ean__contains = self.order_ean) return queryset there is no way to link by key in list_display it shows how the text is normal, list_editable - gives an error (admin.E121) The value of list_editable [0]' refers to 'variant' I want to output the variant field in admin as a select field and write the selection to the corresponding field in the model. thanks for the help -
Django serializers nested data reformat
I have a three model course_category,course and sub_course which have Foreign key relationship between them serially. I am using DRF serializer to pull a nested data where i want a course_category as my first parent and course as second and subcourse as child but it is totally opposite while i use prefetch_related(). class course_categories(models.Model): deleted_flag = [('y', 'yes'), ('n', 'no')] category_name = models.CharField(max_length=50, unique=True) created_by = models.CharField(max_length=50) created_date = models.DateTimeField(auto_now_add=True) modified_by = models.CharField(max_length=50, blank=True, null=True) modified_date = models.DateTimeField( auto_now_add=False, blank=True, null=True) is_deleted_flag = models.CharField( max_length=1, choices=deleted_flag, default='n') def __str__(self): return self.category_name class courses(models.Model): deleted_flag = [('y', 'yes'), ('n', 'no')] course_name = models.CharField(max_length=70) course_categories = models.ForeignKey( 'course_categories', on_delete=models.CASCADE) created_by = models.CharField(max_length=50) created_date = models.DateTimeField(auto_now_add=True) modified_by = models.CharField(max_length=50, blank=True, null=True) modified_date = models.DateTimeField( auto_now_add=False, blank=True, null=True) is_deleted_flag = models.CharField( max_length=1, choices=deleted_flag, default='n') def __str__(self): return self.course_name class subcourse(models.Model): deleted_flag = [('y', 'yes'), ('n', 'no')] subcourse_name = models.CharField(max_length=50, unique=True) courses = models.ForeignKey( 'courses', related_name="subcourse", on_delete=models.CASCADE) subcourse_short_description = models.CharField(max_length=150, blank=True) created_by = models.CharField(max_length=50) created_date = models.DateTimeField(auto_now_add=True) modified_by = models.CharField(max_length=50, blank=True, null=True) modified_date = models.DateTimeField( auto_now_add=False, blank=True, null=True) is_deleted_flag = models.CharField( max_length=1, choices=deleted_flag, default='n') here is my models.py and serializers here class CourseSerializerView(serializers.ModelSerializer): # subcourse = SubcourseSerializerView() class Meta: model = courses fields = ('__all__') … -
Are Django and node.js can be implemented in same project?
Can I use both Django and node.js in the same application? if it is yes, How?👏 Some say Redis can be good for the implementation. But I did not understand how it can be implemented? -
"127.0.0.1:8000 says Url failed with 404 /ad/1/favorite/" not able to favorite/unfavourite [closed]
I think this issue might be trivial, but, can someone please suggest to me an alternative for this code I did change the structure and wrote it as : I pretty much just changed the way the URL was written, and when I ran my code on localhost and clicked on the star, this is what I get...a prompt saying: 127.0.0.1:8000 says Url failed with 404 /ad/1/favorite/ Kindly tell me, is there anything wrong I'm doing? I'm sure the mistake is somewhere here, but, if not I can also upload code from the views.py and urls.py files... -
Django Best method to create different users
I am creating a School Management System where there should be 3 types of users (Student, Teacher, Authorities). Can anyone please help me in giving me a direction to proceed since I'm stuck in this. -
Why allauth EmailAddress matching query does not exist?
I am using dj-rest-auth packages for auth functionality for apis in my project. But with login endpoint I am getting this error. allauth.account.models.EmailAddress.DoesNotExist: EmailAddress matching query does not exist. When the user who get registered from the web can't login from api endpoint.Do I have to register the email into the allauth Emailaddress Table also if user gets created from web like this. django views def save_user(request): user = form.save() # then create this user email in all auth EmailAddress table ? EmailAddress.objects.create(email=user.email..) ?? rest settings ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_EMAIL_VERIFICATION = "mandatory" ACCOUNT_EMAIL_CONFIRMATION_EXPIRE_DAYS = 1 ACCOUNT_AUTHENTICATION_METHOD = "username" OR is there any settings available so that any active users from the system can login through api endpoint ? -
SMTPAuthenticationError on apache but not in the standard server. DJANGO and Apache2
When I am doing python manage.py runsever 0.0.0.0:8000 Everything is working correctly. I am just using django server by MY_ADRESS_IP:8000 When I am using apache2 on the Centos 7 I have an error when I want to send an email. My settings: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_USE_TLS = True EMAIL_PORT = 587 EMAIL_HOST_USER = 'MY_EMAIL_NAME' EMAIL_HOST_PASSWORD = 'MY_EMAIL_PASS' Do I need some special config in apache to let the gmail send emails? Here more error details: Django Version: 3.1.3 Python Version: 3.6.8 Installed Applications: ['sf_platform.apps.SfSplatformConfig', 'sf_users.apps.SfUsersConfig', 'sf_api.apps.SfApiConfig', 'crispy_forms', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed 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'] Traceback (most recent call last): File "/home/user_name/WEB-Platform/venv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/user_name/WEB-Platform/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/user_name/WEB-Platform/venv/lib/python3.6/site-packages/django/views/generic/base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "/home/user_name/WEB-Platform/venv/lib/python3.6/site-packages/django/utils/decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "/home/user_name/WEB-Platform/venv/lib/python3.6/site-packages/django/utils/decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "/home/user_name/WEB-Platform/venv/lib/python3.6/site-packages/django/contrib/auth/views.py", line 222, in dispatch return super().dispatch(*args, **kwargs) File "/home/user_name/WEB-Platform/venv/lib/python3.6/site-packages/django/views/generic/base.py", line 98, in dispatch return handler(request, *args, **kwargs) File "/home/user_name/WEB-Platform/venv/lib/python3.6/site-packages/django/views/generic/edit.py", line 142, in post return self.form_valid(form) File "/home/user_name/WEB-Platform/venv/lib/python3.6/site-packages/django/contrib/auth/views.py", line 235, in form_valid form.save(**opts) File "/home/user_name/WEB-Platform/venv/lib/python3.6/site-packages/django/contrib/auth/forms.py", line 325, in save … -
Web application could not be started by the Phusion Passenger application server, ModuleNotFoundError - Django [SOLVED]
when I install a third-site application from github with pip install -e git+https://github.com/breduin/das.git#egg=django_ajax_selects my site doesn't start and the following error raises: Web application could not be started by the Phusion Passenger application server. /usr/share/passenger/helper-scripts/wsgi-loader.py:26: DeprecationWarning: the imp module is deprecated in favour of importlib; see the module's documentation for alternative uses import sys, os, re, imp, threading, signal, traceback, socket, select, struct, logging, errno Traceback (most recent call last): File "/usr/share/passenger/helper-scripts/wsgi-loader.py", line 369, in <module> app_module = load_app() File "/usr/share/passenger/helper-scripts/wsgi-loader.py", line 76, in load_app return imp.load_source('passenger_wsgi', startup_file) File "/opt/python/python-3.8.6/lib/python3.8/imp.py", line 171, in load_source module = _load(spec) File "<frozen importlib._bootstrap>", line 702, in _load File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/var/www/u1234567/data/www/mysite/passenger_wsgi.py", line 7, in <module> application = get_wsgi_application() File "/var/www/u1234567/data/env/lib/python3.8/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application django.setup(set_prefix=False) File "/var/www/u1234567/data/env/lib/python3.8/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/var/www/u1234567/data/env/lib/python3.8/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/var/www/u1234567/data/env/lib/python3.8/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/opt/python/python-3.8.6/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked ModuleNotFoundError: No module … -
Is there a way to preserve the original HTTP_REFERER when using Django's redirect?
I have a Django site and I'm using Google Analytics to keep track of where my traffic is coming from. I want to route traffic to various places depending on whether the user is signed in, or has done other stuff. So in my views.py, I have a function like this: def toDefaultLandingPage(request): # tell me who the referrer is # this is what I want to pass along in the request if I can print(request.META.get('HTTP_REFERER')) if request.user.is_authenticated: try: configuration = UserData.objects.get(user=request.user) return redirect('/home/') except: # user has not configured their profile yet return redirect('/user/') else: # promo page for non-logged in users return redirect('/about/') This works great, except that Google Analytics says that most of my traffic has no referrer. I know this is a lie, because the print statement in default landing page has either google or facebook in it about 70% of the time. Is there any way to pass the original referrer to the 3 different redirects I use? -
Replacing old file with a new file throws FileNotFound error Django
When I try to replace/upload a new image it calls the function delete_files_when_file_changed but it throws a FIleNotFound error. # Create your models here. def upload_to(instance, filename): now = timezone_now() base, extension = os.path.splitext(filename) extension = extension.lower() name = base + "_" + number_generator(3) instance = instance.shop_name + "_" + name return f"seller/{now:%Y/%m}/{instance}{extension}" """ Only delete the file if no other instances of that model are using it""" def delete_file_if_unused(model,instance,field,instance_file_field): dynamic_field = {} dynamic_field[field.name] = instance_file_field.name other_refs_exist = model.objects.filter(**dynamic_field).exclude(pk=instance.pk).exists() print("OTHER",other_refs_exist) if not other_refs_exist: instance_file_field.delete(False) class Seller(UrlBase): user = models.OneToOneField( User, related_name="sellers", on_delete=models.CASCADE ) token = models.UUIDField(max_length=36, unique=True, blank=True, primary_key=True) shop_name = models.CharField(max_length=256, blank=True, null=True) address_line_1 = models.CharField(max_length=255, blank=True) address_line_2 = models.CharField(max_length=255, blank=True) state = models.CharField(max_length=128, blank=True) city_village = models.CharField(max_length=255, blank=True) postal_code = models.CharField(max_length=20, blank=True) image = VersatileImageField(upload_to=upload_to, ppoi_field="ppoi", blank=True, null=True) ppoi = PPOIField() hero_image = VersatileImageField(upload_to=upload_to, ppoi_field="hero_image_ppoi", blank=True, null=True) hero_image_ppoi = PPOIField() banner_image_1 = VersatileImageField(upload_to=upload_to, ppoi_field="banner_ppoi_1", blank=True, null=True) banner_ppoi_1 = PPOIField() banner_image_2 = VersatileImageField(upload_to=upload_to, ppoi_field="banner_ppoi_2", blank=True, null=True) banner_ppoi_2 = PPOIField() lookup = models.CharField(max_length=120, blank=True, null=True, unique=True) is_verified = models.BooleanField(default=False) is_featured = models.BooleanField(default=False) def __str__(self): return str(self.user) def save(self, *args, **kwargs) -> None: if not self.token: self.token = str(uuid4()) if not self.lookup: self.lookup = ((self.user.first_name + self.user.last_name + self.shop_name).replace(" ", "_")).lower() … -
I am using django for a project and i got this error
I am doing a project in Django and i got this error.How is this occurs? NoReverseMatch at / Reverse for 'create_order' with no arguments not found. 1 pattern(s) tried: ['create_order/(?P[^/]+)/$'] urls.py from django.urls import path from accounts import views urlpatterns = [ path('',views.home, name="home"), path('product/',views.products, name="product"), path('customer/<str:pkid>/',views.customer, name="customer"), path('create_order/<str:pk>/',views.createOrder, name="create_order"), path('update_order/<str:pk>/',views.updateOrder, name="update_order"), path('delete_order/<str:pk>/',views.deleteOrder, name="delete_order"), ] views.py def createOrder(request, pk): customer = Customer.objects.get(id=pk) form = OrderForm(initial={'customer':customer}) if request.method == 'POST': form = OrderForm(request.POST) if form.is_valid: form.save() return redirect('/') context = {'form':form} return render(request, 'accounts/order_form.html', context) order_form.html {% extends 'accounts/main.html' %} {% load static %} {% block content %} <form action="" method="POST"> {% csrf_token %} {{ form }} <input type="submit" name="Submit"> </form> {% endblock %} -
Where can I store the refresh and access token in django
I'm using django and trying to integrate it with quickbooks online through python-quickbooks package and already did so and it works fine, but the problem is I don't want to store the tokens in the request session because I'm trying to access them outside the views, to be exact I'm trying to send an invoice each time an invoice(invoice model from django) object was made I want to send one to quickbooks and I'm doing this through django signals but I can't access the session from the signals so where is the best place to store them on the server side? thanks in advance. -
Can't find static image. Trying to use a tag in a html for loop
so I was trying to use a webp image converter and the template usage is very simple, the example says: <img src="{% static_webp 'img/hello.jpg' %}">` Ok now my problem is that I show my images using a for like this {% for product_object in products_slider %} <div class="banner banner-1"> <img src="{{ product.image.url }}"> </div>{% endfor %} My question is how I can use te static_webp tag and pass the image url of every product on the for?? I tried this but it didn't work :( <img src="{% static_webp 'media/{{ product.image }}'%}"> <!--FAIL-->