Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django radio button on request.POST is not working
i am trying to read the value from the radio.input in the form below using def question_detail(request,question_id,quiz_id): q = Quiz.objects.get(pk = quiz_id) que = Question.objects.get(pk = question_id) count = q.question_set.count() try: selected_choice = que.answer_set.get(pk=request.POST['choice']) except(KeyError, Answer.DoesNotExist): come = que.rank came = come + 1 later_question = q.question_set.get(rank=came) return render(request, 'app/question_detail.html',{'que': que, 'count': count, 'later_question': later_question}) else: if selected_choice.correct is True: try: come = que.rank came = come + 1 later_question = q.question_set.get(rank=came) except: come = que.rank came = come later_question = q.question_set.get(rank=came) else: come = que.rank later_question = q.question_set.get(rank=come) return render(request, 'app/question_detail.html',{'count': count, 'que': que, 'later_question': later_question}) but when i try to access the webpage,it throws an Keyerror,please help <form action="{% url 'app:detail' quiz_id=que.quiz.id question_id=later_question.id%}" method="post">{% csrf_token%} {% for choice in que.answer_set.all %} <input type="radio" name='choice' value="{{choice.id}}"> <label>{{choice.answer}}-{{choice.correct}}-{{choice.rank}}</label><br> {% endfor %} -
How to unpack dictionary into models.TextChoices atributes in Django models?
Here is new option in Django 3.0 for choices in models by using ENUM library: https://docs.djangoproject.com/en/3.0/ref/models/fields/#enumeration-types I have been trying to use it to create countries choices for AbstractUser model: class User(AbstractUser): """ Custom user model based on AbstractUser model. """ class Countries_ISO3166(models.TextChoices): # This code should run when class is initialized. Instead of cls should be class object for country_code, country_name in countries.COUNTRIES_DICT.items(): setattr(cls, country_name, country_code) username = None email = models.EmailField(verbose_name='email address', unique=True) first_name = models.CharField(null=True, blank=False, max_length=30, verbose_name='first name') last_name = models.CharField(null=True, blank=False, max_length=150, verbose_name='last name') user_country = models.CharField(max_length=2, choices=Countries_ISO3166.choices, null=True, verbose_name='user country of origin') USERNAME_FIELD = 'email' # https://docs.djangoproject.com/en/3.0/topics/auth/customizing/#django.contrib.auth.models.CustomUser.REQUIRED_FIELDS REQUIRED_FIELDS = [] #default_manager = BaseUserManager() objects = users_managers.CustomUserManager() class Meta: unique_together = ( ('first_name', 'last_name', ), ) index_together = unique_together verbose_name = 'user' verbose_name_plural = 'users' def __str__(self): return f'pk - {self.pk}, full name - {self.get_full_name()}, email - {self.email}' Problem is I dont know how to unpack countries dictionary in order to create Countries_ISO3166 class atributes like in Django documentation example. I have tried to do it in init, new but it doesn't work. COUNTRIES_DICT is a counties dict according ISO3166 format: COUNTRIES_DICT = { "AF": "Afghanistan", "AX": "Åland Islands", "AL": "Albania", "DZ": "Algeria", "AS": "American … -
Update foreign key related table field while inserting new record in first table django
I have two tables Table Tour class Tour(BaseModel): statuses = [ ('DRAFT', 'Draft'), ('ACTIVE', 'Active'), ('PAID', 'Paid'), ('COMPLETED', 'Completed') ] status = models.CharField(max_length= 100, choices=statuses, default="DRAFT") Table Billing class Billing(BaseModel): tour=models.ForeignKey(Tour, on_delete=models.PROTECT) total=models.FloatField(null=True) views.py class BillingViewSet(viewsets.ModelViewSet): queryset = Billing.objects.all() serializer_class=Billlingerializer serializers.py class Billlingerializer(serializers.ModelSerializer): class Meta: model = Billing fields ='__all__' whenever a new record is added to Billing table we need to change status to PAID in Tour table, I have other tables too, which is like Billing if any record is added there also need to change the status to complete or active etc.So we need common method that is defined in Tour model which can be called from serialiazers or views .Please help me, thanks in advance. -
Fetch rows field = true by BooleanFilter
I am making very simple booleanfilter I have model which has boolean column named 'is_show'. I want to fetch the items is_show is true. I accessAPI like this /api/items?is_show=true class Text(models.Model): is_show = models.BooleanField() class TextFilter(filters.FilterSet): is_show = filters.BooleanFilter(is_show=True) However it still returns all rows. -
Django HTML templates can't load CSS files
In my Django project I added a new 404 page, that gets called when I enter an invalid url. But, the CSS file is not loaded with page, so it appears mis-formatted. The browser gives me this error: "Refused to apply style from because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled." The point is, There are other CSS files in the 'static' folder that are loaded correctly without this error, like the bootstrap.css file... My settings.py # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['localhost', '127.0.0.1'] # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.0/howto/static-files/ STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'collected_static') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'static/media') STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] My urls.py urlpatterns = [ ... ] handler400 = 'utils.views.error_400' handler403 = 'utils.views.error_403' handler404 = 'utils.views.error_404' handler500 = 'utils.views.error_500' My utils.views.py def error_400(request, exception): data = {} return render(request, 'utils/mv_admin_400.html', data) def error_403(request, exception): data = {} return render(request, 'utils/mv_admin_403.html', data) def error_404(request, exception): data = {} return render(request, 'utils/mv_admin_404.html', data) def error_500(request): data = {} return render(request, 'utils/mv_admin_500.html', data) My 404.html {% load static %} <!DOCTYPE html> … -
Delete model objects involved in ManyToMany relationships in postgres
I am using postgres and have two very simple models in Django: class VariantTag(ModelWithGUID): saved_variants = models.ManyToManyField('SavedVariant') class SavedVariant(ModelWithGUID): xpos_start = models.BigIntegerField() xpos_end = models.BigIntegerField(null=True) Now, I want to delete SavedVariant but getting an error Key (id)=(24) is still referenced from table "seqr_varianttag_saved_variants". How to correctly delete SavedVariant objects in this case? In dbshell I mean, in postgres using SQL. -
Different time intervals creations
I have datetime objects for start_time and end_time. Both of these from user comes in 24 hours. for eg: 14:00hrs and 16:00hrs. I have an interval of 12 minutes per hour. dateTimeA = datetime.datetime.strptime(start_time, '%H:%M') dateTimeB = datetime.datetime.strptime(end_time, '%H:%M') I need to create slots in the following manner: Diff_in_time = dateTimeB - dateTimeA diff_in_hours = Diff_in_hours.total_seconds() / 3600 So, diff_in_hours gives me a time difference in hours. Here, diff_in_hours = 2.0 Now, the slots to be created should be. slots_interval = 60/12(interval) = 5 slots/hour with interval of 12 minutes. 14:00 - 14:12 14:12 - 14:24 14:24 - 14:36 14:36 - 14:48 14:48 - 15:00 15:00 - 15:12 15:12 - 15:24 15:24 - 15:36 15:36 - 15:48 15:48 - 16:00 Total slots = 10 However, I am unable to perform this operation. I need to keep a tally of both from_time and end_time here to create slots. Can anyone suggest some help? -
how to check whether user after login has submitted the form one , if yes again if he login he should redirect to form 2 not one again in django
I have an app where user login and after he logins he get redirect to dashboard where appears a form and user fill the form , once user fill the form he redirect to next page where it shows the progress of the form. So if user login again he should automatically redirect to the progress page he should not get the form page again if he has filled it . Can any one suggest me how to achieve these. views.py def create(request): if request.method == 'POST': post = AccountProfile() post.user = request.user post.name = request.POST['name'] post.email = request.POST['email'] post.mobile = request.POST['mobile'] post.date = request.POST['date'] post.sex = request.POST['sex'] post.save() return render (request,'posts/dashboard-post-a-job.html') These is the views where user get redirect after login and fill form. -
Custom user model - 'Group' object has no attribute 'user_set'
I am fairly new to Django and set up a custom user model with token authentication. Now I am trying to add the possibility of adding users to user groups from the backend in order to specify permissions. However, I dont seem to be able to get past this error. I am using Python 3.7 and Django 2.2.6. Appreciate your help! The error: File "/Users/.../Dev/.../account/models.py", line 114, in save_m2m self.instance.user_set.set(self.cleaned_data['users']) AttributeError: 'Group' object has no attribute 'user_set' my models.py: from django.db import models from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager from django.conf import settings from django.db.models.signals import post_save from django.dispatch import receiver from rest_framework.authtoken.models import Token from django import forms from django.contrib import admin from django.contrib.auth import get_user_model from django.contrib.admin.widgets import FilteredSelectMultiple from django.contrib.auth.models import Group class MyAccountManager(BaseUserManager): def create_user(self, email, username, password=None): if not email: raise ValueError("Users must have an email address") if not username: raise ValueError("Users must have a username") user = self.model( email=self.normalize_email(email), username=username, ) group = Group.objects.all() group.user_set.add(user) 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 … -
Form coming back with <django.db.models.query_utils.DeferredAttribute object at 0x044C5C28>
Newbie here. I tried to create a Todo app.When I try to display this object as a form , form fields displays some gibberish like "django.db.models.query_utils.DeferredAttribute object at 0x04455C28" inside the textbox. This is my form how looks like views def viewtodo(request,todo_pk): todo=get_object_or_404(Getitdone,pk=todo_pk,user=request.user) if(request.method=='GET'): form=GetitdoneForm(instance=Getitdone) return render(request,'viewtodo.html',{'todo':todo,'form':form}) else: try: form=GetitdoneForm(request.POST,instance=Getitdone) form.save() return redirect('currenttodos') except ValueError: return render(request,'viewtodo.html',{'todo':todo,'form':form,'error':'bad value passed in'}) Template {{ error }} {{ todo.title }} <form method="POST"> {% csrf_token %} {{ form.as_p }} <button type="submit">save</button> </form> forms.py from django.forms import ModelForm from .models import Getitdone class GetitdoneForm(ModelForm): class Meta: model=Getitdone fields=['title','memo','important',] -
No formatting supported by TextField in django admin panel
I have Post model and have it registered in admin. It has description of TextField() but while adding new post from admin panel, description area does not support newline or <br> or any kind of formatting. I have no usage of forms and only way to add post is through admin panel. -
i need to get 40 boxes in django output but i am getting only 2 boxes
from django.shortcuts import render import random Create your views here. def home(request): l=[] for i in str(random.randint(1,40)): l.append(i) return render(request, 'check/web.html', {'list':l} ) templates: {% for i in list %} {{i}} {% endfor %} I am getting only two boxes instead of 40 boxes -
how can i pass Form values to particle.io
Im using django,raspberry pi3, particle.io,relay I want to pass on\off value from Form to particle.io so that i can control lightbulb. <form action="https://api.particle.io/v1/devices/{{value1}}/relay?access_token={{value2}}" method="POST"> The code given above works perfectly fine but when i try to apply the same thing for a pop-up window , Particle.io is not able to receive the value on\off. The code is given below {% if user.is_authenticated %} <div class = "container"> <div class="wrapper"> <form action="javascript:my_c()" class="form-signin" method="POST"> <hr class="colorgraph"> <br> <p style="color:black; font-family:helvetica; font-size:20px;">Welcome to your home automation system.</p><br> <br> <h style="color:black; font-family:helvetica;">Greetings {{request.user.get_short_name}} </h><br> {% for Profile in UserD|slice:":1" %} <h style="color:black; font-family:helvetica;">Access {{value1}} </h><br> <h style="color:black; font-family:helvetica;">Device ID {{value2}} </h><br> <p style="color:black; font-family:helvetica; font-size:20px;">Tell your device what to do!</p> <center> <div id="donate"> <a style="color:black; font-family:helvetica; font-size:15px;">Lights:</a> <label class="green"><input type="radio" name="arg" value="on"><span>ON</span></label> <label class="red"><input type="radio" name="arg" value="off"><span>OFF</span></label> </div> </center> <center> <input class="btn btn-primary btn-xl js-scroll-trigger" type="submit" value="Do it!"> </center> <br> <br> <script type="text/javascript"> function my_c(){ var win = window.open('https://api.particle.io/v1/devices/{{value1}}/relay?access_token={{value2}}', '1366002941508','width=500,height=200,left=375,top=330'); setTimeout(function () { win.close();}, 6000); } </script> </form> {% endfor %} also is there anyway the instead of using setTimeout(function () { win.close();}, 6000); this , the window is closed automatically closed once the site is fully loaded eg. using onload or something … -
Delete 'Server' response header in Django framework - V3.0.5
Before I begin my question, I have referred the stackoverflow post - Delete header in django rest framework response. Please find the middleware code and settings.py below (referred to the django middleware docs): middleware.py: class SimpleMiddleware: def __init__(self, get_response): self.get_response = get_response # One-time configuration and initialization. def __call__(self, request): response = self.get_response(request) response.__setitem__('Server', '') return response settings.py MIDDLEWARE = [ ...., ...., 'middleware_demo.middleware.SimpleMiddleware', ] With the above code, I get the server response with the server header set to empty string as below. Which is as expected and doesn't disclose the server header details: HTTP/1.1 200 OK Date: Tue, 21 Apr 2020 12:55:25 GMT Content-Type: text/html Server: X-Frame-Options: DENY Content-Length: 16351 X-Content-Type-Options: nosniff My goal is to remove the header altogether and tried 2 ways for the same in middleware.py: Method 1 - official docs class SimpleMiddleware: def __init__(self, get_response): self.get_response = get_response # One-time configuration and initialization. def __call__(self, request): response = self.get_response(request) response.__delitem__('Server') return response Method 2 - referred stackoverflow blog - Delete header in django rest framework response class SimpleMiddleware: def __init__(self, get_response): self.get_response = get_response # One-time configuration and initialization. def __call__(self, request): response = self.get_response(request) del response['Server'] return response But the response still has … -
Django don't render if regex match?
I have pseudo coded what I would like but cant see anything in the docs for using if statements alongside a regex? Any help is appreciated. <!-- if window.name includes Before|After dont render--> {{window.event_id}}-{{window.name}} <!-- end if --> the regex is easy: /(Before|After)/g -
How to reflect changes on both One-To-Many-Relationship instances when updating one of them at once in Django?
I have two tables connected with a Foreignkey. I have a field in the main model, its value depends on the child instances. For example, if I have a Library model and a Book model, Book has Foriegnkey to Library. And we have a field in the Library model which is equal to the "total_price" of all the books in the library. How I can update that field "total_price" whenever I increase the quantity of a certain book or decrease it. Note that I have to save each instance separately in order to get the value right. I have the Books as a TabularInline inside Library, so I make the change to the quantity and save the changes, and then I have to press save one more time to change the "total_price" field. -
Show month name instead of month number in django model choice field
Column acct_per_num in table SAPAdjustment contains the month number. The following code gives a dropdown with month number (1,2,3) but I want month name (January, February, March) instead. forms.py class SAPReconForm(forms.Form): month = forms.ModelChoiceField(queryset=SAPAdjustment.objects.values_list('acct_per_num',flat=True).distinct(), empty_label=None) models.py class SAPAdjustment(models.Model): acct_per_num = models.IntegerField( blank=True,null=True, verbose_name =_('Month'),help_text=_('Month')) -
How can we return multiple SQL table in a single postgre function?
How can we return multiple SQL table in a single postgre function I want something like this: postgrefuction('some parameters') RETURNS refcursor ... ... ... AS $BODY$ DECLARE ... ... ... BEGIN SQL:='some queries'; SQL2:= 'some queries'; RETURN SQL,SQL2 $BODY$ -
Model Formset showing error wen updating my form
The form is creating perfectly but when I am trying to update the form the model formset is not updating as it is showing the data but wen when i change the data and submit it the lecture_content fliefield is showing empty.`def content_edit_view(request, id): course = get_object_or_404(Course, id=id) LectureFormset = modelformset_factory(Lecture, fields=('lecture_title', 'lecture_content'), extra=0) if course.user != request.user: raise Http404() if request.method == 'POST': content_edit_form = ContentEditForm(request.POST or None, request.FILES or None, instance=course) formset = LectureFormset(request.POST or None, request.FILES or None) if content_edit_form.is_valid() and formset.is_valid(): content_edit_form.save() print('course is saved') data = Lecture.objects.filter(post=post) # give index of the item for a formset item strting form 0 and (f)the item itself for index, f in enumerate(formset): if f.cleaned_data: if f.cleaned_data['id'] is None: video = Lecture(course=course, lecture_title=f.cleaned_data.get('lecture_title'), lecture_content=f.cleaned_data.get('lecture_content')) video.save() else: video = Lecture(course=course, lecture_title=f.cleaned_data.get('lecture_title'), lecture_content=f.cleaned_data.get('lecture_content')) d = Lecture.objects.get(id=data[index].id) #get slide id which was uploaded d.lecture_title = video.lecture_title, # changing the database tiitle with new title d.lecture_content = video.lecture_content # changing the database content with new content d.save() return redirect('teacher-profile') else: print("form invalid") else: content_edit_form = ContentAddForm(instance=course) formset = LectureFormset(queryset=Lecture.objects.filter(course=course)) context = { 'contentForm': content_edit_form, 'course': course, 'formset': formset, } return render(request, 'apps/contentAdd.html', context) ` -
Checkout form not getting saved in admin
Hi I'm trying to develop an e-commerce site with Django. So I'm at this point where, users can add items to their cart, proceed to checkout but for some reason, my checkout form is not being saved. I made sure that I have registered my models, and ran migrations, but everytime I fill out my form and go to check in my admin panel, it says: 0 user addresses. What is the problem? Can anyone please help me out? My views.py: @login_required def checkout(request): if request.method == 'POST': address_form = UserAddressForm(request.POST) if address_form.is_valid(): new_address = address_form.save(commit= False) new_address.user = request.user new_address.save() return redirect(reverse("checkout")) else: address_form = UserAddressForm() context = {"address_form": address_form} template = "orders/checkout.html" return render(request, template, context) My checkout.html: <form method="POST" action=''> {% csrf_token %} <fieldset class="form-group"> {{ address_form|crispy }} </fieldset> <div class="form-group"> <input type="submit" class="btn btn-outline-dark" value="Place Order"/> </div> </form> My urls.py: from orders import views as orders_views path('checkout/', orders_views.checkout, name='checkout'), -
how to get data personal from the another user in single website
I am creating a website where tour and travels and truck transports record their data in the website, M done to make this but I have problem, one user logged in and enter their entries well, but another user logged in and he able to see first user data, that's the problem, pl z tell me how to solve this, M using sqlite3 db and django framework -
How do I create a new record in a related model, with just a button in django?
I have two models: class Post(models.Model): POST_TYPE_CHOICES = ( ('D','Declaration'), ('O', 'Offer'), ('R', 'Request'), ) post_type=models.CharField(max_length=1,choices=POST_TYPE_CHOICES, blank =False, default='D') content = models.CharField(max_length=144) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): title = f'{self.get_post_type_display()} from {self.author}' return title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk':self.pk}) and class Match(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='matched_post') matchee=models.ForeignKey(User, on_delete=models.CASCADE, related_name='matchee') created_on=models.DateTimeField(auto_now_add=True) read=models.BooleanField(default = False) def __str__(self): return f'{self.matchee} matched with {self.post.author}: {self.post.get_post_type_display()}' I have a list view for all records in the Post model: class PostListView(ListView): model = Post template_name = 'marketplace/post_cards.html' context_object_name = 'posts' ordering = ['-date_posted'] paginate_by = 15 I have created a template to display every one of the posts in the Post model: {% extends "base.html" %} {% block content %} <div class="container-fluid"> <div class="row"> {% for post in posts %} <div class="col-sm"> <div class="card" style="width:15rem"> <img class="rounded-circle card-img-top" src="{{ post.author.profile.image.url }}"> <div class="card-body"> <div class="card-title"> {{ post.get_post_type_display }} from <a class="mr-2" href="#">{{ post.author }}</a> </div> <div class="card-subtitle"> <small class="text-muted">{{ post.date_posted|date:"F d, Y" }}</small> </div> <div class="card-text"> {{ post.content }} </div> {% if user.is_authenticated %} <p class="card-text">Click below to match with this {{ post.get_post_type_display }}.</p> <a href="#" class="btn btn-outline-info">Match</a> </form> {% else %} <p class="card-text">You must be logged in to match with … -
Error deploying Cookiecutter-Django app to Heroku
I'm working with the Django Cookiecutter boilerplate, using Docker. Everything works fine locally so now I'm trying to deploy the app to Heroku by following this guide: Deployment on Heroku. I'm using Django 3 and Rest framework. Docker for development. After running the config commands, I push to Heroku master and get this error: Error while running '$ python manage.py collectstatic --noinput'. Here's the trace: remote: -----> $ python manage.py collectstatic --noinput remote: Traceback (most recent call last): remote: File "/app/.heroku/python/lib/python3.7/site-packages/environ/environ.py", line 273, in get_value remote: value = self.ENVIRON[var] remote: File "/app/.heroku/python/lib/python3.7/os.py", line 679, in __getitem__ remote: raise KeyError(key) from None remote: KeyError: 'SENDGRID_API_KEY' remote: During handling of the above exception, another exception occurred: remote: Traceback (most recent call last): remote: File "manage.py", line 31, in <module> remote: execute_from_command_line(sys.argv) remote: File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line remote: utility.execute() remote: File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/__init__.py", line 395, in execute remote: self.fetch_command(subcommand).run_from_argv(self.argv) remote: File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/__init__.py", line 231, in fetch_command remote: settings.INSTALLED_APPS remote: File "/app/.heroku/python/lib/python3.7/site-packages/django/conf/__init__.py", line 76, in __getattr__ remote: self._setup(name) remote: File "/app/.heroku/python/lib/python3.7/site-packages/django/conf/__init__.py", line 63, in _setup remote: self._wrapped = Settings(settings_module) remote: File "/app/.heroku/python/lib/python3.7/site-packages/django/conf/__init__.py", line 142, in __init__ remote: mod = importlib.import_module(self.SETTINGS_MODULE) remote: File "/app/.heroku/python/lib/python3.7/importlib/__init__.py", line 127, in import_module remote: return _bootstrap._gcd_import(name[level:], package, level) remote: … -
My cart items dont remove even after pressing remove button
I want my cart item to remove when clicked on remove but its not working cart page just refresh and end execution.. I want to create a cart function to remove items from it. please help me to get out over this its really frustating my template file views.html--- ''' {% extends 'pro/base.html' %} {% block content %} {% if empty %} <div class="container"> <h1 style="text-align:center">{{ empty_message }}</h1> </div> {% else %} <div class="row"> <div class="col-sm-8 col-sm-offset-2"> <table class="table"> <thead> <th>Item</th> <th>Quantity</th> <th>Price</th> <th></th> </thead> <tfoot> <th></th> <th></th> <th>Total:{{ cart.total }}</th> <th></th> </tfoot> {% for item in cart.cartitem_set.all %} <tr> <td>{{ item.product }} {% if item.variations.all %}<ul> {% for subitem in item.variations.all %} <li>{{ subitem.category|capfirst }}:{{ subitem.title|capfirst }}</li> {% endfor %} </ul>{% endif %}</td> <td>{{ item.quantity }}</td> <td>{{ item.product.price }}</td> <td><a href="{% url 'remove_from_cart' item.id %}">Remove</a></td> </tr {% endfor %} </table> </div> </div> {% endif %} {% endblock %} ''' my views.py--- ''' from django.shortcuts import render from .models import Cart,CartItem from django.http import HttpResponseRedirect from django.urls import reverse from app.models import Product,Variation def cart(request): try: the_id = request.session['cart_id'] except: the_id = None if the_id: cart = Cart.objects.get(id=the_id) context = {'cart':cart} else: empty_message = "you have notthing in your cart.Carry … -
Order object by field containing string value
I have a django model and a field representing an ip-address. I want order queryset of this model by ip-address value such "10.10.10.1" I do Model.objects.order_by("ip_address"), but I get this QuerySet["10.10.10.1", "10.10.10.11", "10.10.10.12", ...] I want this QuerySet["10.10.10.1", "10.10.10.2", "10.10.10.3", ...] I don't know how to do this. Anyone have any ideas?