Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can i get the pk from a cloned model instance i in form_valid to use in get_success_url in an UpdateView? https://bpaste.net/F76Q
class DomainRegistrationItemUpdateView(UpdateView): model = DomainRegistrationItem form_class = DomainAddYearsForm template_name = "add_years.html" def get_context_data(self, *args, **kwargs): context = super(DomainRegistrationItemUpdateView, self).get_context_data(**kwargs) # tld_ppy Top Level Domain Price Per Year context['tld_ppy'] = TLD.objects.get( name='.%s' % (self.kwargs['domain_name'].split('.')[1])).yearly_price return context def get_object(self, queryset=None): return DomainRegistrationItem.objects.get(domain=self.kwargs['domain_name'], purchased=True) def get_success_url(self): split_dn = self.kwargs['domain_name'].split('.') namespace = split_dn[0] sld = split_dn[1] return reverse("domain_registraiton_item_detail", kwargs={ "pk": self.kwargs['pk'], 'namespace': namespace, 'second_level_domain': sld}) def form_valid(self, form): f = form.save(commit=False) working_dri = DomainRegistrationItem.objects.get(domain=self.kwargs['domain_name']) working_dri.pk = None working_dri.save() working_dri.purchased = False working_dri.years = f.years f.save() return super(DomainRegistrationItemCreateView, self).form_valid(form) The working_dri code is code that clones a DomainRegistrationItem under consideration by the view. I want to get the pk from working_dri to usee in get_success_url. How can I do this? Thanks in advance for any and all help. -
I have a Django-MySQL back end, which web-server provider can handle this?
The day has finally come where I have finished the front end of my mobile app. I completed the back end, a Django-API connected to MySQL, prior to beginning the front end. Now I need to push my backend onto a server so that I can publish my app. Which server provider can handle MySQL/Django? Thank you. -
Maintain AJAX received data in the browser's back
How do I maintain the ajax received data when the user navigates back/forward in the browser? I have Python, Django app, Jquery for ajax. When I receive data from ajax I populate that in a div. When I move to another page and return 'back' on chrome browser the data is lost and I have to make the ajax call again. -
Django: How to use custom url name instead of 'password_reset_done' for password reset route in urls.py?
I am creating my first Django project and implementing password-reset functionality. So I know that I have to configure the URLs with the following name and use inbuilt views. password_reset password_reset_done password_reset_confirm password_reset_complete But I have created a seaparate application accounts to handle the authentication part and I am following a convention of prepending application name for naming application-specific URLs. So all the URLs in the accounts app have accounts- prepended to them. path('signup/', views.signup, name='accounts-signup'), path('logout/', auth_views.LogoutView.as_view(), name='accounts-logout'), PROBLEM: But while creating password reset URLs, I have to use predefined names as mentioned above. Is there a way to use a custom name in place of these predefined names, or any way to override these in settings.py I checked docs for settings.py but could not find anything. EXPECTATION: I want to be able to assign custom names like accounts-password_reset and accounts-password_reset_done. The app works fine with predefined names, but what If I want to create another app in the same project with a separate authentication system and separate routes. Wouldn't the same name for reset password route can cause namespace collisions in other apps? -
Can I add a Color Picker to Django Forms
I tried using the django-colorfield module which works great for the admin page but I cannot get it to render the widget in the actual forms. Below is what I have tried so far and all I get on the form is a CharField with the default value as text. I am open to every and any suggestions but I do not want to use the RGB color picker that html5 has if possible. This is in my forms.py from django import forms from .models import Automation from colorfield.fields import ColorWidget def get_automation_form(content, data=None, files=None): songs = content[2].split(', ') music_choices = [] for song in songs: song = song.replace(' ', '-') song_filename = f'Music/{song}.wav' music_choices.append((song_filename, song)) class AutomationForm(forms.ModelForm): music_selection = forms.CharField(widget=forms.Select(choices=music_choices)) class Meta: model = Automation fields = content[0] labels = content[1] widgets = { 'color1': forms.CharField(widget=ColorWidget()), 'color2': forms.CharField(widget=ColorWidget()), 'color3': forms.CharField(widget=ColorWidget()), 'color4': forms.CharField(widget=ColorWidget()), 'color5': forms.CharField(widget=ColorWidget()), } def __init__(self, *args, **kwargs): super(AutomationForm, self).__init__(data=data, files=files,*args, **kwargs) return AutomationForm() This is in my models.py from django.db import models from django.contrib.auth.models import User from colorfield.fields import ColorField class Automation(models.Model): timestamp = models.DateTimeField(auto_now=True) user = models.ForeignKey(User, on_delete=models.CASCADE, default="", blank=True) text_field01 = models.CharField(max_length=50, default="") text_field02 = models.CharField(max_length=50, default="") text_field03 = models.CharField(max_length=50, default="") text_field04 = models.CharField(max_length=50, default="") … -
Using a Wagtail "ChoiceBlock" with dynamic choices rather than a hardcoded list
We have a setup with a Blog model that has a manytomany relation for BlogPageCategory, and we have a "recent blog posts" streamfield block that lets you specify whether to show cards for X latest blog posts, or X latest blog posts from a specific category. As such, we started with the following code: from wagtail.core import blocks class RecentBlogEntries(blocks.StructBlock): title = blocks.CharBlock( required=True, ) category_filter = blocks.ChoiceBlock( label='Filter by Category', required=False, choices=[ ('all', 'All'), ('First Category', 'First Category'), ('...',. '...'), ], ) ... But hardcoding the categories is kind of silly, and being able to pick them from "what the list is, right now, based on the CMS data for BlogPageCategory" would be far more convenient. However, the following code (of course) turns into an equally hardcoded migration: from wagtail.core import blocks from ... import BlogPageCategory class RecentBlogEntries(blocks.StructBlock): title = blocks.CharBlock( required=True, ) choices = [ (cat.name, cat.name) for cat in BlogPageCategory.objects.all()] choices.sort() choices.insert(0, ('all', 'All')) category_filter = blocks.ChoiceBlock( label='Filter by Category', required=False, choices=choices, ) ... Is there any way to make this a dynamic value instead of a list that is fixed by makemigrations? -
How to use post_save signal with custom user model extended with AbstractBaseUser
There are two apps in my ecommerce website and i have been following a particular tutorial on youtube. In the course, the guy used django-allauth package for login purposes. I followed the course along but I created custom user model exending AbstracBaseUser class in account app. I created another app called product where I handled all the ecommerce logics. Here's the code: models.py (account) class MyAccountManager(BaseUserManager): def create_user(self, email, username, first_name, last_name, gstin_no, phone_no, password=None): if not email: raise ValueError("Users must have an email address") if not username: raise ValueError("Users must have a username") if not first_name: raise ValueError("Users must have First Name") if not last_name: raise ValueError("Users must have Last Name") if not gstin_no: raise ValueError("Users must have a valid GSTIN Number") if not phone_no: raise ValueError("Users must have a valid Phone Number") user = self.model( email=self.normalize_email(email), username=username, first_name=first_name, last_name=last_name, gstin_no=gstin_no, phone_no=phone_no, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, username, first_name, last_name, gstin_no, phone_no, password): user = self.create_user( email=self.normalize_email(email), password=password, username=username, first_name=first_name, last_name=last_name, gstin_no=gstin_no, phone_no=phone_no, ) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class Account(AbstractBaseUser): email = models.EmailField(verbose_name="email", max_length=60, unique=True) username = models.CharField(max_length=30, unique=True) date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True) last_login = models.DateTimeField(verbose_name='last login', … -
Template tags not rendering in HTML
I am building a skeleton django website, but can't manage to get the template tags to render for what I thought would be a simple test. Currently, the template tags just appear as text (i.e. it just says '{{ test }} and end' when I look at the website. I am sure the problem is obvious, but I am not very experienced with django. I am not running into any errors though, so if there is any debugging advice that would be helpful. Please let me know if I have missed any key information. views.py from django.shortcuts import render from .models import Forms def home(request): return render(request, 'kb/home.html', {'test': 'begining'}) home.html <html> <head> <title>Kinbank</title> </head> <body> <p>Hi there!</p> <p>{{ test }} and end </p> </body> </html> urls.py from django.urls import path from django.conf.urls import url from . import views urlpatterns = [ path('', views.home, name='home'), ] -
Python django.How can I enter the text selected by the user with a drop-down element in the name_znat field
There is an html form with dropdown elements: <form method = "POST" action = "{% url 'create_group_handler'%}"> <select name = "select"> <! - Add an identifier here instead of using 'name' -> <option value = "value1"> Value 1 </ option> <option value = "value2" selected> Value 2 </ option> <option value = "value3"> Value 3 </ option> </ select> </ form> And there is a Python django model: Znat Class (models.Model): name_znat = models.CharField ('Name znat', max_length = 200) Suppose that the user selects a drop-down element with the text "Value 2". How can I enter the text selected by the user with a drop-down element in the name_znat field -
Django channels freezes
I'm trying to create a Django Channels consumer which receives some data in real time from a RabbitMQ queue and then sends this data to a frontend, in order to let users have real-time data. Here is my basic consumer: class EchoConsumer(AsyncConsumer): async def websocket_connect(self, event): print("connected", event) connection = pika.BlockingConnection( pika.ConnectionParameters(host='localhost')) channel = connection.channel() channel.queue_declare(queue='Test') def callback(ch, method, properties, body): print(" [x] Received %r" % body) channel.basic_consume( queue='Test', on_message_callback=callback, auto_ack=True) print(' [*] Waiting for messages. To exit press CTRL+C') await self.send({ "type": "websocket.accept" }) await channel.start_consuming() async def websocket_receive(self, event): print("received", event) # Echo the same received payload async def websocket_disconnect(self, event): print("disconnected", event) And here is my Javascript code: <script> // websocket scripts var loc = window.location var wsStart = 'ws://' + window.location.host + window.location.pathname var endpoint = wsStart + loc.host + loc.pathname var socket = new WebSocket(endpoint) if (loc.protocol == 'https:'){ wsStart = 'wss://' } socket.onmessage = function(e){ console.log("message", e) } socket.onopen = function(e){ console.log("message", e) } socket.onerror = function(e){ console.log("message", e) } socket.onclose = function(e){ console.log("message", e) } </script> The problem with this code is that, altough in my console i will see the queue waiting for data, on my HTML page i won't see any … -
Check the instance of a Mocked method called once
My function looks for a Actor object in the database and calls its do_something() method with a passed argument. from my_app.models import Actor def my_function(id, stuff): actor = Actor.objects.get(id=id) return actor.do_something(stuff) I want my unit test to check two things : 1. my_function finds the Actor I want. 2. my_function calls the actor's do_something method as expected. from unittest import mock from django.test import TestCase from my_app.models import Actor from my_app.views import my_function class ViewsTestCase(TestCase): @classmethod def setUpTestData(cls): self.actor = Actor.objects.create(id=42, name='John') def test_my_function(self): with mock.patch.object(Actor, 'do_something') as mock_do: my_function(id=42, stuff='a-short-string') mock_do.assert_called_once_with('a-short-string') This works to make sure my_function called do_something like I wanted but I don't know how to be sure it found the Actor I asked him to find. This test would pass even if my_function found the wrong actor. Is there any way to check that ? -
Django Admin: How to set the background-color for a datafield
I have a choice datafield and in the admin page I want to highlight its value with a background-color: YES = green NO = red I can set the background-color for a function field (see also image): fields = ['_kw', 'status'] readonly_fields = ['_kw'] def _kw(self, obj): return mark_safe('<span class="{}">{}</span>'.format(obj.status, obj.kw)) class Media: css = { 'all': ('myapp/admin.css',) } But I dont know how to achieve this with a datafield. Any ideas? If possible, I dont want to customize the admin-template or use a 3rd party app. my admin page -
Django-xhtml2pdf and static css files
So I've encountred a problem with Django and the xhtml2pdf module. I am trying to create PDFs from my pdf.html template which contains UNICODE characters which get displayed as ■■■■ in the PDF files. I tried to use CSS in the html file directly or in a separate file but no matter what i try i can't seem to figure it out. My PDF.html file: {% load static %} <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <style> {% include "pdfstylefonts.css" %} </style> <link rel='stylesheet' href="{% static 'pdfstyle.css' %}"/> </head> <body> <h1>árvíztűrő tükörfúrógép</h1> </body> </html> My PDFSTYLEFONTS.CSS {% load static %} @font-face { font-family: "Calibri"; src: url({% static "fonts/calibri.ttf" %}); } @font-face { font-family: "Calibri"; src: url({% static "fonts/calibrib.ttf" %}); font-weight: bold; } @font-face { font-family: "Calibri"; src: url({% static "fonts/calibrii.ttf" %}); font-style: italic, oblique; } @font-face { font-family: "Calibri"; src: url({% static "fonts/calibriz.ttf" %}); font-weight: bold; font-style: italic, oblique; } My PDFSTYLE.CSS h1 { color: blue; } *, html { font-family: "Calibri"; font-size:11pt; color: red; } My View from views.py def pdf_view(request): adat = get_object_or_404(Egyenleg,user=request.user) template = get_template('pdf.html') context = {'Data':adat} html = template.render(context) pdf = render_to_pdf('pdf.html', context) if pdf: response = HttpResponse(pdf, content_type='application/pdf') filename = "PDF%s.pdf" %("12341231") content = … -
How to fetch parent child hierarchy using django rest-framework
I am new to Django rest-framework. I am writing an API to fetch details in a parent-child hierarchy. Following is my code; models.py class ConfigAttributes(models.Model): attr_set_name = models.CharField(max_length=32) product_type = models.CharField(max_length=32) class ProductInfo(models.Model): config_attr = models.ForeignKey(ConfigAttributes, on_delete=models.CASCADE) product_name = models.CharField(max_length=32) class AttributeDetails(models.Model): product_info = models.ForeignKey(ProductInfo, on_delete=models.CASCADE) attribute_name = models.CharField(max_length=32) serializers.py class ConfigAttributesSerializer(serializers.ModelSerializer): class Meta: model = ConfigAttributes fields = ['id', 'attr_set_name', 'product_type'] class ProductInfoSerializer(serializers.ModelSerializer): class Meta: model = ProductInfo fields = ['id', 'product_name', 'config_attr_id'] class AttributeDetailsSerializer(serializers.ModelSerializer): class Meta: model = AttributeDetails fields = ['id', 'attribute_name', 'product_info_id'] views.py class ConfigAttributesViewSet(viewsets.ModelViewSet): queryset = ConfigAttributes.objects.all() serializer_class = ConfigAttributesSerializer class ProductInfoViewSet(viewsets.ModelViewSet): queryset = ProductInfo.objects.all() serializer_class = ProductInfoSerializer class AttributeDetailsViewSet(viewsets.ModelViewSet): queryset = AttributeDetails.objects.all() serializer_class = AttributeDetailsSerializer and app/urls.py router = routers.DefaultRouter() router.register('config', ConfigAttributesViewSet) router.register('product', ProductInfoViewSet) router.register('attr', AttributeDetailsViewSet) urlpatterns = [ path('', include(router.urls)), ] When I call the API, my required hierarchy and output is; [ { "attr_set_name" : "abc", "product_type" : "efg", "product_info" : { "product_name" : "hij", "attribute_details" : { "attribute_name" : "klm" } } } ] What are the changes need to done in the files to get the above output in hierarchy (I am using Postman to check my APIs). Thank you for the help. -
Export csv from Django Detail View
I am trying to export data from a browser in a Django detailview. The DetailView is of the model OsmoClient, and the data I would like to export is in the model FinancialData, which is linked to OsmoClient by foreignkey. models.py class OsmoClient(models.Model): created = models.DateTimeField(auto_now_add=True) client_code = models.CharField(max_length=250, blank=True) osmo_client_ref = models.CharField(max_length=250, blank=True) def __str__(self): return self.client_code def get_absolute_url(self): #used to create a unique URL page for each object return reverse('osmoclient-detail',args=[str(self.id)]) def get_fields(self): #Needed so that we can iterate over the fields in the html view, rather than typing them out. return [(field.verbose_name, field.value_from_object(self)) for field in self.__class__._meta.fields] class FinancialData(models.Model): osmo_client = models.ForeignKey(OsmoClient, on_delete=models.CASCADE) bank_balance = models.IntegerField() sales_balance = models.IntegerField() daily_movement_in_sales = models.IntegerField() trade_debtors_balance = models.IntegerField() trade_creditors_balance = models.IntegerField() date_created = models.DateTimeField(auto_now_add = True) class Meta: verbose_name_plural = "Financial Data" unique_together = ['osmo_client', 'date_created'] #Needed so that each client can only have one set of financial data per day ordering = ['osmo_client'] def __str__(self): return str(self.osmo_client) + str(self.date_created) def get_absolute_url(self): #Used to generate a unique URL page for each object return reverse('financialdata-detail', args=[str(self.id)]) def get_fields(self): #Needed so that we can iterate over the fields in the html view, rather than typing them out. return [(field.verbose_name, field.value_from_object(self)) for field in … -
Django get_context_data overrides get_object
Django 3 Python 3.8 In a class based detail view, why does the get_context_data function override the get_object? I have a Detail view in which I want to look at an item {{ object }} but I also want to add a list to the template. I created a get_context_data and returned {"fields": [1,2]} however when I went to the template, I could run {% for x in fields %} {{ x }} {% endfor %} but now {{ object }} returned blank! How can I use both the get_object and the get_context_data or should i put the object in the context? Thanks -
How to send an email using django and ajax
Hello I'm working on a Django contact form that enables a user to send an email, previously the email was being sent but the page was reloading so decided to use ajax Here's my javascript code, the ajax code $('.menu').click(function(){ $('.toggle').toggleClass('active'); }) $(document).on('submit', '#contact_form', function(e){ e.preventDefault(); $.ajax({ type:'POST', url:'/contact', data:{ from_email:$('#id_from_email').val(), subject:$('#div_id_subject').val(), message:$('#div_id_message').val(), csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val() }, success:function(){ alert("Message sent succsessfuly") } }) }) }); This is my views, getting the data and sending email if request.method == 'GET': form = ContactForm() else: form = ContactForm(request.POST or None) if form.is_valid(): subject = form.cleaned_data['subject'] from_email = form.cleaned_data['from_email'] message = form.cleaned_data['message'] reply_to=[from_email] msg_mail = str(message) + " " + str(from_email) try: send_mail( subject, message, from_email, ['kimkidati@gmail.com'], reply_to, ) except BadHeaderError: return HttpResponse('Invalid header found.') messages.add_message(request, messages.SUCCESS, 'Email sent successfully.') return render(request, "contact.html", {'form': form,}) My template, here is my django form where i collect the user message and email <h1>Contact Us</h1> {% if message %} {% for message in messages %} <p class="text-black mt-5 pt-5">{{message}}</p> {% endfor %} {% endif %} <form id="contact_form" method="POST" data-url='/contact'> {% csrf_token %} <p>{{form|crispy}}</p> <div class="form-actions mb-5"> <button class="btn btn-primary btn-sm" type="submit">Send Message</button> </div> </form> </div> ``` **Also had an issue with the email which does not specify who … -
MySQL connection pooling in Python2.7 doesn't work as expected. Facing issue with close() function of connection pool
I have taken the python sample code for MySQL Connection pool and tried to execute it with django framework. I'm able to execute the queries and retrieve the data if I don't close the cursor and connection object. When I call close() function connection object it's failing with following error, Please help me to solve this. ProgrammingError at /settings 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO) Method: GET Request URL: http://sample.app.com/settings Django Version: 1.11.5 Exception Type: ProgrammingError Exception Value: 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO) Exception Location: venv/local/lib/python2.7/site-packages/mysql/connector/connection.py in _auth_switch_request, line 256 Python Executable: venv/bin/python2 Python Version: 2.7.17 The code which I'm using, Coding in bold are creating the issue. If don't close connection, its working fine. when i close it doesn't work and throws an error. db_pool.py import mysql.connector.pooling dbconfig = { "host":"127.0.0.1", "port":"3306", "user":"root", "password":"root", "database":"test", } class MySQLPool(object): """ create a pool when connect mysql. """ def __init__(self, host="127.0.0.1", port="3306", user="root", password="root", database="test", pool_name="mypool", pool_size=3): res = {} self._host = host self._port = port self._user = user self._password = password self._database = database res["host"] = self._host res["port"] = self._port res["user"] = self._user res["password"] = self._password res["database"] = self._database self.dbconfig = … -
Django AJAX not updated after POST was called
I have this fat GET request in ajax . Is this GET request in some way q bad practice considering the looping of elements? let pages = 0; $.ajax({ url: '/posts/', method: 'GET', dataType: 'json', success: function (data) { let totalObjects = Object.keys(data.posts).length.toString(); # check how much pages should be displayed based on data length let rows = ''; data.posts.forEach(post => { rows += '<tr class="postTable" style="display: none;">' + '<th scope="row"><input type="checkbox" aria-label="Checkbox" style="display: none"></row>' + '<td class="tm-product-name"><a href="' + '/posts/' + post.slug + '/edit/">' + post.title + ' </a></td>' + '<td class="text-center">145</td>' + '<td class="text-center">' + post.total_likes + '</td>' + '<td>' + post.created_at + '</td>' + '<td><i class="fas fa-trash-alt tm-trash-icon" id="delete-icon" data-id="'+ post.slug + '"></i></td>' + '</tr>'; }); $('tbody').append(rows); let current_page = ''; let tables = document.getElementsByClassName('postTable'); $('#pagination-test').twbsPagination({ totalPages: pages, visiblePages: 5, onPageClick: function (event, page) { console.log('ALARMM'); current_page = page; console.log('PAGE Changed'); console.log('Page: ' + current_page); switch (current_page) { # here i'm looping all the elements via switch case for pagination. } }, }); } }); ajax POST $(document).on('click','tr[class="postTable"] td i[id="delete-icon"]' ,function () { let action = confirm('Are you sure you want to delete this post?'); let slug = $(this).attr('data-id'); console.log(slug); let url = '/posts/' + slug + … -
GAE production + Django + Gunicorn Error: HaltServer 'Worker failed to boot.' 3
I run my Django project on localhost by 'python manage.py runserver' - it works. I deploy it on Google App Engine - on xxx.appspot.com it print 502 Bad Gateway/by Ngnix and raise followed: gunicorn.errors.HaltServer: Traceback (most recent call last): File "/env/bin/gunicorn", line 10, in <module> sys.exit(run()) File "/env/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py", line 58, in run WSGIApplication("%(prog)s [OPTIONS] [APP_MODULE]").run() File "/env/lib/python3.7/site-packages/gunicorn/app/base.py", line 228, in run super().run() File "/env/lib/python3.7/site-packages/gunicorn/app/base.py", line 72, in run Arbiter(self).run() File "/env/lib/python3.7/site-packages/gunicorn/arbiter.py", line 229, in run self.halt(reason=inst.reason, exit_status=inst.exit_status) File "/env/lib/python3.7/site-packages/gunicorn/arbiter.py", line 342, in halt self.stop() File "/env/lib/python3.7/site-packages/gunicorn/arbiter.py", line 380, in stop and not self.cfg.reuse_port File "/env/lib/python3.7/site-packages/gunicorn/config.py", line 201, in reuse_port @property File "/env/lib/python3.7/site-packages/gunicorn/arbiter.py", line 242, in handle_chld self.reap_workers() File "/env/lib/python3.7/site-packages/gunicorn/arbiter.py", line 525, in reap_workers raise HaltServer(reason, self.WORKER_BOOT_ERROR) gunicorn.errors.HaltServer: <HaltServer 'Worker failed to boot.' 3> Python 37 Django 2.1.14 I`m first time with Django&GAE, pleese help -
How to create a child object in Serializer Django Rest?
I have a task, I need to return this json object here: { "id": "99999999", "point": "11111111", "name": "some name", "quantity": { "needed": "10", "done": "2", }, } I must have the quantity field as a child object, but in the Django model quantity_needed and quantity_done must not be child objects. Here is the code: # model.py class NeedModel(models.Model): article = models.ForeignKey(ArticleModel, on_delete=models.CASCADE) point = models.ForeignKey(PointModel, verbose_name="Hospital", on_delete=models.CASCADE) quantity_needed = models.PositiveIntegerField(default=0) quantity_done = models.PositiveIntegerField(default=0) I tried to change this using the to_representation method, here's what my code looks like: # serializer.py class NeedsSerializer(ModelSerializer): class Meta: model = NeedModel fields = ('id', 'point') def to_representation(self, instance): data = super(NeedsSerializer, self).to_representation(instance) data['name'] = instance.article.name data['quantity'] = { 'needed': instance.quantity_needed, 'done': instance.quantity_done, }, return data But as a result, I get a quantity field with a list that contains the object. How to get rid of this list? { "id": 6, "point": 4, "name": "Бинт гіпсовий 20см х2,7м", "quantity": [ { "needed": 12, "done": 0 } ], }, -
Django rest framework model is not visible in admin site
I'm working on a simple DRF API and I can't seem to access one of my many models from the admin site, although I can access some models from the same Application, please help! project/app/models.py looks something like this: class ImportantModel(models.Model): name = # character field relation1 = # foreign key relation2 = # foreign key ... class Contact(models.Model): information = # character field ... The problem is I can see the Contact model(and multiple other models) from the admin site(http://localhost:8000/admin/) but ImportantModel is not showing. Thank you in advance. -
Django Model inheritance: model child class creating extra rows in model parent class data-table
I am trying to apply basic model inheritance based on the Django documentation. The end goal is to access the shared id of the Exam and Date models in the get_date_info view, which is called after the get_exam_info view. Perhaps there is a better way to do this than model inheritance, but this seemed the most straight forward to me. Here is the relevant Model code: class Exam(models.Model): instructor_first_name = models.CharField(max_length=30) instructor_last_name = models.CharField(max_length=30) department = models.CharField(max_length=30, null=True) course_name = models.CharField(max_length=30, null=True) course_number = models.IntegerField(null=True) section_number = models.IntegerField(null=True) num_students = models.IntegerField(null=True) calculator = models.CharField(max_length=30, blank=True) notes = models.CharField(max_length=30, blank=True) computer_exam = models.BooleanField(default=False) scantron = models.BooleanField(default=False) timed = models.BooleanField(default=False) dictionary = models.BooleanField(default=False) comment = models.CharField(max_length=300, blank=True) class Date(Exam): start_date = models.DateField() end_date = models.DateField() late_start_date = models.DateField(blank=True, null=True) late_end_date = models.DateField(blank=True, null=True) Here is the relevant view code: def get_exam_info(request): if request.method == 'POST': exam_form = ExamForm(request.POST) if exam_form.is_valid(): exam_form.save() date_form = DateForm() return render(request, 'date_info.html', {'date_form': date_form}) else: exam_form = ExamForm() return render(request, 'exam_info.html', {'exam_form': exam_form}) def get_date_info(request): exam_request = Exam.objects.all() if request.method == 'POST': date_instance = Date() date_form = DateForm(request.POST, instance=date_instance) if date_form.is_valid(): date_form.save() current_user_id = date_instance.exam_ptr_id print(current_user_id) return HttpResponseRedirect('/') else: date_form = DateForm() return render(request, 'date_info.html', {'date_form': date_form}) … -
django-serializers error inside a virtualenvironment
I am trying to install the django serializers-module inside a virutal environment. It gives me an error and I don't know how to get around it. I have tried on 2 computers and a vps and get the same error. It works outside of the virtual environment but not inside. This is what gets the error: mkdir test-pi; cd test-pi/; virtualenv -p python3 .; source bin/activate; pip install django-serializers; This is the error ERROR: Command errored out with exit status 1: command: /home/owner2/Dev/BELove/src/belove/test-pi/bin/python3 -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-o2kpa85w/django-serializers/setup.py'"'"'; __file__='"'"'/tmp/pip-install-o2kpa85w/django-serializers/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /tmp/pip-install-o2kpa85w/django-serializers/pip-egg-info cwd: /tmp/pip-install-o2kpa85w/django-serializers/ Complete output (6 lines): Traceback (most recent call last): File "<string>", line 1, in <module> File "/tmp/pip-install-o2kpa85w/django-serializers/setup.py", line 56 print "You probably want to also tag the version now:" ^ SyntaxError: Missing parentheses in call to 'print'. Did you mean print("You probably want to also tag the version now:")? ---------------------------------------- ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output. -
Django 2.0: Display a Select widget as HTML in the List View table
I have a Django 2.0 app. One class in the admin interface ("list" view, not "change"!) needs a column with a select dropdown with numbers from 1:10, and a Submit button. From the docs I understood that I should use a "Select" widget and define a form. I am curious if it's possible to do with just admin.py and my model, without involving forms.py, templates, etc. So I tried this: class MyClassAdmin(SuperAdmin): list_display = ["inline_mycolumn", "other_field1", "etc"] def mycolumn(self, my_object): from django import forms MY_CHOICES= [tuple([x,x]) for x in range(1,11)] return mark_safe(forms.Select(choices=MY_CHOICES)) .....the rest of the class code.... This below of course does not render the widget as select dropdown, in the source of the table it comes as: <th class="field-column"><a href="/admin/<myapp>/<my_model_name>/<record id>/change/"><django.forms.widgets.select object="" at="" 0x7f4fea267828=""></django.forms.widgets.select></a></th> and the cell stays empty. The rest of the table is rendered as it should. And without mark_safe it just prints the object's name in the cell: format_html (I had to try!) gives 'Select' object has no attribute 'format' Maybe there's a way to cast that widget object into HTML representation with just admin.py code? Thanks