Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to open file in text editor other than vim when connected via SSH
For instance, instead of vim 'settings.py' how do I go about opening 'settings.py' in a specific application such as PyCharm because open -a "PyCharm" settings.py does not work -
What is the correct place to use the @transaction.atomic decorator?
In my Django apps, the first database operation that I want to wrap in a transaction might occur at any level of the framework -- it could be in the view, a manager method, or a model method. Up until now, my practice has been to mark the outermost method where database write access first occurs with @transaction.atomic. But I'm finding this painful to keep track of. As I refactor or move things around, the outermost method frequently changes. What is the best way to handle this? Here are some options I'm considering, and of course I'm open to any other suggestions. Option 1: The view method only. Should I just always declare @transaction.atomic at the view level and be done with it? @transaction.atomic def view_method(): # database operation manager_method() def manager_method(): # database operation model_method() def model_method(): # database operation another_model_method() def another_model_method(): # database operation Option 2: All of the methods. Or should I wrap every method that leads to multiple database operations? @transaction.atomic def view_method(): # database operation manager_method() @transaction.atomic(savepoint=False) def manager_method(): # database operation model_method() @transaction.atomic(savepoint=False) def model_method(): # database operation another_model_method() def another_model_method(): # database operation Option 3: Only the methods I expect will be β¦ -
Django make document filing structure + foreign keys
So... I am using django and sqlite3 and am trying to create a file storage system to link in with my database. I have 2 models: patient and appointment where patient has a 1 to many relationship with appointment. Each appointment needs to have multiple files associated with it so i created another model called 'appointmentFiles'. I want each appointment file to be uploaded to the path: patient/appointment/filename.txt . I also want it so that when i select the patient, the list of appointments to select from should be shown. It all sounds a little complex so forgive me if I didn`t explain it well enough. Thanks in advance! -
Can you use Python for both front end and back end using Django framework?
I'm watching the udemy Django tutorial that requires using JavaScript as the front-end and Python for the back-end: Can you replace JavaScript with Python? What are the advantages and disadvantages of that? -
Multiple Login Field Options for Django Rest Framework (JWT)
How can I override the django-rest-framework-jwt JSONWebTokenSerializer to allow for a user to login via either email, username or password. I see that as the suggested option in this github issue but am not sure how I'd override the default JSONWebTokenSerializer as its not among the JWT_AUTH settings. I want to be able to provide functionality as seen in this SO question where you can allow a Django User to login via any field you may have in the Custom user table -
Django Gunicorn Import Error: no module name wsgi
I use Python3.5.2 Django1.9 I use python -m venv venv/weather_station to create virtual evnironment (/home/user/venv) This is my project tree in Ubuntu /home/user/myproject: (export project=/home/user/myproject) myproject | βββ gunicorn.conf.py βββ static β βββ admin βββ weather_station βββ base β βββ migrations β βββ static β βββ templates βββ weather_station βββ settings In the gunicorn.conf.py: import os bind = '127.0.0.1:8080' worders = (os.sysconf('SC_NPROCESSORS_ONLN') * 2) + 1 loglevel = 'error' command = '/home/user/venv/weather_station/bin/gunicorn' pythonpath = '/home/user/myproject/weather_station' And in the /etc/nginx/sites-available/weather.conf: upstream weather_station { server 127.0.0.1:8080; } server { listen 80 default_server; listen 443 default ssl; server_name http://my_ip; client_max_body_size 10M; keepalive_timeout 15; location /static/ { alias /$project/static/; } location / { proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Protocol $scheme; proxy_pass http://myproject; When I run gunicorn -c gunicorn.conf.py weather_station.wsgi It showed ImportError: No module named 'weather_station.wsgi' Does any know the reason ? -
DRF @property field serializer Got AttributeError when attempting to get a value for field X on serializer Y
I'm using django rest framework for serialize and update a @property field, but i'm getting the error: AttributeError: Got AttributeError when attempting to get a value for field `template` on serializer `PublicationSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `Publication` instance. Original exception text was: 'NoneType' object has no attribute 'template'. i have the following models: class Publication(models.Model): @property def template(self): return self.apps.first().template class App(models.Model): publication = models.ForeignKey(Publication, related_name='apps') template = models.ForeignKey(Template, blank=True, null=True) class Template(models.Model): name = models.CharField(_('Public name'), max_length=255, db_column='nome') and the following serializer: class PublicationSerializer(serializers.ModelSerializer): template = TemplateSerializer(read_only=False) class Meta: model = models.Publication fields = ('template',) def update(self, instance, validated_data): template_data = validated_data.pop('template', None) instance = super().update(instance, validated_data) if template_data: instance.apps.all().update(template__id=template_data['id']) return instance This error happens when i use GET method to view and my Publication.apps is empty, and when i try to use POST method, i receive an empty OrderedDict() object. This looks like when my field is null the DRF can't discover field type, and when my i try to POST the serializer isn't working as well... -
File upload type validation in Django
I am trying to validate upload file type functionality in django. The allowed extension would be xml only. The admin will upload a xml file and then the table would be populated with the data from xml file. The model has no filefield but the form has. accounts/models.py -- class Coupling(models.Model): coupling_name = models.CharField(max_length=150, blank=False, null=True, default="") module_name = models.TextField(blank=False, null=True) def __str__(self): return self.coupling_name class Meta: verbose_name_plural = "Couplings" accounts/forms.py -- class CouplingUploadForm(forms.ModelForm): coupling_file = forms.FileField(label='XML File Upload:', required=True) class Meta: model = models.Coupling exclude = ['coupling_name', 'module_name'] settings.py UPLOAD_PATH = os.path.join(BASE_DIR, "static", "uploads") CONTENT_TYPES = ['xml'] MAX_UPLOAD_SIZE = "2621440" accounts/admin.py class couplingAdmin(admin.ModelAdmin): list_display = ('coupling_name','module_name') form = CouplingUploadForm admin.site.register(Coupling, couplingAdmin) I have gone through some SOF references and most of them have model.FileField but in my case I do not want to save the file in model. I tried with using magic -- https://djangosnippets.org/snippets/3039/ but I got an python-magic installation error -- Unable to find libmagic. So I would like to do it without magic. Any help/suggestion/link is highly appreciated. Thanks in advance. -
python manage.py crontab add, Unknow Command
I am trying to configure django-crontab by following this article, I have done all the setting but when I am trying to add cron job by the following command, I am not able to add the job. Django Version: 1.8.1 django-crontab: 0.7.1 Command Used: python manage.py crontab add ERROR MESSAGE: Unknown command: 'crontab' Type 'manage.py help' for usage. -
How to add data into two dependent table in django
Here's my files(below), I don't know how to add disease and symptoms into database (1-M relationship) webpage looks like: dname:|____________| type: |____________| symptom:|___________| |add| |finish| Add dname,type of disease Add 1st symptom of that disease and click add button Add 2nd symptom of that same disease and click add button Do for all symptoms click finish to complete insertion of 1st disease I am not able to manage this scenario. Since I have to add multiple symptoms how can I access Disease id because at this moment disease entry is not present in the database. - **models.py** class Disease(models.Model): did = models.AutoField(verbose_name='Disease Id', primary_key=True) dName = models.CharField(max_length=20) dtype = models.CharField(max_length=10) class Symptoms(models.Model): sid = models.AutoField(verbose_name='Symptoms Id',primary_key=True) sname = models.CharField(max_length=10) disease = models.ForeignKey(Disease, related_name='symptoms',on_delete=models.CASCADE) - **forms.py** class DiseaseForm(ModelForm): dname = forms.CharField() type = forms.ChoiceField() class Meta: model = Disease fields = "__all__" class SymptomForm(ModelForm): sname = forms.CharField() class Meta: model = Symptoms fields = "__all__" - **Views.py** class AddDisease(TemplateView): template_name = 'personal/disease.html' def get(self, request): dform = DiseaseForm() sform = SymptomForm() ddata = Disease.objects.all() sdata = Symptoms.objects.all() args = {'dform': dform,'sform': sform,'ddata':ddata,'sdata':sdata} return render(request,self.template_name,args) - **disease.html** <body> <form method="post">{% csrf_token %} {{ dform.as_p }} {{ sform.as_p }} <input type="button" class="btn" name="addbtn" β¦ -
How to change how disabled dropdown in form is rendered
I have 2 forms, the first of which has a dropdown which lets users a driver: Bob, Jim, Jack.... Assume the user opts for Bob and saves. class RouteUpdate(forms.ModelForm): class Meta: model= Route fields= [ 'route', 'driver', ... In the second form, I need to display Bob but the field must not be editable. Readonly isn't an option as this allows viewing (if not selection) of the other options. Disabling the field works, but it is still rendered as a dropdown list (disabled). Any suggestions on how to solve this. I'd be happy if there's a way to simply render "Bob as a variable in the template rather than as a form field. Alternatively how can I format the field? Thanks. -
primary key must be unique when extending table
I'm trying to add extend user model. I keep getting this error: Primary key is not unique. class UserExtended(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE,parent_link=True,primary_key=True) If I remove primary_key=True then I get the error instance.userextended.id does not exists well, of course it doesn't since now I dont have id. How do I get around this? -
I only get one column of database in json format
My model is named Color has 4 columns,which is Name & Background color & H1 color & P color.It is like But now I only can get one column(it is Name) of database in json format. It is like [ { "task_name": "white" }, { "task_name": "green" }, { "task_name": "pink" } ] I wanna get all columns of table in json format,but why can't I do it? models.py is from django.db import models # Create your models here. class Color(models.Model): name = models.CharField(max_length=255) background_color = models.CharField(max_length=255) h1_color = models.CharField(max_length=255) p_color = models.CharField(max_length=255) def __str__(self): return self.name serializers.py is from .models import Color from rest_framework import serializers class TaskSerializer(serializers.Serializer): task_name = serializers.CharField(max_length=100,source='name') class Meta: model = Color fields = ('name', 'background_color', 'h1_color', 'p_color', 'task_name') views.py is from django.shortcuts import render from .models import Color from .forms import ColorForm from .serializers import TaskSerializer from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from rest_framework import generics # Create your views here. def index(request): d = { 'colors': Color.objects.all(), 'form': ColorForm(), } return render(request, 'index.html', d) class TaskGet(generics.ListAPIView): serializer_class = TaskSerializer queryset = Color.objects.all() I cannot understand why Name can be get,but other cannot be get.In models.py,I resignated all β¦ -
Django and Angular4 web application
I am developing a application. application's front-end is developed by Angular4 and back-end should be developed in Django. I am new to the Djano framework can anyone suggest me how can i write rest api. Thanks in advance. -
Django. Create object ManyToManyField error
I am trying to write tests for my models. I try to create object like this: GiftEn.objects.create(gift_id=1, name="GiftEn", description="GiftEn description", short_description="GiftEn short description", categories='1', partner='1', addresses=2) But i get this error: File "/home/stasman/giver/giver/giver/gift/test_gift.py", line 29, in setUp addresses=2) ValueError: "<GiftEn: GiftEn, GiftEn description, GiftEn short description>" needs to have a value for field "giften" before this many-to-many relationship can be used. Here is my model: class GiftEn(models.Model): gift = models.ForeignKey(Private, on_delete=models.CASCADE) name = models.CharField(max_length=100) description = models.TextField(max_length=1000) short_description = models.TextField(max_length=500) categories = models.ManyToManyField(CategoryEn,) partner= models.ManyToManyField(Partner,) addresses= models.ManyToManyField(AddressWhereTakeGift,) def __str__(self): return '%s, %s, %s' % (self.name, self.description, self.short_description) class Meta: ordering = ('-gift__id',) How to create object for this model? -
Django, Gunicorn, Nginx, server error 500
Yes, this is a type of question we all dislike, but I am running out of possible solutions. I have tried to set up Nginx server with gunicorn runing django on my VPS and I have failed. I have used few tutorials so far, but I have not been successful yet. The sad part is, despite those tutorials are step by step, I did not manage to find an error in my settings. Moreover I think I made quite mess in those configs. Most of the tutorials shows quite "elaborate" configs, but for start I could not find any basic solution and I could not even tell which settings would be required. Anyway maybe You will point me at the right direction or will find my error. settings.py import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # 50 random characters. SECRET_KEY = '_my_secret_key_for_csrf_protection_' # SECURITY WARNING: don't run with debug turned on in production! PRODUCTION_ENABLE = True DEBUG = False ALLOWED_HOSTS = ['.biocounter.org', 'www.biocounter.org'] INSTALLED_APPS = [ 'main_page.apps.MainPageConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'biocounter_site.urls' TEMPLATES = [ { β¦ -
Globally set None default template rendering
Is it possible to set different rendering for None globally or per template? So I tell Django to render all None as - for example. There are pages like profile where we have tens of attributes and this would be slightly better than taking care of every possible None or rewriting every attribute from: {{ user.userprofile.attribute }} To {% firstof user.userprofile.attribute "-" %} or {{ user.userprofile.attribute|default:"-" }} -
How to prevent Django from auto converting datetime
Datetime value such as, day = "2017-9-2 00:00:00" , when used in template, index.html ... {{day}} ... it is auto converted by Django to Sept. 2, 2017, midnight. How can I disable this behavior? I want it to display in its original format, "2017-9-2 00:00:00". -
How to assign template tag-value in loop?
I have an HTML snippet which I like to re-use many times on a page. For instance <div id="custom"> <p>{{ object_name }}</p> <p>{{ object_value }}</p> <p>Static text</p> </div> How can I include this snippet on a page/template, where the values of the template tags or assigned dynamically? Currently I work with this solution: <div class="custom"> <p>{{ object_name_one }}</p> <p>{{ object_value_one }}</p> <p>Static text</p> </div> <div class="custom"> <p>{{ object_name_two }}</p> <p>{{ object_value_two }}</p> <p>Static text</p> </div> <div class="custom"> <p>{{ object_name_three }}</p> <p>{{ object_value_three }}</p> <p>Static text</p> </div> With a dictionary containing the respective values I pass in the view of this app. Instead of a list of objects containing the values, I assigned all values, for instance { ..., object_name_three = l[2].name, ... } -
Django - app's static files loading in a template, not in another
I have a crazy issue about static files in an app (Django-Autocomplete_Light, DAL) I'm using to implement form autocomplete.. https://github.com/yourlabs/django-autocomplete-light/issues/907 I'm able to load a DAL form in my home-page, which is extending base.html. The same DAL form does not work in another template which is extending the same base.html. I mean, the DAL JS files are not loaded in the other template.. the string {{ form.media }} is in base.html after jquery import, as required by the doc of DAL. What might be the problem? This is what is not loaded in the other template: <link href="/static/autocomplete_light/vendor/select2/dist/css/select2.css" type="text/css" media="all" rel="stylesheet" /> <link href="/static/autocomplete_light/select2.css" type="text/css" media="all" rel="stylesheet" /> <script type="text/javascript" src="/static/autocomplete_light/jquery.init.js"></script> <script type="text/javascript" src="/static/autocomplete_light/autocomplete.init.js"></script> <script type="text/javascript" src="/static/autocomplete_light/vendor/select2/dist/js/select2.full.js"></script> <script type="text/javascript" src="/static/autocomplete_light/select2.js"></script> -
TemplateDoesNotExist at /app/api/get
I wanna make a page that shows model's content in json format. Now I got an error, TemplateDoesNotExist at /app/api/get rest_framework/api.html . models.py is from django.db import models # Create your models here. class Color(models.Model): name = models.CharField(max_length=255) background_color = models.CharField(max_length=255) h1_color = models.CharField(max_length=255) p_color = models.CharField(max_length=255) def __str__(self): return self.name serializers.py is from .models import Color from rest_framework import serializers class TaskSerializer(serializers.Serializer): task_name = serializers.CharField(max_length=100,source='name') class Meta: model = Color fields = ('name', 'background_color', 'h1_color', 'p_color', 'task_name') urls.py is from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'api/get',views.TaskGet.as_view(),name='task-get') ] views.py is from django.shortcuts import render from .models import Color from .forms import ColorForm from .serializers import TaskSerializer from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status # Create your views here. def index(request): d = { 'colors': Color.objects.all(), 'form': ColorForm(), } return render(request, 'index.html', d) class TaskGet(APIView): def get(self, request, format=None): obj = Color.objects.all() serializers = TaskSerializer(obj, many=True) return Response(serializers.data, status.HTTP_200_OK) I did not write api.html anywhere.And I did not regist directory of frest_framework.So,I really cannot understand why this error happens.How can I fix this? -
how to count number of instances of a subclass in python?
I am trying to create a website where you can play songs from different albums. I think everything is working fine but I'm stuck with just one thing. In the details of the album I also wanted to display number of songs it contains. Here are my models and please suggest necessary code. from django.contrib.auth.models import Permission, User from django.db import models class Album(models.Model): user = models.ForeignKey(User, default=1) artist = models.CharField(max_length=250) album_title = models.CharField(max_length=500) genre = models.CharField(max_length=100) album_logo = models.FileField() is_favorite = models.BooleanField(default=False) def __str__(self): return self.album_title + ' - ' + self.artist class Song(models.Model): album = models.ForeignKey(Album, on_delete=models.CASCADE) song_title = models.CharField(max_length=250) audio_file = models.FileField(default='') is_favorite = models.BooleanField(default=False) def __str__(self): return self.song_title Please help me to display number of songs in album details. -
Django CSRF vs 2FA
I am using a contractor for web development and as part of admin panel security, he wants to implement CSRF. I have never used CSRF but multiple websites use 2FA. He said CSRF will take care of security and I don't need 2FA. I can't find articles related to comparing CSRF vs 2FA. Can you please comment the pros and cons of Django CSRF vs 2FA? -
Django admin - list_editable - foreign key attribute?
Is it possible to make editable ForeignKey attribute in change list? Every user has it's UserProfile object (OneToOneField). I want admin to be able to modify UserProfile expiry date from User change list. I can display the expiry in change list: class UserCustomAdmin(UserAdmin): list_display = ['id', 'username','email', 'last_login','userprofile__expiracia'] # list_editable = ['userprofile__expiracia'] exclude = ['groups','user_permissions'] inlines = [UserProfileInline] fieldsets = ( (None, {'fields': ('username', 'password')}), (_('Personal info'), {'fields': ('first_name', 'last_name', 'email')}), (_('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser', )}), (_('Important dates'), {'fields': ('last_login', 'date_joined')}), ) def userprofile__expiracia(self,obj): return obj.userprofile.expiracia But I can't add userprofile__expiracia to list_editable list. It raises: <class 'dashboard.admin.UserCustomAdmin'>: (admin.E121) The value of 'list_editable[0]' refers to 'userprofile__expiracia', which is not an attribute of 'auth.User'. How can I make it work? -
Django multiple files in one field
I am trying to make a database using sqlite3 with a field for multiple files so that i can have a file list on mt model info page. For example if the model is student and he needs to store an unspecified number of homework files and needs to be able to add, view, edit and delete them. Any help is much appreciated.