Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Need to sort dict values and print highest value pair using Django Python
As i am using Python for backend and Django for frontend. Currently i am getting output in background as below from function: d={'Testcase1': {'hydra.c': 10,'clone.c':5}, 'Testcase2':{'hydra.c':337,'vendor.c':100 }, 'Testcase3':{'hydra.c':100,'vendor.c':80} 'Testcase4':{'vendor.c':89,'template.c':98,'temp.c':92}, 'Testcase5':{'vendor.c':83} 'Testcase6':{'template.c':34}....} for key,values in d.iteritems(): so=sorted(values.iteritems(),key=operator.itemgetter(1)) print(key,so[-1][0],so[-1][1]) for backend i'm getting correct output but how to implement this function in Django frontend {% for key,value in d.items() %} {% for k,v in sorted(value.iteritems(), key=lambda (k,v): (v,k)): <table> <tr> <td>{{ key }}</td> <td>{{ k[-1] }}</td> <td>{{ v[-1] }}</td> </tr> </table> -
How to add CSS class to django RadioSelect label?
how do i add css class for the auto generated label for a RadioSelect widget <div> {% for rdo in form.category_res %} <div class="custom-control custom-radio custom-control-inline"> {{ rdo }} </div> {% endfor %} </div> -
The view users.views.RegisterView didn't return an HttpResponse object. It returned None instead
I am using this code for a register form. But the post request doesn't work and give me an error : ValueError at /register/ The view users.views.RegisterView didn't return an HttpResponse object. It returned None instead. views.py class RegisterView(View): def get(self,request): register_form = RegisterForm() return render(request, 'register.html',{'register_form':register_form}) def post(self,request): register_form = RegisterForm(request.POST) if register_form.is_valid(): user_name = request.POST.get("email", "") user_psw = request.POST.get("password", "") user_profile=UserProfile() user_profile.username = user_name user_profile.email = user_name user_profile.password=make_password(user_psw) user_profile.save() send_register_email(user_name,"register") pass urls.py from django.contrib import admin from django.urls import path, include from django.views.generic import TemplateView import xadmin from users.views import LoginView , RegisterView import xadmin urlpatterns = [ path('xadmin/', xadmin.site.urls), path('',TemplateView.as_view(template_name="index.html"),name="index"), path('login/',LoginView.as_view(),name="login"), path('register/',RegisterView.as_view(),name="register"), path("captcha/", include('captcha.urls')) ] forms.py class RegisterForm(forms.Form): email = forms.EmailField(required=True) password = forms.CharField(required=True, min_length=5) captcha = CaptchaField(error_messages={"invalid":"please input correctly"}) register.html <div class="tab-form"> <form id="email_register_form" method="post" action="{% url 'register' %}" autocomplete="off"> <input type='hidden' name='csrfmiddlewaretoken' value='gTZljXgnpvxn0fKZ1XkWrM1PrCGSjiCZ' /> <div class="form-group marb20 "> <label>邮&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;箱</label> <input type="text" id="id_email" name="email" value="None" placeholder="请输入您的邮箱地址" /> </div> <div class="form-group marb8 "> <label>密&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;码</label> <input type="password" id="id_password" name="password" value="None" placeholder="请输入6-20位非中文字符密码" /> </div> <div class="form-group marb8 captcha1 "> <label>验&nbsp;证&nbsp;码</label> {{ register_form.captcha }} <img src="/captcha/image/2f3f82e5f7a054bf5caa93b9b0bb6cc308fb7011/" alt="captcha" class="captcha" /> <input id="id_captcha_0" name="captcha_0" type="hidden" value="2f3f82e5f7a054bf5caa93b9b0bb6cc308fb7011" /> <input autocomplete="off" id="id_captcha_1" name="captcha_1" type="text" /> </div> <div class="error btns" id="jsEmailTips"></div> <div class="auto-box marb8"> </div> … -
Django if function in html to set changes in selected option tag
when I use the django if function in the html template to set changes to the selected option tag, but nothing changes <form method="post"> <select name="name"> <option >--SELECT--</option> {% for job in all_pekerjaan%} <option value="{{job.id}}" {% if job.id == current_name %}selected="selected"{% endifequal %}> {{job.name}} </option> {% endfor %} </select> {% csrf_token %} <input type="submit" class="btn btn-success" value="submit" > </form> anyone know how to fix this issue? -
Django not displaying HTML template correctly
I am trying to load a test template using Django on Ubuntu. The template has loaded correctly in terms of errors. I downloaded a custom template from a website and I loaded up all of what it asked for: Jquery, Bootstrap and their own custom css also images and fonts. The site returns no errors in the console but it looks like this: When it supposed to look like this: The console returns no errors at all. The html files are practically the same except for the import statements for the files being replace with {% static 'css/mycssfiles.css' %} Any advice at all? -
How do you make a lowercase field in a django model?
With this method, I can make a field save as lowercase, but this does not change the field in the existing model (that is in memory). def get_prep_value(self, value): value = super(LowercaseField, self).get_prep_value(value) if value is not None: value = value.lower() return value I'm having a hard time figuring out how to force this field to lowercase without overriding save and doing the change there. But that splits the logic for this lowercase field. I'd like all of it in the field. What do I override so that setting this value forces lowercase in memory AND on in the DB? I don't want to change a form, I want all the lowercase logic contained inside the field class. -
show images uploaded by admin in html template
I am new to django and I saw solutions for my problem but none worked. I make admin upload images as you see in Item class in models.py : from django.db import models from django.contrib import admin class Customer (models.Model): username = models.CharField(max_length=500) email = models.CharField(max_length=1000 , unique=True) phone = models.IntegerField() address = models.CharField(max_length=3000) class Category(models.Model): category_title = models.CharField(max_length=100 , unique=True) def __str__(self): return self.category_title class Order (models.Model): time = models.DateTimeField(auto_now_add=True) total = models.IntegerField() created_by = models.ForeignKey(Customer, related_name='orders') class Item (models.Model): name = models.CharField(max_length=100 ,unique=True) details = models.CharField(max_length=1000) price = models.IntegerField() item_logo = models.ImageField(upload_to='res/static/res/images') category = models.ForeignKey(Category, related_name="items" ,on_delete= models.CASCADE) def __str__(self): return self.name class ItemInline(admin.TabularInline): model = Item class CategoryAdmin(admin.ModelAdmin): inlines = [ ItemInline, ] so how can I make those images appear in my HTML ( note: html code works fine but a small default image field appear instead of image ) : {% extends 'res/menu.html' %} {% block content %} <h1>hello</h1> <table class="table table-striped table-bordered" style="text-align: left ; border-color: black;" id="pizza_table"> <tbody> {% for item in items %} <td> {{ item.name }} <p>{{ item.details }}</p> </td> <td> <img src="{{item.item_logo}}"> </td> <td> </td> <td> <button type="button" class="btn btn-success" style="margin: 5px ;" onclick="additem('Seafood Pizza', 20 ) ;">Add</button> </td> {% … -
Django: Testing a CreateView that takes an argument from URL
I am using a CreateView with a custom form_valid function. On the test server, everything works fine. But as I started writing the unittests, the test for creating a model containing a foreign key is not passing. Any help or further questions would be greatly appreciated. I hope I formatted this to your guys' liking The classes are: class Parent(models.Model): name = models.CharField(max_length=10) class Child(models.Model): name = models.CharField(max_length=10) parent = models.ForeignKey(Father,on_delete=models.PROTECT) And in the urls.py we have the following URLs path('newparent/',views.AddNewParent.as_view(),name='new-parent'), path('parent/<int:parent_id>',views.ParentDetail.as_view(), name='parent-detail'), path('parent/<int:parent_id>/newchild',views.AddNewChild.as_view(), name='new-child') In views.py we have class AddNewParent(CreateView): model=Parent fields=['name'] class AddNewChild(CreateView): model=Child fields=['name'] def form_valid(self,form): form.instance.parent = Parent.objects.get(pk=self.kwargs['parent_id'] return super().form_valid(form) In tests.py, I have the following two tests class TestCreateViews(TestCase): def setUp(self): self.client = Client() def test_create_parent(self): createurl = reverse('new-parent') form_data = {'name':'John'} self.client.post(createurl,form_data) self.assertEqual(Parent.objects.last().name,'John') def test_create_child(self): p=Parent(name='John') p.save() createurl = reverse('new-child',args=[p.id]) form_data = {'name':'Dave'} self.client.post(createurl,form_data) self.assertEqual(Child.objects.last().parent_set.last().name,'John') The second test is failing to create a child instance in the database, and the HttpResponse that comes back is 200? This is a simplified case from a larger project I've been working on -
Annotate a queryset by a values queryset
I want to annotate a count of objects to a queryset, which I know how to do, but I want the objects counted to have their own filtering. This works well; first_model_qs = FirstModel.objects.filter(do a bunch of filtering) grouped_values_qs = first_model_qs.values('second_model').annotate(Count('pk')) So I now have a nice queryset with all the first_model counts grouped by second_model ids. Awesome. What I'ld like to do now is something like; secound_model_qs = SecondModel.objects.annotate(first_model_count = grouped_values_qs) And then be able to say secound_model_qs.first().first_model_count Is this possible? -
Django1.10: how to create 2 objects with foreign key relationship in one transaction
I have 2 models: class Vendor(models.Model): admin = models.ForeignKey(User) ... class User(models.Model): ... I want to create the user and vendor in one transaction: with transaction.atomic(): user = User(name="test") user.save() vendor = Vendor(admin=user) vendor.save() But I get error : ValueError: save() prohibited to prevent data loss due to unsaved related object 'admin'. How to fix this error? How to create these 2 objects in 1 transaction? -
efficient way to send a temporary message from admin to a specific user in django
i'm trying to send a temporary message/alert for a specific user on my app. I've managed to do it using this approach and i wanna know if there is an efficient/easier way to do it . models.py class Indar(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE , related_name='indars') content = models.CharField(max_length=120) start = models.DateField(auto_now=False, auto_now_add=False) end = models.DateField(auto_now=False, auto_now_add=False) views.py def home(request): qs = Indar.objects.filter(start__lte=timezone.now().date(),end__gte=timezone.now().date(),user=request.user) return render (request, 'home.html' , {'qs':qs}) home.html <div class="alert alert-warning" role="alert"> {% for obj in qs %} {{ obj.content }} {% endfor %} </div> -
Are ModelSerializers meant to be written on a per-view basis?
I am writing a Django app, which is huge and has a large number of API endpoints. This app uses DRF to serialize the information being sent to the frontend via JSON, and deserialize the information sent via JSON from the frontend. For ease of explaining my situation, let's consider a simplistic model. So let's say I have a model A. class A(models.Model): field1 = models.CharField(max_length=255) field2 = models.CharField(max_length=255) field3 = models.CharField(max_length=255) I have views for scenarios like these. create: User enters field1, based on which field2 and field3 will be populated and saved show: Only field2 will be shown on every model in the matching queryset show_full: Both field2 and field3 will be shown on every model in the matching queryset This brings me to my questions. Should I write one ModelSerializer each for all the views above? Or does DRF have some facility to specify model field names in the view itself? If serializers are meant to be written on a per-view basis, aren't serializers more tied to views than models? Thanks for helping me out. Neither the DRF documentation, nor any number of Google searches managed to solve my issue. -
Django Passing Multiple Views from Different Apps to the Same Template
I have a django shop application where all the Products are listed on one page via listview (no individual product pages). But my cart is rendered on a different app/template. When products are added to the cart they go to the other cart template. How can I combine the views into one? Thanks in advance. Carts App views.py from django.shortcuts import render, redirect from catalogue.models import Product from .models import Cart # Create your views here. def cart_home(request): cart_obj, new_obj = Cart.objects.new_or_get(request) return render(request, "carts/carts.html", {"cart": cart_obj}) def cart_update(request): product_id = request.POST.get('product_id') if product_id is not None: try: product_obj = Product.objects.get(id=product_id) except Product.DoesNotExist: print("Product is gone") return redirect("cart:home") cart_obj, new_obj = Cart.objects.new_or_get(request) if product_obj in cart_obj.products.all(): cart_obj.products.remove(product_obj) else: cart_obj.products.add(product_obj) return redirect("cart:home") This is views.py from Catalogue app from django.views.generic import ListView from django.shortcuts import render from . import models from .models import Product from carts.models import Cart class ProductListView(ListView): model = models.Product template_name = "catalogue/catalogue.html" def get_context_data(self, *args, **kwargs): context = super(ProductListView, self).get_context_data(*args, **kwargs) cart_obj, new_obj = Cart.objects.new_or_get(self.request) context['cart'] = cart_obj cat_appetizers = Product.objects.filter(category__name='Appetizers') cat_alltimefavourites = Product.objects.filter(category__name='All Time Favourites') cat_baltidishes = Product.objects.filter(category__name='Balti Dishes') cat_biryanidishes = Product.objects.filter(category__name='Biryani Dishes') cat_bread = Product.objects.filter(category__name='Bread') cat_drinks = Product.objects.filter(category__name='Drinks') cat_grillroastdishes = Product.objects.filter(category__name='Grill & Roast Dishes') cat_housespecials … -
Inline Disabling
I am disabling a button inline using Django conditions <button {% if order.return_available == True %} disabled="disabled" {% endif%} class="class1 class2 {% if order.return_available == True %} disabled {% endif %}"> Problem is that when I play around with the Chrome Dev Tools and manually remove those inline disables, it removes the disable formatting and I am able to once again trigger the POST for the form and furthermore it actually updates the database and performs the action of the button. Will this be the same for when deployed and for the end user? Do I need to change this or will the disable be a hard feature once deployed? -
Email setup for Django in AWS using SES
I am trying to setup email capability for my Django website on AWS using Elastic Beanstalk. I have activated Simple Email Service (SES) and verified two email address for testing. Furthermore, I have followed instruction to install and setup Dango-SES. However, when I try to sign up in my website pretending to be a new user I receive this error in my browser: SESAddressNotVerifiedError: 400 Email address is not verified. That is confusing because I am using verified email to sign up (email verified by SES). I am using django-allauth for authentication and registration. Can anyone give an advice on this? Thank you very much! Regards -
Relationships between models (Django)
I have 2 models venta and detalleventa which is fine since a sale can have many details class Venta(models.Model): cliente = models.ForeignKey(Cliente,on_delete=models.CASCADE,verbose_name='Cliente') fecha = models.DateField(auto_now_add=True) descripcion = models.CharField(max_length=300, blank=True, verbose_name='Detalle del pedido') total = models.DecimalField(decimal_places=2, max_digits=7, verbose_name='Total de la venta') def __str__(self): return '{}'.format(self.id) class DetalleVenta(models.Model): producto = models.ForeignKey(Producto,on_delete=models.CASCADE,verbose_name='Producto') cantidad = models.IntegerField(verbose_name='Cantidad') venta = models.ForeignKey(Venta,on_delete=models.CASCADE, verbose_name='Venta') def __str__(self): return '{} - {}'.format(self.venta,self.producto) How do I access detail from venta if the foreign key has detalle? because if there are several detalles you should not edit one by one if you do not edit the venta that contains all the detalles So far I can edit but through its detalle: class VentaUpdate(UpdateView): model = DetalleVenta second_model = Venta template_name = 'venta/venta_form.html' form_class = DetalleForm second_form_class = VentaForm success_url = reverse_lazy('venta:ventas_listar') def get_context_data(self, **kwargs): context = super(VentaUpdate, self).get_context_data(**kwargs) pk = self.kwargs.get('pk', 0) detalle = self.model.objects.get(id=pk) venta = self.second_model.objects.get(id=detalle.venta_id) if 'form' not in context: context['form'] = self.form_class() if 'form2' not in context: context['form2'] = self.second_form_class(instance=venta) context['id'] = pk return context def post(self, request, *args, **kwargs): self.object = self.get_object id_detalle = kwargs['pk'] detalle = self.model.objects.get(id=id_detalle) venta = self.second_model.objects.get(id=detalle.venta_id) form = self.form_class(request.POST, instance=detalle) form2 = self.second_form_class(request.POST, instance=venta) if form.is_valid() and form2.is_valid(): form.save() form2.save() return HttpResponseRedirect(self.get_success_url()) … -
How do I call requests.get() from my own Django views to my Django Rest Framework?
Instead of trying to use the serializer class in my views, I'm trying to just do requests.get(<url for DRF>) and pull the json data, but I cannot seem to do that at all. It worked on my localhost:8000 when testing, but does not work on my production server on ec2. This is what I've tried: My django application is currently running on https:// So I've added SECURE_SSL_REDIRECT = False SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTOCOL', 'https') into my settings.py. I have tried requests.get(url=<url>, verify=False) I've tried logging the specific requests.get,but I found to see that my code does not even hit that line of code. I've used PyCharm to do remote debugging on http://, and that worked completely fine. The url that I use requests.get(url='https://<host>/api/users/', verify=False) note that there is a https:// when calling this url. I've tried using requests.get(url='http://<host>/api/users/), but I get a 404 response. But, if I use the same http:// on my PyCharm debug server, it works. Please don't suggest to just use the Serializers or Models. -
Django- Unable to access values from DetailView model object
I am trying to create a chat application that has two models: one holding the chat room names and another holding the messages. from django.db import models class ChatRoom(models.Model): name = models.CharField(max_length=256) professor = models.CharField(max_length=256) def __str__(self): return self.name class MessagesInChat(models.Model): room_name = models.ForeignKey(ChatRoom, on_delete=models.CASCADE, related_name="message_room") user_name = models.CharField(max_length=256) message = models.TextField(blank=True, null=True) def __str__(self): return str(self.user_name) However, whenever I try to access these fields from the template, I get the following error: No messages in chat found matching the query I did fill the models with dummy values before trying this. The following are my views.py file and template I'm using: views.py from django.views.generic import DetailView, ListView from chat import models class Chats(ListView): template_name = "chat_list.html" context_object_name = "chat_list" model = models.ChatRoom def get_queryset(self): return models.ChatRoom.objects.order_by("name") class ChatPage(DetailView): model = models.MessagesInChat template_name = "chat.html" context_object_name = "chat_page" Template <!-- 'm' stands for message --> {%for m in chat_page.message_room.all%} <div class="p-3 mb-2 bg-light text-dark" style="margin-top:20px;">{{m.message}}</div> <div class="p-3 mb-2 bg-success text-white" style="margin-top:20px;">{{m.message}}</div> {%endfor%} Also the urls.py file: from django.contrib import admin from django.conf.urls import url from chat.views import ChatPage, Chats urlpatterns = [ url('admin/', admin.site.urls), url(r'^$', Chats.as_view(), name="chat_page"), url(r'^(?P<pk>[-\w]+)/$', ChatPage.as_view(), name="chats") ] This problem has been bugging me for a while. … -
If condition is not working in Inner Loop in django templates
I don't know what is the problem and I've been stuck here for hours. There maybe duplicate questions but none of them could get me out of this. I am using an if condition in the inner loop to check if the attribute of inner is equal to the outer loop but if condition is never true even the data is same. I've printed the data individually, both attributes print the data mean data is correct. But when I use if condition it goes to else Data Here's the data I'm working with: activityy.activity_name = [Table Tennis,Swimming Pool, Football ] slot.activity = [Table Tennis,Table Tennis,Table Tennis,Table Tennis,Swimming Pool, Football] activities.html {% for activityy in all_activities%} <div style="margin-left: 450px; padding: 15px; border-radius: 5px; background-color: #dfdfdf;height: 150px; width: 800px; margin-top: 20px; text-align: center"> {% for slot in all_slots %} {% if slot.activity == activityy.activity_name %} <div style="background-color: #3a589a; padding: 15px; width: 120px; height: 120px; float: left; border-radius: 5px;"> <span style="color: #f1f1f1; font-size: 20px;"> {{ activityy.activity_name}}</span><br> </div> {% else %} <div style="background-color: #589a; padding: 15px; width: 120px; height: 120px; float: left; border-radius: 5px;"> <span style="color: #f1f1f1; font-size: 20px;"> {{ slot.activity}}</span><br> </div> {% endif %} {% endfor %} </div> {% endfor %} Views.py def … -
serializer custom queryset field
Is there a way to create a custom field in a serializer that calls a queryset ? Here is what I am trying to do: I have a serializer for Employee and I want to have "last_attendance" field included. class EmployeeSerializer(serializers.ModelSerializer): class Meta: model = Employee fields = ("id", "username", "first_name", "last_name") I would like to add one more field "last_attendance". Which is a queryset like this: "last_attendance" = Attendance.objects.filter(employee_id = idofthatemployee).last() -
DRF "field is required" error on POST request?
curl --user testuser:passwordz -d '{"name":"testplatform"}' -X POST http://localhost:8080/api/v1/platforms error {"name":["This field is required."]}% views.py class platform_list(APIView): def get(self, request, format=None): query = request.GET.get('name') if query: platforms = Platform.objects.filter(name=query) else: platforms = Platform.objects.all() serializer = PlatformSerializer(platforms, many=True) return Response(serializer.data) def post(self, request, format=None): serializer = PlatformSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) I know the auth works because if I type in wrong user or pass the error changes to "invalid credentials" . Why am I getting the field required error though? -
Pycharm permanently blinking "Updating indices..." in statusbar and html file
windows10 pycharm version:2017.31build number:py-173.3942.36 python3.6.3 anaconda3 django 2.0.1 pycharm blinking Hello I pasted a video link. These flashes only occur when HTML files are present. In python only case, it did not happen when anaconda only project. It happens when django's project. Deleting HTML files stops them. -
Image size warnings and what cropping field means in django-image-cropping
I'm trying to use django-image-cropping app on my website. I've set it up with size warnings on. Build in warnings are not good enough for me - as I understand if I try use size smaller than defined frame color in cutting tool is changing but nothing more. I'd like to check sizes in view but cleaned_data contains only cropping value which is string with 4 numbers in it. Does anybody know what those 4 numbers describe? Or maybe there is another way to prevent cropping not allowed sizes? -
taggit_templatetags2 exclude count
I'm using django-taggit to manage my tag. I want to include a list of used tags with the indication of how many times each of them has been used. To do so I'm using taggit_templatetags2. my template.html: {% load taggit_templatetags2_tags %} {% get_taglist as tags for 'blog.post' %} {% for tag in tags %} {% if tag.slug != 'draft' and tag.slug != 'retired' %} <h4 style="text-align:center"><a href="{% url 'blog:post_list_by_tag' tag.slug %}"> {{ tag }} ({{ tag.num_times }}) </a></h4> {% endif %} {% endfor %} But I want to exclude from the count all the tags of the draft posts and of the retired posts. I do not want just to exclude the tags 'draft' and 'retired' (I'm already doing that) but even the other tags that such posts can have. How can I do that? Probably I have to mess with the taggit_templatetags2 code... Here some code: @register.tag class GetTagList(TaggitBaseTag): name = 'get_taglist' def get_value(self, context, varname, forvar, limit=settings.LIMIT, order_by=settings.TAG_LIST_ORDER_BY): # TODO: remove default value for limit, report a bug in the application # django-classy-tags, the default value does not work queryset = get_queryset( forvar, settings.TAGGED_ITEM_MODEL, settings.TAG_MODEL) queryset = queryset.order_by(order_by) context[varname] = queryset if limit: queryset = queryset[:limit] return '' … -
How to change DRF to use a Response from a schema?
Is it possible to change the Django Rest Framework to use a Response from a schema? For example, a GET using the standard DRF will output: { "count": 0, "next": null, "previous": null, "results": [] } Where I would like it to output { "meta_stuff": { "License": "MIT" }, "data": [] } Where results=data and an extra ). Would I need to customise DRF or can a swagger.JSON schema be used to achieve this?