Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Where can I add form control in my html when loading a registration form and iterating over that form?
So I'm loading my registration form into my html and then using a for loop to iterate over those fields. I am wondering where I can add form control to show a green box around my username field so that a user knows if a username is taken before hitting the submit button. I tried adding it to the form tag and setting a div tag around {{field}} but neither of those work. Furthermore, how can I make it ONLY for Username? registration.html {% block content %} <br> <h1 class="text-center" style="color:#f5387ae6">Register to fall in love today!</h1> <form method="post" style="width:700px;margin:auto" action="{% url 'dating_app:register' %}" enctype="multipart/form-data" class= "form" > {% bootstrap_form registration_form%} {% csrf_token %} {% for field in bootstrap_form %} <p> <div class="form-control is-valid"> {{field.label_tag}} {{field}} </div> {% if field.help_text %} <small style="color:grey;">{{field.help_text}}</small> {% endif %} {% for error in field.errors %} <p style="color: red;">{{error}}"</p> {% endfor %} </p> {% endfor %} <div class="form-check"> <input type="checkbox" id="accept-terms" class="form-check-input"> <label for="accept-terms" class="form-check-label">Accept Terms &amp; Conditions</label> </div> <div> <br> <button type="submit">Register</button> </div> </form> {% endblock content %} reg_form class RegistrationForm(UserCreationForm): class Meta: model = Profile fields = ("username","email","description","photo","password1","password2") -
i am begginer in django ,
Q1-> I don't know why "GroupMember" model is not showing in admin panel. Q2-> why "members = models.ManyToManyField(User,through="GroupMember")" field is also not showing in admin panel from django.conf import settings from django.core.urlresolvers import reverse from django.db import models from django.utils.text import slugify # from accounts.models import User import misaka from django.contrib.auth import get_user_model User = get_user_model() from django import template register = template.Library() class Group(models.Model): name = models.CharField(max_length=255, unique=True) slug = models.SlugField(allow_unicode=True, unique=True) description = models.TextField(blank=True, default='') description_html = models.TextField(editable=False, default='', blank=True) members = models.ManyToManyField(User,through="GroupMember") def __str__(self): return self.name def save(self, *args, **kwargs): self.slug = slugify(self.name) self.description_html = misaka.html(self.description) super().save(*args, **kwargs) def get_absolute_url(self): return reverse("groups:single", kwargs={"slug": self.slug}) class Meta: ordering = ["name"] class GroupMember(models.Model): group = models.ForeignKey(Group, related_name="memberships") user = models.ForeignKey(User,related_name='user_groups') def __str__(self): return self.user.username class Meta: unique_together = ("group", "user") enter image description here -
Django doesn't let me switch a OneToOneField Relationship between objects
I'm using Django with PostgreSQL, and I'd like to switch a relationship between two objects. The models look something like this (very simplified): class User: group = models.OneToOneField(Group, on_delete=models.SET_NULL, null=True, blank=True, related_name="user") class Group: """ Some fields """ And when I try to do something like this (both of the users have some group set): group1 = # Some query user1 = group1.user user1.group = user_to_update.group user_to_update.group = group1 user1.save(using=db_type, update_fields=['group']) . . . user_to_update.save(using=db_type, update_fields=['group']) It gives me these two errors: psycopg2.errors.UniqueViolation: duplicate key value violates unique constraint "testing_klasen_mains_id_key" & django.db.utils.IntegrityError: duplicate key value violates unique constraint "testing_klasen_mains_id_key" DETAIL: Key (mains_id)=(386) already exists. I've searched around for the error, and describing the situation and all of that, but everything sends me to an error which shows up when trying to migrate. I can't try and destroy the objects and create new ones, because they have other objects which depend on them. If anyone knows what the case may be, it would be of great help! Also if any more detail is needed, feel free to ask! -
how do i make a simple "order" products app like this
I need to make a system for my company, we sell perfumes, in a first stage i only need an app where people can choose between 5 perfumes types, when they chose the type, the have to choose the "family" of the perfume, and then the perfume itself (name of the perfume), and this perfumes have a price so , for example: Perfume for pets (type) - puppys ("family") - citrus (the name of the scent) - 10 usd (price) for understanding how it works, first I want to make a web where i can order the products and they add up in a detailed order where I can see the products, the price, the total, etc, standard stuff, so I need this to add up and store in a form i think. I have created the class and they're like this : from django.db import models class TipoProducto(models.Model): nombre = models.CharField(max_length=20) precio_mayorista = models.IntegerField(default=0) precio_final = models.IntegerField(default=0) def __str__(self): return self.nombre class LineaProducto(models.Model): nombre = models.CharField(max_length=40) def __str__(self): return self.nombre class Productos(models.Model): aroma = models.CharField(max_length=30, null=False, blank=False) tipo = models.ForeignKey(TipoProducto, on_delete=models.CASCADE) linea = models.ForeignKey(LineaProducto, on_delete=models.CASCADE, null=True) def __str__(self): return self.aroma I would really apreciate if someone could help me … -
django/using session variables/how to i pull a value and search the dictionary for that key value pair
sorry if this is a basic question, relatively new to Django. Im creating a table from a list of items. on this table there is a button to set the session variable to one for that part. it looks like this: `<td><center><button type="submit" class="btn btn-secondary"><a href="{% url 'add' things.id %}">Add</a></button></center></td>` where things.id is the primary key of the part. This works but now i want to change the button to a delete button if it has already been added. to do this I need to search the dictionary for the key of things.id. so in my naive mind i would think the code should look like this <td><center> {{request.session.things.id}} </center></td> needless to say it does not work like that. so how do i get the value of things.id such that things.id={value} <td><center> {{request.session.{value}}} </center></td> here is some additional code to help this is the table: {% if all_items %} <table class="table table-bordered table-striped"> <thead> <tr> <th scope="col">Identification Key</th> <th scope="col">Meters</th> <th scope="col">Actions</th> <th scope="col">status</th> </tr> </thead> <tbody> {%for things in all_items%} <tr> <td><center>{{ things.MainKey }}</center></td> <td><center>{{ things.Meters }}</center></td> <td><center><button type="submit" class="btn btn-secondary"><a href="{% url 'add' things.id %}">Add</a></button></center></td> <td><center> {{request.session.1}} </center></td> </tr> {%endfor%} </tbody> {% endif %} </table> and the ad … -
Generating highly customized dynamic PDF file
I have a requirement to generate a report in PDF format. The report is having some graphics (graphs, charts, etc). All of these dynamics - value of graph and charts will change based on the user input. Currently I another similar working thing using https://github.com/incuna/django-wkhtmltopdf. So I am trying to implement this as well using same technology. I am not able to proceed ahead - lot of blockers. Issue is sometime some javascript is not working with wkhtmltopdf, sometime some particular styles are not working, etc etc. For example : This https://codepen.io/umr55766/pen/WNQPVXG is getting converted to pdf correctly. Whereas, this https://codepen.io/umr55766/pen/QWjYeOG is not getting converted correctly. I need help with following this: If this is not the right question for this platform - where should I go ? Am I missing something in wkhtmltopdf ? How can I make it working seamlessly ? Any links, resources, much appreciated! Would you suggested any other tool/tech to generate highly customized PDF ? -
Hi im new to django, i been trying to implement signin/signup application
I been trying to implement a sign-in/signup application. If I had to filter the specific object from the database what parameters I should use for the filter() method? now I have used all() which gives all the objects what if I want the details of the only person who has the account and trying to sign-in and if not tell him to signup. views py from rest_framework import status from rest_framework.decorators import api_view from rest_framework.response import Response from webspaces.models import merchant from webspaces.serializers import merchantSerializer # Create your views here. @api_view(['GET']) def signin(request): try: ex=merchant.objects.all() except merchant.DoesNotExist: return Response("status.HTTP_404_NOT_FOUND sign-up first") if request.method=="GET": serializer=merchantSerializer(ex, many=True) return Response(serializer.data) @api_view(['POST']) def signup(request): if request.method=="POST": serializer=merchantSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.erros, status=status.HTTP_400_BAD_REQUEST) models py class merchant(models.Model): first_name=models.CharField(max_length=10) last_name=models.CharField(max_length=10) email=models.EmailField(max_length=254) password=models.CharField(max_length=10) def __self__(self): return self.email -
using forloop in an image in django
## How to loop through images for a better view ## HI everyone,I am trying to create a photo gallery website which i have the front end worked well because i use material design,for example when you open the website you see 5 parent images in it which if you open each has its own child pictures, but i am getting it wrong because once i open each they show me the same child pictures of all of the pictures posted by me using the django admin i am really in need of this to be solved i have tried all way i can but i am not fortunate enough to get tho i am new to django python below is code ##url.py## urlpatterns = [ path('', views.photos_view, name='photos'), path('<int:id>/', views.pic_detail, name='pic_detail'), path('blog/', views.blog, name='blog'), path('bio/', views.bio, name='bio'), path('quotes/', views.quotes, name='quotes'), path('admin/', admin.site.urls) ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) views.py from django.shortcuts import render, get_object_or_404 from .models import Patios,Patiosimage,Resins,Resinsimage,Tarmac,Tarmacimage,Fencing,Fencingimage,BlockPaving,BlockPavingimage def photos_view(request): patios = Patios.objects.all() resins = Resins.objects.all() tarmac = Tarmac.objects.all() fencing = Fencing.objects.all() blockpaving = BlockPaving.objects.all() return render(request, 'photos.html', { 'patios':patios, 'resins':resins, 'tarmac':tarmac, 'fencing':fencing, 'blockpaving':blockpaving }) def pic_detail(request, id): patios = get_object_or_404(Patios, id= id) photos = Patiosimage.objects.filter(patios=patios) resins = get_object_or_404(Resins, id= id) … -
django - share variables between apps
I am connecting to postgresql database using psycopg2 and after this connection, I will have instance of psycopg2.connect with variable name connection and another variable cursor which is instance of connection.cursor. And I have two more variables with some data. I have 4 apps in django, each for one api and all of these apps has to interact with database. So, in views.py of each app, I did: from file_with_variables import database_variables and this generates an ImportError when I do py manage.py runserver. How do i fix this? EDIT 1: This can't be a possible duplicate of (since my question is about variables and these didn't help me too): 1. django - Sharing data between apps 2. Sharing models between Django apps -
Run javascript variable in Django templates
I have variable bbb = "youmightalsolike.0.title"; in javascript of django template file. i want to add {{ and }} in variable bbb like i made in aaa for example which runs perfectly with output 42 which i want. var aaa = {{youmightalsolike.0.title}}; console.log("aaa = "+aaa); //aaa = 42 I have tried using these which was useless. maybe i dont know to concantinate var bbb = "youmightalsolike.0.title"; console.log("bbb = "+bbb); //bbb = youmightalsolike.0.title var ccc = {{bbb}}; console.log("ccc = "+ccc); //ccc = undefined -
Primary key Auto generation in djongo
I am creating an application using django with djongo connector. I am getting only the _id(5ec6ec593ece2384a572ec0c), AutoFiled ID is not generating and incrementing. But in auth_user I am getting the ID and it's incrementing automatically. Could any one help me in this? Thanks in advance. -
Django Crispy Forms Form Helper - Custom Checkbox CSS Class
I'm presently using Django's crispy forms to generate a HTML form. I would like to change the text of read-only check-boxes to white with an opacity of 0.5. Looking at the Chrome Developer Console, I see crispy forms is calling the .custom-control-input:disabled~.custom-control-label from https://stackpath.bootstrapcdn.com/bootstrap/scss/_custom-forms.scss. Within the console I can change it without issue; the problem I face is trying to overwrite the scss class. Copying the relevant parts of the scss file, I've created a new one in my project: .SCSS File: .mycustom-control { position: relative; display: block; min-height: ($font-size-base * $line-height-base); padding-left: $mycustom-control-gutter; } .mycustom-control-inline { display: inline-flex; margin-right: $mycustom-control-spacer-x; } .mycustom-control-input { position: absolute; z-index: -1; // Put the input behind the label so it doesn't overlay text opacity: 0; &:checked ~ .mycustom-control-label::before { color: $mycustom-control-indicator-checked-color; @include gradient-bg($mycustom-control-indicator-checked-bg); @include box-shadow($mycustom-control-indicator-checked-box-shadow); } &:focus ~ .mycustom-control-label::before { // the mixin is not used here to make sure there is feedback box-shadow: $mycustom-control-indicator-focus-box-shadow; } &:active ~ .mycustom-control-label::before { color: $mycustom-control-indicator-active-color; background-color: $mycustom-control-indicator-active-bg; @include box-shadow($mycustom-control-indicator-active-box-shadow); } &:disabled { ~ .mycustom-control-label { color: white; opacity: 0.5; &::before { background-color: $mycustom-control-indicator-disabled-bg; } } } } I've also loaded it in my HTML file: <link rel="stylesheet" href="{% static "/checkboxes.scss" %}"> But how then do I … -
Making Django Payments [closed]
What is the best way to make payments? I'm in the making of an app in which users can make payments to other users. Thus, any user that registers their account can receive payments. However I'm not exactly sure on how to keep this secure. Storing someone's bank data doesn't seem secure at all, that is why I was thinking of simply implementing it with PayPal. Users could register the necesary data to receive PayPal payments, but not enough to allow to log into their account. Thus when user A wants to make a payment to user B, A would be redirected to PayPal's site to make a payment to user B's paypal's account. Basically I just want to keep enough data so that users are able to receive payments but never enough financial data that if the site got hacked and someone fully took over the database they could make payments from an user's account. EDIT: Also what could I do to keep User's PayPal's data as safe as possible? -
is it possible to overight the main page of admin site? DJANGO
do you have idea on how to overight this page? do you have any documentation that easy to follow and understand? -
Django - 'ManyRelatedManager' object has no attribute 'get_total_addon_price'
Here I am trying to call a function of a different model class. When trying to call this function it throws an error sayiing 'ManyRelatedManager' object has no attribute 'get_total_addon_price' In Cart(models.Model) I am trying to call the function get_total_addon_price of the model AddonCartItem def get_total(self): c_cart_item = 0 a_cart_item = 0 cart_total = 0 if self.addon_item.get_total_addon_price != 0: But it throws an error Can anyone please help me with this. I have added the full models.py and the error Traceback models.py class ComboCartItem(models.Model): user = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE) combo = models.ForeignKey(Combo, blank=True, null=True, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) ordered = models.BooleanField(default=False) def __str__(self): return f"{self.quantity} of {self.combo.title}" # return str(self.id) def get_total_combo_price(self): return self.quantity * self.combo.combo_regular_price def get_total_combo_sale_price(self): return self.quantity * self.combo.combo_sale_price def get_amount_saved(self): return self.get_total_combo_price() - self.get_total_combo_sale_price() def get_final_price(self): if self.combo.combo_sale_price: return self.get_total_combo_sale_price() return self.get_total_combo_price class AddonCartItem(models.Model): user = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE) addon = models.ForeignKey(Addon, blank=True, null=True, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) ordered = models.BooleanField(default=False) addon_total = models.DecimalField(default=0.00, max_digits=100, decimal_places=2) def __str__(self): return f"{self.quantity} of {self.addon.name}" # return str(self.id) def get_total_addon_price(self): addon_total = 0 addon_total = self.quantity * self.addon.price self.addon_total = addon_total self.save() return self.quantity * self.addon.price class Cart(models.Model): user = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE) combo_item = models.ManyToManyField(ComboCartItem, … -
Generate token without username and password using djangorestframework-simplejwt
I am using a non username password based authentication, with the help of a model field, which is passed as API_KEY in post parameter. If this value matches with the record in the model. I want to add a custom payload. I used to the following code, but it asks me for username and password. class MyTokenObtainPairSerializer(TokenObtainPairSerializer): def validate(self, attrs): try: request = self.context["request"] except KeyError: pass else: request_data = json.loads(request.body) api_key = request_data.get("API_KEY") try: profile = Factory.objects.get(api_key = api_key) except: raise Exception finally: return super().validate(attrs) @classmethod def get_token(cls, factory): token = super().get_token(factory) token['id_key'] = factory.api_key return token class MyTokenObtainPairView(TokenObtainPairView): serializer_class = MyTokenObtainPairSerializer Alternatively, I tried class Login(APIView): permission_classes = (permissions.AllowAny, ) def post(self, request): if "API_KEY" not in request.data: return Response("API_KEY Missing", status=status.HTTP_400_BAD_REQUEST) factory = Factory.objects.filter(api_key=request.data['API_KEY']) if factory is None: return Response("Invalid API KEY", status=status.HTTP_401_UNAUTHORIZED) refresh = RefreshToken.for_user(factory) return Response({ 'refresh_token': str(refresh), 'access_token': str(refresh.access_token) }, status=status.HTTP_200_OK) but it throws error, user_id = getattr(user, api_settings.USER_ID_FIELD) AttributeError: 'QuerySet' object has no attribute 'id' -
saving submission.created_utc value and saving in django models.DateTimeField
Having an issue grabbing the submission.created_utc value and trying to store it in my django models.DateTimeField. // here's my model's DateTimeField red_created = models.DateTimeField(default=timezone.now, editable=False) // this is how I try to save it red_created = returnUtcDate(submission.created_utc) // value of created_utc = 1589720741.0 def returnUtcDate(utcDate): dt = datetime.fromtimestamp(int(utcDate)) newUtcDate = timezone.make_aware(dt, timezone.utc) return newUtcDate // value being returned 2020-05-17 13:05:41+00:00 When I try to run that I get: TypeError: expected string or bytes-like object I know I need to convert the utc date before I store it but I don't know how or to what format. Tried searching but I'm assuming searching for the wrong terms. -
When to Fan Out with Celery Groups vs. Delay
Trying to figure out best practice here as I am learning celery. I want to fan out a bunch of small jobs in another job. I understand groups is a great way to get the results from a bunch of enqueued smaller jobs, but what if I don't care about results? I just want to split a big job into a bunch of smaller tasks. Is calling delay in a loop the same thing in this case? Is it still best practice to use groups when wanting to fan out, and queue up a bunch of smaller jobs in a parent job? Below is some pseudo code as an example. @app.task def call_job(job_args): groups([for small_job.s(x) for x in job_args]).delay() @app.task def small_job(x): # do something vs @app.task def call_job(job_args): for x in job_args: small_job.delay(x) @app.task def small_job(x): # do something -
Django Rest Framework, "lookup_field" value that is defined on models level
I faced with an issue in Django Rest Framework when I try to implement hyperlink related stuff. Let's say there is a model with slug that is defined during save procedure class Family(models.Model): name = models.CharField(unique=True, max_length=150) slug = models.SlugField(unique=True) description = models.TextField(blank=True) def __str__(self): return self.name def save(self, *args, **kwargs): self.slug = slugify(self.slug) super().save(*args, **kwargs) So in my serializers package I have the following: class FamilySerializer(serializers.ModelSerializer): class Meta: model = Family fields = ["name", "slug", "description", "url"] extra_kwargs = { "url": {"view_name": "api:family-detail", "lookup_field": "slug"}, # I have to mark this field as not required one to be able POST wo this field "slug": {"required": False} } When I try to create a new Family through POST request, of course, I'm getting django.urls.exceptions.NoReverseMatch: Reverse for 'family-detail' with keyword arguments '{'slug': ''}' not found. 2 pattern(s) tried: ['api/families/(?P<slug>[^/.]+)\\.(?P<format>[a-z0-9]+)/?$', 'api/families/(?P<slug>[^/.]+)/$'] and django.core.exceptions.ImproperlyConfigured:... exception as well. And here is my ViewSet: class FamilyViewSet(ModelViewSet): """ Provides CRUD operations on Family entity. """ serializer_class = FamilySerializer queryset = Family.objects.all() lookup_field = "slug" permission_classes = [permissions.IsAdminUser] How to elaborate the issue I faced. Should I modify FamilyViewSet to generate slug on ViewSet level or take a look at "custom" reverse? -
Django Issues - Adding a product
I'm currently learning how to create websites using Django. I followed a tutorial on Youtube and came across an error that I don't really understand. I was on the admin page and tried to add products to my site. This is the error I received after clicking Save: Screenshot. I hope this is enough information to solve the issue. If anyone has an answer could you please make it somewhat easy to understand. I'm just starting and probably won't understand some terms. Thank you! -
How can i declare a user profile with username in Django?
I'm new to Django and still learning. Currently, I'm trying to develop a Blog website. Last few days I'm suffering this kind of error and I can't solve this. My codes: base.html <nav> <ul> <li><a href="{% url 'account:profile' username=user.username %}">Profile</a></li> </ul> </nav> urls.py path('profile/<username>/', views.profile, name='profile'), views.py def profile(request, username): user = User.objects.get(username=username) editable = False if user.is_authenticated and request.user == user: editable = True return render(request, 'Account/profile.html', {'user':user, 'editable':editable}) profile.html <!--User Profile--> <div class="row info"> <div class="col-sm-4 image"> {% if user.user_profile %} <img src="/media/{{ user.user_profile.profile_pic }}" alt="{{ user.username }}" title="{{ user.username }}" class="rounded-circle"> {% else %} <img src="/media/profile_pics/avatar.png" title="Add Profile Photo" class="rounded-circle"> {% endif %} </div> <div class="col-sm-8 text"> <h2>{{ user.username }}</h2> <h6 class="post-text"><strong>{{ user.blog_author.count }}</strong> Blogs</h6> <div class="full-name"> <h4>{{ user.first_name }} {{ user.last_name }}</h4> </div> <br> {% if editable %} <a href="{% url 'account:edit_profile' %}" class="btn btn-light btn-md">Edit Profile</a> <a href="{% url 'account:logout' %}" class="btn btn-danger btn-md logout">Logout</a> {% endif %} </div> </div> It runs perfectly when the user is logged in. However, it shows this type of error when the user is logged out. NoReverseMatch at / Reverse for 'profile' with keyword arguments '{'username': ''}' not found. 1 pattern(s) tried: ['account/profile/(?P<username>[^/]+)/$'] I want to use one template … -
Reverse for 'update_task' '('',)' not found
Im new to programming, i started 3 weeks ago, so im very new and get lost really quick haha, so this project is for learning for my final app that i want to do, this is just one part of it. Im trying to make a web where i can add products, that have specific atributes, like, name, family, type, price, etc. This is the error i get : NoReverseMatch at / Reverse for 'update_task' with arguments '('',)' not found. 1 pattern(s) tried: ['update_task\/(?P[^/]+)\/$'] Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 3.0.6 Exception Type: NoReverseMatch Exception Value: Reverse for 'update_task' with arguments '('',)' not found. 1 pattern(s) tried: ['update_task\/(?P[^/]+)\/$'] Exception Location: C:\Users\Fede\PycharmProjects\remito_wakanda_prueba_1\venv\lib\site-packages\django\urls\resolvers.py in _reverse_with_prefix, line 677 Python Executable: C:\Users\Fede\PycharmProjects\remito_wakanda_prueba_1\venv\Scripts\python.exe Python Version: 3.6.8 Python Path: ['C:\Users\Fede\PycharmProjects\remito_wakanda_prueba_1\remitowakandaprueba', 'C:\Users\Fede\PycharmProjects\remito_wakanda_prueba_1\venv\Scripts\python36.zip', 'C:\Users\Fede\AppData\Local\Programs\Python\Python36\DLLs', 'C:\Users\Fede\AppData\Local\Programs\Python\Python36\lib', 'C:\Users\Fede\AppData\Local\Programs\Python\Python36', 'C:\Users\Fede\PycharmProjects\remito_wakanda_prueba_1\venv', 'C:\Users\Fede\PycharmProjects\remito_wakanda_prueba_1\venv\lib\site-packages'] and this is my code : list.html : <div class="center-column"> <form method="POST" action="/"> {% csrf_token %} {{form.title}} <input class="btn btn-info" type="submit" name="Añadir Producto"> </form> <div class="todo-list"> #task #tasks {% for producto in productos %} <div class="item-row"> <a class="btn btn-sm btn-info" href="{% url 'update_task' productos.id %}">Modificar</a> <a class="btn btn-sm btn-danger" href="{% url 'delete' productos.id %}">Borrar</a> {% if productos.complete == True %} <strike>{{productos}}</strike> {% else %} <span>{{productos}}</span> {% endif %} … -
Django redirect to different page based on choice
I need to add redirect to the next page in Django based on Payment choice. So if customer click pay on delivery or pay on local pickup, then redirect should be to the page where he will see details etc. If he chose pay by bank transfer, there should be redirect to the different page where he will see bank account details. Actually I have everything ready just need to code for redirect and i dont know if i should to do that on template or in the views. Any recommendations please ? -
Upload file in Django using modal form
I'm working with Django. I'm trying to upload an image through a ModelForm. The only particular thing is that I'm using the bootstrap-modal-forms module and as I'm kind of noobish I can't catch the error. My model in models.py is: class Sheet(models.Model): name = models.CharField(max_length=30) image = models.ImageField(upload_to='cheatsheets/', default='test.png') class Meta: verbose_name = "Cheat sheet" def __str__(self): return self.name My form in forms.py is: class SheetForm(BSModalForm): class Meta: model = Sheet fields = ['name', 'image'] Now my view in views.py that generates the bootstrap modal is: class EditSheetView(BSModalUpdateView): model = Sheet template_name = 'edit_sheet.html' form_class = SheetForm def get_success_url(self): return reverse_lazy('cheatsheet:menu_cheatsheet') def form_valid(self, form): print(form.cleaned_data['image']) return HttpResponseRedirect(self.get_success_url()) Everything works great, I use several BSModal views to create, modify or delete and everything is fine. Except here, I can't upload an image. (and probably could not upload a file with other forms either) As you can see in EditSheetView() I've added a form_valid() to debug. For form.cleaned_data['image'] it prints the old_image.png despite I've uploaded new_image.png. For information I can correctly upload an image through the admin panel and I can change the name through the form. So the only thing is the image upload. What could I try ? Obviously my … -
Position only two child divs side by side and third one at the bottom center in Django template using CSS
I have the following html code in django template. <div class="row"> {% for user in companies.object_list %} <div class="index_column"> <div class="logo_services"> <div class="user_logo"><a href="#" target="_blank"> <img class="images" src="{{ user.userprofile.logo.url }}"> </a></div> <div class="services">{{ user.userprofile.services|linebreaks }}</div> </div> <div class="username"><h6>{{ user.username }}</h6></div><br><br> </div> {% if forloop.counter|divisibleby:2 %} </div> <div class="row"> {% endif %} {% endfor %} </div> I want to place services and user_logo side by side and username at the bottom of the two and vertical and horizontal align all these inside row. How can I do that?