Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DRF: Dynamically add a field to a serializer
I am working with Python 2.7 and Django 1.8 aswell as DRF. In one app, I have defined a Serializer. Something like this: class BlacklistedHostSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = BlacklistedHost fields = ('foo', 'bar',) I want to add a new field to the serializer. This field is the result of a calculation donde by a different app. I have managed to do so with something like this: class BlacklistedHostSerializer(serializers.HyperlinkedModelSerializer): if apps.is_installed('credits'): credits_field = serializers.SerializerMethodField('get_host_credits') def get_host_credits(self, host): from credits.utils.credits import CreditCache cc = CreditCache() return cc.get_host_credits(BlacklistedHost, host.host_name) class Meta: model = BlacklistedHost fields = ('foo', 'bar',) if apps.is_installed('credits'): fields = fields + ('credits_field',) This works fine, but I want each app to be modular (self-contained). Therefor I want to the "credits" app to be the one that adds the field "credits_field" to the Serializer. How could I achive this? This is a snippet of code that I have come up with. It resides in the "credits" app, and it imports the Serializer and tries to dynamically add the new field, but it's not working: from views import * from apirest.serializers import BlacklistedHostSerializer from credits.utils.credits import CreditCache from synchronizer.models import BlacklistedHost from rest_framework import serializers def get_host_credits(self, host): cc = CreditCache() … -
Get data from one model to another Django/Python
I'm building an application with python and Django. I have several models but I need to get data from one model to another (the relation can be made with a SOSS (sales order number). I do have the logic to do that, but is not as efficient as I would wanted. It takes around 5-6 min to process the data. My Model 1 has the relation number (po_number) and is related to Model 2 (there is called planning_number) It takes a lot of time because Model 2 has around 93,000 data lines. This is my logic: def import_withtimes(request): print "importando With Times a ots report" po_cache = list() for item in Model1.objects.all(): if item.po_number in po_cache: continue withtimes = Model2.objects.filter(planning_order=item.po_number) for wi in withtimes: po_cache.append(wi.planning_order) item.wms = wi.wms_order item.status = wi.shipment_status item.aging = wi.status_date item.carrier = wi.service_level item.add_date = wi.order_add_date item.asn_validation = wi.asn_sent_time item.docs_add_date = wi.docs_received_time item.save() My question is: Is there any way more efficient to reflect data from one model to another? -
Django mongodb - settings.DATABASES is improperly configured
I'm using Django 1.8 and MongoDB in my project. I can connect to database but when I want to do something in views.py I'm getting this error: ImproperlyConfigured at /make_histograms settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details. Request Method: POST Request URL: http://127.0.0.1:8000/make_histograms Django Version: 1.8 Python Executable: G:\Stamp 2\VENV2\Scripts\python.exe Python Version: 2.7.12 Python Path: ['G:\\Stamp 2\\znaczki2', 'G:\\Stamp 2\\VENV2\\Scripts\\python27.zip', 'G:\\Stamp 2\\VENV2\\DLLs', 'G:\\Stamp 2\\VENV2\\lib', 'G:\\Stamp 2\\VENV2\\lib\\plat-win', 'G:\\Stamp 2\\VENV2\\lib\\lib-tk', 'G:\\Stamp 2\\VENV2\\Scripts', 'c:\\python27\\Lib', 'c:\\python27\\DLLs', 'c:\\python27\\Lib\\lib-tk', 'G:\\Stamp 2\\VENV2', 'G:\\Stamp 2\\VENV2\\lib\\site-packages'] Server time: Tue, 20 Dec 2016 17:23:38 +0100 Installed Applications: ('django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'app') Installed Middleware: ('django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware') Traceback: File "G:\Stamp 2\VENV2\lib\site-packages\django\core\handlers\base.py" in get_response 132.response = wrapped_callback(request, *callback_args, **callback_kwargs) File "G:\Stamp 2\VENV2\lib\site-packages\django\views\decorators\csrf.py" in wrapped_view 58. return view_func(*args, **kwargs) File "G:\Stamp 2\znaczki2\app\views.py" in make_histograms 62. example.save() File "G:\Stamp 2\VENV2\lib\site-packages\django\db\models\base.py" in save 710. force_update=force_update, update_fields=update_fields) File "G:\Stamp 2\VENV2\lib\site-packages\django\db\models\base.py" in save_base 735. with transaction.atomic(using=using, savepoint=False): File "G:\Stamp 2\VENV2\lib\site-packages\django\db\transaction.py" in __enter__ 150. if not connection.get_autocommit(): File "G:\Stamp 2\VENV2\lib\site-packages\django\db\backends\base\base.py" in get_autocommit 286. self.ensure_connection() File "G:\Stamp 2\VENV2\lib\site-packages\django\db\backends\dummy\base.py" in complain 21. raise ImproperlyConfigured("settings.DATABASES is improperly configured. " Exception Type: ImproperlyConfigured at /make_histograms Exception Value: settings.DATABASES is improperly configured. Please supply the ENGINE value. … -
Django 1.10 don't show post from db
Im start to learn django framework.I write blog. I add some post in django-admin and i want to show it on web.(but it don't show) THIS IS MODELS.PY from django.db import models from django.utils import timezone from django.core.urlresolvers import reverse class PublishedManager(models.Manager): def get_queryset(self): return super(PublishedManager, self).get_queryset()\ .filter(status='published') class Post(models.Model): STATUS_CHOICES = ( ('draft', 'Roboczy'), ('publish', 'Opublikowany') ) title = models.CharField(max_length=300) slug = models.SlugField(max_length=300, unique_for_date='publish') body = models.TextField() publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='draft') object = models.Manager() published = PublishedManager() class Meta: ordering = ('-publish',) def __str__(self): return self.title def get_absolute_url(self): return reverse('blog:post_detail', args=[self.publish.year, self.publish.strftime('%m'), self.publish.strftime('%d'), self.slug]) THIS IS VIEWS.PY from django.shortcuts import render, get_object_or_404 from .models import Post def post_list(request): posts = Post.published.all() return render(request, 'blog/post/list.html', {'posts': posts}) def post_detail(request, year, month, day, post): post = get_object_or_404(Post, slug=post, status ='published', publish_year=year, publish_month=month, publish_day=day) return render(request, 'blog/post/detail.html', {'post': post}) THIS IS URLS.PY at BLOG APP from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.post_list, name='post_list'), url(r'^(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/$' r'(?P<post>[-\w]+)/$', views.post_detail, name='post_detail'), ] AND THIS IS URLS.ON PROJECT from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^blog/', include('blog.urls', namespace='blog', app_name='blog')), ] list.html {% extends "blog/base.html" … -
how to unpack stxetx data in python
I'm receiving a data packet sent from a RS485 level serial bus to a ESeye Hammerkop transmitter which then URL encodes the data and sends it to my server. The request looks like the following: at=info method=GET path="/write/?type=stxetx&packet=ArcYX%01%00%00%00%00%00%00%03%00%F0%00%06%00%F0%008%0E%B0%27%00%00%E85&localpackettime=2016-12-20+16%3A00%3A27&serial=868324023356343&packettime=2016-12-20+16%3A00%3A27&receivetime=2016-12-20+16%3A00%3A28&timezone=UTC" host=dry-hollows-46605.herokuapp.com request_id=4d5bec23-0676-4e32-ae66-af26e26f0394 fwd="81.94.198.91" dyno=web.1 connect=1ms service=232ms status=500 bytes=63266 I'm using Django 1.9 as my framework and to get the packet data I use: packet_data = request.GET.getlist('packet') The data i receive is the following: packet_data = [u"A\x90cYX\x01\x00\x00\x00\x00\x00\x00\x03\x00\xf0\x00\x06\x00\xf0\x008\x0e\xb0'\x00\x00\xe85"] I then must split this into bytes, the first letter is an ascii letter which is straight forward and can be ignored, the rest are bytes. I'm trying to split out this unicode string into the values i need for example the first 4 bytes after the 'A' are a byte int timestamp. I've tried encoding the values, for example: a = packet_data[1].encode('utf-8') b = packet_data[2].encode('utf-8') c = packet_data[3].encode('utf-8') d = packet_data[4].encode('utf-8') which converts them to str rather than unicode and then I unpack them: timestamp = unpack('i',a+b+c+d) however this only works some of the time and sometimes I get the error: error: unpack requires a string argument of length 4 I got the error for these timestamp values for example: before encoding u'\x90', u'c', u'Y', … -
HMAC in Django request URL for embedded Shopify App
I am creating an embedded Shopify app with Django. When I first request a URL it will appear as so in the browser address bar: https://storeurl.myshopify.com/admin/apps/appname/action/ However, if I refresh the page I will get HMAC information in it like so: https://storeurl.myshopify.com/admin/apps/appname/action/?hmac=[... some token ...]&protocol=https%3A%2F%2F&shop=storeurl.myshopify.com&timestamp=1482249434 This is my view: @login_required def home(request, *args, **kwargs): # Get a list of the user's products. with request.user.session: products = shopify.Product.find() return render(request, "appname/index.html", { 'products': products, }) Why do I get this information? Should I be validating this information to ensure the request is genuine? Why do I not get it in the URL on the first call? -
Can't render django-countries-plus options in form template
For some reason I can't get the list of Countries in django-countries-plus to render in my template. The table is imported fine under Countries Plus > Countries and I've set the models.py up as follows: from countries_plus.models import Country class Project(models.Model): title = models.CharField(max_length=500) status = models.BooleanField(default=True) location = models.CharField(max_length=500) projectcountry = models.ForeignKey(Country) Then added the new field projectcountry to the form on forms.py: from django.forms import ModelForm from .models import Project, Proposal class ProjectForm(ModelForm): class Meta: model = Project fields = ['title', 'status', 'location', 'projectcountry'] Then in the template I'm trying to bring in the 252 countries in the table to render in a Bootstrap dropdown: <form class="form-horizontal" method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="form-group"> <label class="col-sm-2 control-label">PROJECT TITLE</label> <div class="col-sm-6"> <textarea rows="1" class="form-control" name="title"></textarea> </div> </div> <div class="form-group"> <label class="col-sm-2 control-label">STATUS</label> <div class="col-sm-6"> <select name="status" class="form-control"> <option value="1">Active</option> <option value="0">Disabled</option> </select> </div> <div class="col-sm-4"> </div> </div> <div class="form-group"> <label class="col-sm-2 control-label">CITY / TOWN</label> <div class="col-sm-6"> <textarea rows="1" class="form-control" name="location"></textarea> </div> </div> <div class="form-group"> <label class="col-sm-2 control-label">COUNTRY</label> <div class="col-sm-6"> <select name="projectcountry" class="form-control"> {% for country in countries %} <option value="{{ country.iso }}">{{ country.name }}</option> {% endfor %} </select> </div> <div class="col-sm-4"> </div> </div> </form> Can you see what I'm … -
How to start using react on existing django website
My team developed a django website with lot of pages that working completely without javascript or may be with the little jquery manipulation. We want try to use a react library to speed up our pages and add page navigation without full page reloading (we choose react because we implemented some SPA website with react and we like it). Also our pages should working with disable js. I want to start with one page with 5 forms on it. If any form is submit then page is reloaded, data populated in fields is lost and it work slowly. I think to implementing sending data on ajax and change some html after server answer. Every react tutorial is saying to write jsx components with html markup inside, convert it with babel to pure js and adding on page dynamically on page load. Or if you want to render pages on server you need to use standalone node server. But I already has a powerfull django template engine to render templates on server side, also I need to render templates with specific django things like multilanguage content, user variables etc. Can I fully render page with django on server side and after … -
Denied the access of Django Helpdesk if not connected
I'm working on the module Helpdesk from Django and I got a question. Right now, everybody have an access to my Helpdesk. Administrators, normal users, and not connected persons. (Not connected persons have the same right that the normal users -> Submit a ticket.) I would like that people who try to join 192.168.x.xxx:8000/helpdesk/ are redirected to the login page : 192.168.x.xxx:8000/helpdesk/login/?next=/helpdesk/ I would like too that people who are trying to join an inexistant page like http://192.168.x.xxx:8000/helpdesk/blablabla are redirected to the homepage if he is connected, or redirected to the login page if he isn't. Thanks for your help. -
Django linking files on production server
from os import path PROJECT_ROOT = path.dirname(path.abspath(path.dirname(__file__))) STATIC_ROOT = path.join(PROJECT_ROOT, 'static').replace('\\', '/') # URL prefix for static files. # Example: "http://media.lawrence.com/static/" STATIC_URL = '/static/' This code works in development server But does not work in production server Css and javascript files are not getting linked for the web app. What do I need to do? -
Django webserver on deployment
I have made my django project, I want to deploy it on the mentioned server IP so same project I put on the server with debug=False. My static files are not uploaded so I set static root and then run collect static command and now I am wondering which is exactly my server on which I deployed my project. Is there any one to check which server I am using Apache or other? -
Using Canvas and Tables with ReportLab
I need to create a PDF with tables and text with ReportLab. However, all the examples don't use canvas to print a table so right now I can either have text or a table, not both. How can I still use canvas to write while appending tables? Table Code: location = 'C:/Users/Evan/Desktop/webapp/Web PDF/' name = quote + ".pdf" save_name = os.path.join(location, name) doc = SimpleDocTemplate(save_name, pagesize=A4, rightMargin=30,leftMargin=30, topMargin=30,bottomMargin=18) doc.pagesize = landscape(A4) elements = [] data = [ ["#", "Item", "Quantity", "Comments"], ["1", a1, b1, c1], ["2", a2, b2, c2], ["3", a3, b3, c3], ["4", a4, b4, c4], ["5", a5, b5, c5], ["6", a6, b6, c6], ["7", a7, b7, c7], ["8", a8, b8, c8], ["9", a9, b9, c9], ["10", a10, b10, c10], ] style = TableStyle([('ALIGN',(1,1),(-2,-2),'RIGHT'), ('TEXTCOLOR',(1,1),(-2,-2),colors.red), ('VALIGN',(0,0),(0,-1),'TOP'), ('TEXTCOLOR',(0,0),(0,-1),colors.blue), ('ALIGN',(0,-1),(-1,-1),'CENTER'), ('VALIGN',(0,-1),(-1,-1),'MIDDLE'), ('TEXTCOLOR',(0,-1),(-1,-1),colors.green), ('INNERGRID', (0,0), (-1,-1), 0.25, colors.black), ('BOX', (0,0), (-1,-1), 0.25, colors.black), ]) s = getSampleStyleSheet() s = s["BodyText"] s.wordWrap = 'CJK' data2 = [[Paragraph(cell, s) for cell in row] for row in data] t = Table(data2) t.setStyle(style) elements.append(t) doc.build(elements) Canvas Code p = canvas.Canvas(save_name) logo = 'C:/Users/Evan/Desktop/webapp/pictures/logo1.png' p.drawImage(logo, 50, 750, width=225, height=75) p.drawString(280, 775, quote) p.drawString(100, 100, data) p.drawString(50, 725, "Customer:") p.drawString(110, 725, customer) p.drawString(400, 725, "Customer PO:") p.drawString(480, 725, … -
Reading raw http request
Django 1.10.4 I'd like to just have a look at the raw HTTP request that a view function gets. views.py def test_handler(request): return HttpResponse(request.body.decode(), content_type="text/plain") Well, I place a breakpoint in my IDE. And I can evaluate these expressions: request.body={bytes}b"" request.body.decode()={str}b"" My purposes are purely educational. I read in the documentation: https://docs.djangoproject.com/en/1.10/ref/request-response/#django.http.HttpRequest.body So, the mechanism for reading raw request is organized. But I suppose some middleware or something just nullified the raw request. By the way, Django is just out of the box: I didn't interfere with middleware or settings. Could you help me understand: 1) How to read the raw request text; 2) If it is nullified where it is done and why? -
how to use asyncio via django orm
I am going to use asyncio via django orm in a new project. I did the same via twisted in another project but it does not work via asyncio in my new project. My code is some thing like this: import asyncio import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "pj1.settings") from django.conf import settings from world.models import * async def msg(text): await asyncio.sleep(0.1) print(text) async def long_operation(): for i in range(10): # can run a long time. print('long_operation started', i) await asyncio.sleep(3) print('long_operation finished', i) async def main(): await msg('first') task = asyncio.ensure_future(long_operation()) await msg('second') await task if __name__ == "__main__": loop = asyncio.get_event_loop() loop.run_until_complete(main()) When I run the code via python 3.5 and django 1.10, it shows following exception: django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. What is the problem? I did not find any clue in the net. -
easy-thumbnails 2.1 - how to trim only the image height?
I use Python package easy-thumbnails 2.1 and I need to trim only the height of the image. How can I make this? Thanks. -
How to update Angularjs view from Django code?
My app scraps data from the Internet & processes them using django. I want to update the user with the current process my app is doing in a progress bar. So I need a way to send messages from django to Angular without interrupting my django processing. -
Fixed Model in django
I'd like to model a driver with some information, e.g. forename, surname and his allowed classes (e.g. A, B, C, D, ....), so I modeld a driver and classes like this: class Classes(models.Model): CLS = tuple([(x, x) for x in ("A1", "A", "B", "BE", "C1", "C1E", "C", "CE", "D1", "D1E", "D", "DE", "M", "L", "T")]) name = models.CharField(max_length=3, choices=CLS, primary_key=True) class Driver(models.Model): forename = models.CharField(_('Forename'), max_length=50) surname = models.CharField(_('Surname'), max_length=50) classes = models.ManyToManyField(Classes, verbose_name=_("Classes")) Now I don't want to set the Classes class as fixed, so you cannot add nor remove any data from it and it always should have all of the options. Initial Data could be an option, but I don't like it, because that's an extra migration step. Any chances I get what I want? -
Django static fileds and Media files returning 404 when running on server
I'm trying to deploy my project to the ubuntu. My project is working with python manage.py runserver and when I'm trying to enter my project its giving 404 on media files and static files. I already gave static root and media root to the urls. "GET /static/rest_framework/js/bootstrap.min.js HTTP/1.1" 404 2578 -
Django sort queryset based on timestamp
I have three django models and I am using django-simple-history stores Django model state on every create/update/delete. player = Player.history.all().values('first_name','history_date', 'history_id', 'history_type', 'history_user_id', 'id', 'createdtstamp') coach = Coach.history.all().values('coach_name','history_date', 'history_id', 'history_type', 'history_user_id', 'id', 'createdtstamp') title = Title.history.all().values('title_name', 'history_date', 'history_id', 'history_type', 'history_user_id', 'id', 'createdtstamp') result_list = sorted(chain(player, coach, title), key=lambda instance: instance.createdtstamp) queryjson = json.dumps(result_list, cls=DjangoJSONEncoder) return HttpResponse(queryjson) How can I sort query result based on createdtstamp field (sort by latest)? -
function onClick not triggered
I have a django admin site where an admin can manage the documents that the employees are allowed to see. The admin can change the order of the elements because I added the class "sortable" in the ul that contains the document elements, in the following way: <!-- Sortable categories and documents --> <div class="document_container"> <ul class="sortable"> <li class="document-item context-menu-document"></li> <li class="document-item context-menu-document"></li> <li class="document-item context-menu-document"></li> ... ... ... </ul> </div> Then, using a JS I'm attaching a click event to the elements that has the class .document-item in order to select them, as you can see: $(document).ready(function(){ $('.document-item').click(function(e){ $(this).addClass('ui-selected selected-unique'); }); }); Until here, everything works as expected. Now, I also want the employees to be able to enter in the admin site, but they cannot change the order of the elements. To do so, I have changed the line: <ul class="sortable"> For the line: <ul> Indeed, the users cannot move the elements now, but it seems that the click behaviour is not working either. The funciton is attached to the elements, as I can see in the inspector, but is never triggered. Any help is much appreciated, Thanks. -
Why isn't behave's documented manual integration with Django working?
I have a Django project ("theproject") and some behave features. I've been using behave-django. python manage.py behave works. However, PyCharm (which uses the behave executable rather than a Django management command) doesn't know how to run my features, so I'm attempting to use behave's documented "manual integration" with Django. My entire features/environment.py: import os import django from django.test.runner import DiscoverRunner from django.test.testcases import LiveServerTestCase from splinter.browser import Browser os.environ["DJANGO_SETTINGS_MODULE"] = "theproject.settings" def before_all(context): django.setup() context.test_runner = DiscoverRunner() context.test_runner.setup_test_environment() context.old_db_config = context.test_runner.setup_databases() context.browser = Browser('phantomjs') # When we're running with PhantomJS we need to specify the window size. # This is a workaround for an issue where PhantomJS cannot find elements # by text - see: https://github.com/angular/protractor/issues/585 if context.browser.driver_name == 'PhantomJS': context.browser.driver.set_window_size(1280, 1024) def before_scenario(context, _): context.test_case = LiveServerTestCase context.test_case.setUpClass() def after_scenario(context, _): context.test_case.tearDownClass() del context.test_case def after_all(context): context.test_runner.teardown_databases(context.old_db_config) context.test_runner.teardown_test_environment() context.browser.quit() del context.browser Also, for this experiment I removed behave-django from theproject/settings.py's INSTALLED_APPS. When I run behave I get Exception AppRegistryNotReady: Apps aren't loaded yet. Traceback (most recent call last): File "/usr/local/bin/behave", line 11, in <module> sys.exit(main()) File "/usr/local/lib/python2.7/site-packages/behave/__main__.py", line 109, in main failed = runner.run() File "/usr/local/lib/python2.7/site-packages/behave/runner.py", line 672, in run return self.run_with_paths() File "/usr/local/lib/python2.7/site-packages/behave/runner.py", line 678, in run_with_paths self.load_step_definitions() … -
how to send function error report through email in django
I have to implement paystation payment gateway in my project, this gateway response in two ways after the transaction one on return url and other on POST url, post url works on the backend as it works in all other payment gateways, It returns all the payment related response on POST url, It returns the result in XML format. I want to send this response on my email, so that i can check the response parameters, so i am using this code. def payment_post(request): responseData = xmltodict.parse(request.POST) msg = EmailMultiAlternatives('Post Parameters', responseData, 'exampleFrom@gmail.com', ['exampleTo@gmail.com']) msg.send() Its not sending me any details on my email id, but when i use this code msg = EmailMultiAlternatives('Post Parameters', 'Testing data', 'exampleFrom@gmail.com', ['exampleTo@gmail.com']) msg.send() It sends me the mail with 'testing data' as mail content and 'POST parameters' as subject, so it means there are some issues in parsing xml or i am not getting any post data in response. So i want to check the error, is there any way i can get the error details for this , can i send the error details on my email id ? Thanks -
Django social auth to update profile model
I am using django-social-auth. Everything works fine except that profile model is not updated. I have a OneToOneField with USER table. Whenver a user registers on site using e-mail, his profile is created automatically. However when login with social credentials, profile is not automatically created. What changes needs to be done for this to work. Thank you. Profile.py class Profile(models.Model): user=models.OneToOneField(settings.AUTH_USER_MODEL) contact_number= models.CharField(max_length=250,null=True,blank=True) official_email= models.EmailField(null=True,blank=True) website= models.CharField(max_length=250,null=True,blank=True) address = models.TextField(null=True,blank=True) city = models.CharField(max_length=250,null=True,blank=True) -
Django admin form fields attributes override
Django 1.8. I've got model: class Location(models.Model): address = models.CharField(max_length=65) annotation = models.CharField( max_length=80, verbose_name='Additional info', blank=True, null=True, help_text='e.g. officce 412, 4 floor') And i have task to expand form input field a bit for this model in admin. I made this by: class LocationAdminForm(forms.ModelForm): annotation = forms.CharField( widget=forms.widgets.TextInput(attrs={'size': 70})) and here i lost my verboose_name, blank=True and help_text in admin form. I can fix this problem by: class LocationAdminForm(forms.ModelForm): annotation = forms.CharField( required=not Location._meta.get_field('annotation').blank, label=Location._meta.get_field('annotation').verbose_name, help_text=Location._meta.get_field('annotation').help_text, widget=forms.widgets.TextInput(attrs={'size': 70})) but this variant looks so ugly... Is there any options here? -
Django Rest Framework Get Requests With Custom Url
I'm just trying to make get request with my field. But in this get request I don't want to use pk. I just want to use Barcode which you can see model below. Also I'm new on Django: class Product(models.Model): name = models.CharField(max_length=255) price = models.CharField(max_length=255,null=True) barcode = models.BigIntegerField(unique=True, validators=[MaxValueValidator(13)]) cover_photo = models.ImageField(upload_to='images/', blank=True, null=True) description = models.CharField(max_length=255,null=True) product_url = models.CharField(max_length=255,null=True) product_company = models.ForeignKey(Company, blank=True, null=True) fields = ['barcode', 'name', 'cover_photo', 'product_url', 'price'] def __unicode__(self): return self.name.encode('utf-8') Also this is my urls. url(r'^api/products/(?P<barcode>)/$',product_detail, name="product_detail"), product_detail = views.ProductViewSet.as_view({ 'get': 'retrieve' }) and this is my view. class ProductViewSet(viewsets.ReadOnlyModelViewSet): queryset = Product.objects.all() serializer_class = ProductSerializer