Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Application with AWS ElastiCache, 500 Errors
I setup Django Cache with Memcached (with pylibmc backend). My settings look like this: CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.PyLibMCCache', 'LOCATION': 'LOCATION:PORT', } } I am only caching a view using the cache_page() decorator. From my end, everything seems to be working fine for this cached view. However, when I use Google PageSpeed Insights on the URL, every other run returns a 500 error. My error logs don't seem to show any information. Just that 500 errors were returned for the Google PageSpeed Bot. The website is not under heavy-load, so i don't think there is any cache stampede or similar issue involved. Any help here, thank you. -
How to display multiple forms of a single model in Django templates?
I have this model Note: class Note(models.Model): category = models.ForeignKey(Category) author = models.ForeignKey('auth.User') title = models.CharField(max_length=40) text = models.TextField() created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) And I want to display this form: class NoteEditForm(forms.ModelForm): class Meta: model = Note fields = ('title', 'text') in a template, but I want it to appear for each existing Note object in the database (it has to be that way). I've done something like that but then I hardcoded the form, pointing to the edit view URL with each object pk as a parameter; but I'm sure it has to be a clearer way, just I haven't found it. Could you guys help me with that? Thanks! -
how to host a webpage from Django without the port in Kali
I have created a web page and i can able to host in Django as http://127.0.0.1:8000 or 0.0.0.0:8000 , which is accessible in my Lan with my ip, i could access with http://192.168.0.4:8000 , but i dont need the port in the url , i need to access the site with http://192.168.0.4 iam writing auto redirecting code so if there is :8000 that will not work properly so i need a way to host Django without the port -
Django rest framework one to one relation Create serializer
I'm a beginner to the Django Rest Frame work. I want to create a custom user but I have a problem from a long period i try to find a solution through many forums but unfortunately i didn't succeed. hope you help me models.py class Account(models.Model): user=models.OneToOneField(User,on_delete=models.CASCADE) image=models.ImageField(upload_to='Images/',default='Images/user.png') date=models.DateField(auto_now=True,auto_now_add=False) Serializers.py class AccountCreateUpdateSerializer(serializers.ModelSerializer): user=UserListSerializers() image=serializers.ImageField() class Meta: model= Account fields=['id','user','image'] def create(self,validated_data): user_data=validated_data.pop('user') account=Account.objects.create(**validated_data) User.objects.create(account=account,**user_data) return account the error : enter image description here -
Upload images based on matching field and image name
I'm building an inventory list that includes the fields listed below in my Django model. I have a folder full of images that the name of the images correspond to the the Item Number. For install, the item number may be 4119, then the image file name will be 4119.jpg. I would like to write a script that iterated over the items in the database and uploads the corresponding image. Any thoughts on where to start are greatly appreciated. from django.db import models def directory_path(instance, filename): return '{0}/{1}/{2}'.format(supplier.name, pricelist.item_number, filename) class Supplier(models.Model): name = models.CharField(max_length=80) def __str__(self): return self.name class PriceList(models.Model): supplier = models.ForeignKey('Supplier', on_delete=models.CASCADE) item_number = models.CharField(max_length=80) description = models.CharField(max_length=120) case_quantity = models.CharField(max_length=80) piece_list_amount = models.CharField(max_length=80) partner_list_amount = models.CharField(max_length=80) upload = models.ImageField(upload_to=directory_path) def __str__(self): return self.item_number -
How do I deploy a Django app developed on Cloud9 to Heroku
I have a django app that I've been developing on Cloud9 and would like to deploy it to Heroku. What do I need to do to get it setup (and a database for it on Heroku) and deployed? -
How can I find my git repository pushed by heroku
I created an a heroku app on python-django framework.I pushed my slug to my git repository using the following commands. git add . git commit -m "first commit" git push heroku master After that I search my local git repository and I can't able to find the things that I pushed.How can I find it? Please help me. -
Django 500 Internal Server Error with Passenger on Dreamhost
I'm trying to migrate my fully working Django 1.9.6 project with Python 2.7.3 to Dreamhost. I'm not sure if my current file structure is correct, as well as my passenger_wsgi.py and project.fcgi files. When I try to access the website I get a 500 Internal Server Error message. Here's my directory structure home user website.com .htaccess env bin include lib local public assets passenger_wsgi.py manage.py project.fcgi django-project settings.py urls.py wsgi.py django-app Here's my passenger_wsgi.py import sys, os cwd = os.getcwd() sys.path.append(cwd) sys.path.append(cwd + '/django-project') if sys.version < "2.7.3": os.execl("/home/user/website.com/env/bin/python", "python2.7.3", *sys.argv) sys.path.insert(0,'/home/user/website.com/env/bin') sys.path.insert(0,'/home/user/website.com/env/lib/python2.7/site-packages/django') sys.path.insert(0,'/home/user/website.com/env/lib/python2.7/site-packages') os.environ['DJANGO_SETTINGS_MODULE'] = "django-project.settings" from django.core.wsgi import get_wsgi_application application = get_wsgi_application() Here's my django-project.fcgi import sys, os sys.path.insert(0, "/home/user/website.com/env/bin/python") os.chdir("/home/user/website.com/django-project") os.environ['DJANGO_SETTINGS_MODULE'] = "django-project.settings" from django.core.servers.fastcgi import runfastcgi runfastcgi(method="threaded", daemonize="false") Any ideas where I'm going wrong? This is my first time launching a website like this so I may be making a fundamental directory structure mistake. Let me know if I should provide any other files or information. -
Django Collectstatic Error IBM bluemix
I am getting this error when i am trying to deploy the django app on IBM Bluemix. Please see the log file Log file -
Make form text field presence dependent on checkbox selection
I have a Django form and I would like it to initially hide a text field until the user selects a checkbox. I am new to Django and web applications, so I have no idea what I am looking for or what it is called. I have searched to no avail. Any pointer would be helpful. -
Need an easy master detail table implementation in django python
i need to create a form which a master block and a detail block coming from models and django forms(not modelforms). Is there a good and clear tutorial out there? I am stuck here among foreign keys, primary keys and committing the form data by creating objects. Cannot assign "'str value'": "Detail table.voucher_id" must be a "Master table" instance I spent all day trying to understand this :( -
Django model formset
I have created page to view data on report of job classification. In 'Value' model i added "is_value" field, in order to indicate the ranks of job classifications parrent under parrent until the last unit (which only contains the value, for example: Parrent:Professions -> Parrent: Drivers -> the last unit which has the value: taxi driver, whose value equals to '0' zero.) The job classification tree generated by "treeOrderField", and ordering by "path" field: I used my template tag "title_for_report "to generate HTML source to show the tree by "Title.path" : Now i want genarate forms to input all value in template as shown on the picture. In column "Value" i need to add forms wheare is_value==True. And show Titles like tree. How can i do it? class TreeOrderField(models.CharField): def pre_save(self, model_instance, add): if add: # parent = model_instance.parent if model_instance.parent: parent = (model_instance.parent or model_instance.id) if parent.seq < 1000: parent.seq += 1 parent.save() else: pass value = ('%s%03d' % (getattr(parent, self.attname, '-'), parent.seq, ))[:255] setattr(model_instance, self.attname, value) return value else: value = '001' return value return models.CharField.pre_save(self, model_instance, add) class Title(models.Model): parent = models.ForeignKey('self', blank=True, null=True, related_name='child_set') path = TreeOrderField(max_length=255, blank=True) seq = models.PositiveSmallIntegerField(default=0) title = models. CharField(max_length=255, blank=False, … -
How to upload an image from an input type='file' using django?
i need to upload an image from an file input using django, i tried img=request.Post.get('name') but it doesn't work. How can i proceed ? -
Why I am getting Error: 'QuerySet' object has no attribute?
I have 3 models class Lease(CommonInfo): version = IntegerVersionField( ) #amount = models.DecimalField(max_digits=7, decimal_places=2) is_renewed = models.BooleanField(default=False) unit = models.ForeignKey(Unit) is_terminated = models.BooleanField(default=False) class LeaseTerm(CommonInfo): version = IntegerVersionField( ) start_period = models.ForeignKey(Period, related_name='start_period' ) end_period = models.ForeignKey(Period, related_name='end_period') lease = models.ForeignKey(Lease) increase = models.DecimalField(max_digits=7, decimal_places=2) amount = models.DecimalField(max_digits=7, decimal_places=2) is_terminated = models.BooleanField(default=False) def clean(self): model = self.__class__ if self.lease_id and (self.is_terminated == False) and model.objects.filter(lease=self.lease, is_active=True ).count() == 1: raise ValidationError('!Lease has a active condition already, Terminate prior to creation of new one'.format(self.lease)) class LeasePayment(CommonInfo): version = IntegerVersionField( ) amount = models.DecimalField(max_digits=7, decimal_places=2) leaseterm = models.ForeignKey(LeaseTerm) period_payed_for = models.DateTimeField() payment_date = models.DateTimeField() Since clean method allows only one LeaseTerm to be active and not terminated in my view I want to see all the payments done for this Lease CurrentTerm lease = get_object_or_404(Lease, pk=lease_id) leaseterm = LeaseTerm.objects.filter(lease=lease, is_terminated =False, is_active = True ) payment = leaseterm.leasepayment_set.all().order_by('payment_date') but getting an error 'QuerySet' object has no attribute 'leasepayment_set' What I am doing wrong? -
Django REST Framework Serializer returning object instead of data
I am writing a simple database for the condo I live in which has a list of people, units, unit type (home vs parking space), and unitholder (join table for many-to-many relationship between a person and a unit) - one person can be the owner of a unit type of "home" while renting a parking space. This is my model: class Person(models.Model): first_name = models.CharField(max_length=30, null=False) last_name = models.CharField(max_length=30, null=False) phone = models.CharField(max_length=20) email = models.EmailField(max_length=20) class UnitType(models.Model): description = models.CharField(max_length=30) class Unit(models.Model): unit_number = models.IntegerField(null=False, unique=True) unit_type = models.ForeignKey(UnitType, null=False) unitholders = models.ManyToManyField(Person, through='UnitHolder') class UnitHolderType(models.Model): description = models.CharField(max_length=30) class UnitHolder(models.Model): person = models.ForeignKey(Person) unit = models.ForeignKey(Unit) unitholder_type = models.ForeignKey(UnitHolderType) This is my view: class PersonViewSet(viewsets.ModelViewSet): queryset = Person.objects.all() serializer_class = PersonSerializer class UnitHolderTypeViewSet(viewsets.ModelViewSet): queryset = UnitHolderType.objects.all() serializer_class = UnitHolderTypeSerializer class UnitViewSet(viewsets.ModelViewSet): queryset = Unit.objects.all() serializer_class = UnitSerializer class UnitHolderViewSet(viewsets.ModelViewSet): queryset = UnitHolder.objects.all() serializer_class = UnitHolderSerializer class UnitTypeViewSet(viewsets.ModelViewSet): queryset = UnitType.objects.all() serializer_class = UnitTypeSerializer This is my serializer: class UnitSerializer(serializers.ModelSerializer): unit_type = serializers.SlugRelatedField( queryset=UnitType.objects.all(), slug_field='description' ) class Meta: model = Unit fields = ('unit_number', 'unit_type', 'unitholders') class UnitTypeSerializer(serializers.ModelSerializer): class Meta: model = UnitType class PersonSerializer(serializers.ModelSerializer): class Meta: model = Person class UnitHolderSerializer(serializers.ModelSerializer): person = serializers.PrimaryKeyRelatedField(many=False, read_only=True) unit = serializers.PrimaryKeyRelatedField(many=False, … -
Django: import Topic Issue, word Topic shows instead of title?
Hey guys I just began working through the Django section in the Python Crash Course. I'm making a learning log in which you can add entries. I followed the book but I'm having one odd issue. When I add a new topic instead of the title for a new topic I literally get the word Topic My code is so far as follows, under admin.py from django.contrib import admin from learning_logs.models import Topic admin.site.register(Topic) This is my models.py from django.db import models # Create your models here. class Topic(models.Model): """A topic the user is learning about """ text = models.CharField(max_length=200) date_added = models.DateTimeField(auto_now_add=True) def _str_(self): """Returns a string representation of the model """ return self.text the code matches the book, any idea why this is happening? -
Cannot assign "'str value'": "Detail table.voucher_id" must be a "Master table" instance
I am trying to create a form using my master and detail table. Master table : TmpPlInvoic (primary key: voucher_id) Detail table: TmpPlInvoicedet (foreign key: voucher_id, multiple entries against one voucher id) Error Cannot assign "'5453661'": "TmpPlInvoicedet.voucher_id" must be a "TmpPlInvoice" instance. I am not why i am getting this instance error. The voucher id under question is created by me and inserted in the master table. Then i try to pass the voucher id by getting it from the master table to the detail table so that it comes as an instance. tmpPlInvoicedet_save = TmpPlInvoicedet.objects.create( voucher_id=voucher_id, Views.py def new_invoice(request): logger.info('FORM INFO ----------------------------------------------') QuestionFormSet = formset_factory(AddRowsForm, extra=5) QuestionFormSet_one = formset_factory(AddRowsForm, extra=1) if request.method == 'POST': form = NameForm(request.POST) formset = QuestionFormSet(request.POST) temp_vid = TmpPlInvoice.objects.order_by().values_list("voucher_id", flat=True).distinct() items = Item.objects.all().values_list('stock_code', 'description') if form.is_valid(): data = form.cleaned_data logger.info('FORM INFO') new_date = data['new_date'] new_parc = data['new_parc'] new_vid = data['new_vid'] item_combo = data['item_combo'] pos_combo = data['pos_combo'] cus_combo = data['cus_combo'] if not temp_vid: voucher_id = 0 voucher_id += 1 else: voucher_id = str(int(max(temp_vid)) + 1).zfill(4) tmpPlInvoice_save = TmpPlInvoice.objects.create(voucher_date=new_date, voucher_id=new_vid, acct_id=item_combo, particulars=new_parc, pos_code=pos_combo, cust_id=cus_combo tmpPlInvoice_save.save() for detail in enumerate(formset.cleaned_data, 1): tmpPlInvoicedet_save = TmpPlInvoicedet.objects.create( voucher_id=voucher_id, lineitem=detail[0], particulars=detail[1]['Rate'], qty=detail[1]['Quantity'], rate=detail[1]['Rate'], itemtot=int(detail[1]['Rate']) * int(detail[1]['Quantity']), stock_code=detail[1]['StockCode'] ) tmpPlInvoicedet_save.save() else: message = … -
Django - Unresolved reference - application
I'm starting with a project and I suddenly can't import App names. PyCharm says that app is Unresolved Reference and when I try to start shell and import app, it says that it's unrecognized. Do you know where could be the problem? I've checked whether the correct venv is activated. SHELL: >>> from ProductSpyWeb import Api Traceback (most recent call last): File "<console>", line 1, in <module> ImportError: cannot import name Api APPS in Settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'MainApp', 'Api', ] -
Custom context processor breaks i18n on production server
I need to know in my templates which application serves the current request. To achieve that, I've created a simple context processor similar to this one. The Django docs tell that context processors can live anywhere in the code base, so I've made a directory at the top level of my system and put the python file there. That directory is called common (because I put there common stuff) and has __init__.py so essentially it is a Python module. In fact, I had some other code in that module before all this story happened. So I've added this line to the end of my context_processors list: 'common.context_processors.app_info' (The file name is context_processors.py, and the function within is called app_info.) This works fine on my test server (the built-in one, ./manage.py runserver). However, when I deployed the solution to the production server, it didn't. The Python file that holds the context processor hasn't been loaded at all—no .pyc file has been created for it (there is another file there, and it works fine). Futhermore, and this is much worse, my website now refuses to substitute the i18n URL prefixes like /ru/, /de/, and /en/ (I use django.middleware.locale.LocaleMiddleware). The error is as … -
What is the django equivalent of Jinja2 batch filter?
I am trying to use django 1.10 templating system to display a list as a sequence of row, each containing at most 3 columns. In Jinja2 I would write: {% for items in all_items|batch(3) %} <div class="row"> {% for item in items %} <div class="col-md-4"> <h1> {{item.name}} </h1> </div> {% endfor %} </div> {% endfor %} Using the batch filter in Jinja2 produces the desired output. I could not find an equivalent filter in django templates. What is the django way to achieve this ? -
Receiving the 404 error in getting of static django files
Please help to understand what I do wrong. I have in my settings.py : PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__)) STATIC_URL = os.path.join(PROJECT_ROOT, 'static').replace('\\','')+'/' And in index.html : {% load static %} <link rel="stylesheet" type="text/css" href="{% static "/css/table.css" %}"> But I still have the error 404 : "GET /var/cardsite/cardsite/static/css/table.css HTTP/1.1" 404 1696 I have this file : ls -la /var/cardsite/cardsite/static/css/table.css -rw-r--r-- 1 root root 77 Sep 25 16:15 /var/cardsite/cardsite/static/css/table.css So what is going on? P.S. My project stored on "/var/cardsite" and I want to make static folder on each application, like in example is default application "cardsite" thanks -
Django 1.10 - Multiple Table Inheritance vs Single model with 'type'
Basically, I'm trying to build an authentification system using django's authentification support. I would need 2 different user types, TypeA and typeB for example. They should register through different routes, each one containing many different fields and few similar (email & password). Both of them will login through a single sign in route. What do you think would be the best approach to achieve this? Multiple Table Inheritance or a single model with type attribute (you can suggest other options too, I have no problem with that) ? Thanks in advance! -
Django project architecture
As my Django projects are bigger and bigger I am facing issues regarding architecture. Before starting to code, I spend a lot of time to find a nice architecture for my project: how I split my project in apps, which apps are dependent on other apps and so on. To be clear, by architecture I don't mean project layout. I have done my research and I haven't found yet a ressource showcasing some methods to find the best architecture for a given Django project. Outside web development, UML seems to be the way to go. My questions are: 1) Why is there almost no discussion about those topics on the internet ? Am I missing something and totally wrong in my approach ? 2) Can UML be used to work on Django project architecture ? 3) Is there a common way to tackle this issue with Django ? -
fetch 5 items for each day in a given month, in raw sql or Django orm
Suppose an event is associated with a date. For a given month, I'd like to retrieve events happening in that month, with a constraint such that: I want only 10 events at max for each day. -
Django custom user model, with unique togethr - tenant and username
I am making a multi tenant app on Django, where I want the user model to be unique together on "tenant" (foreign key to tenant model,having the tenant details) and "username", ie something like - unique_together =("username", "tenant") or any of its variety. Is there any possibility of doing that?