Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can I dinamically add new fields to my models/serializer/db ?
I´m developing an application using Django Rest Framework, and I have a problem. I´m trying to make the application as flexible as possible, so i wanted the possibility to dynamically add new fields to my models. For example: I have the model robot with fields id and version. But then the user wants to add a new field, the owner of the robot. What can i do so that with that I can can make the model and serializer reflect that new field. I can see how can i easilly add a new field to the database, but then the model and the serializer will not reflect this change. -
django-money form field in unit test
I am using django-money and I have a money field (value = MoneyField(…)) I want to test in a model form. This is the code: def test_post_valid(self): data = {'value': Money('99.99', currency='GBP'), } response = self.client.post(url, data) I get an error in the form parsing code stating: (Pdb++) form.errors {u'value': [u'This field is required.']} What is the correct format? -
Why doesn't my Django template render a ModelForm's id or pk field?
In Django 1.10, I'm prepopulating a ModelForm in a template using a record from the database. However, when I want to render the HTML for the form, it doesn't show the id (or pk) fields. Here is my models.py: from django.db import models class MyModel(models.Model): name = models.CharField(max_length=50) phone = models.CharField(max_length=50) In the database, I've added one MyModel record with name 'Alice' and phone '212-555-5555'. The id/primary key is 1. Here is my forms.py: from django import forms from . import models class TestForm(forms.ModelForm): class Meta: model = models.MyModel fields = ['id', 'name', 'phone'] Here is my views.py: from django.shortcuts import render from . import forms, models def test_page(request): m = models.MyModel.objects.get(name='Alice') prepopulatedForm = forms.TestForm(instance=m) return render(request, 'testproject/test_template.html', {'form': prepopulatedForm}) Here is my test_template.html: <h1>Test Page</h1> {{ form }} This renders the form on the page, prepopulated with 'Alice' and '212-555-5555': <h1>Test Page</h1> <tr><th><label for="id_name">Name:</label></th><td><input id="id_name" maxlength="50" name="name" type="text" value="Alice" required /></td></tr> <tr><th><label for="id_phone">Phone:</label></th><td><input id="id_phone" maxlength="50" name="phone" type="text" value="212-555-5555" required /></td></tr> My question is, why doesn't the id / primary key column appear in this form? I can't get it to render when I use this for the template either: <h1>Test Page</h1> {{ form.id }} {{ form.name }} {{ form.phone … -
I did not understand this behavior in Django
This is the directory structure of my Django project. When I am running python code of importing a model:from scraping.models import LinkVendorStandard from the file "framework_product_processing.py" it throws this exception: django.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_INDEX_TABLESPACE, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. When I add this code: import django django.setup() to initialize the django project settings, I get this exception: django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. I have the following 2 questions about this behavior: The file:"framework_product_process.py" in the django project structure is at the same level as "views.py" which can access model without having to setup the Django project.If this file is accessible from the same python path as that of view then why django.core.exceptions.ImproperlyConfigured? Even after adding import django;django.setup() code why I get django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.? Can anyone please explain? -
Links not working Django
In my base.html the links on the nav bar are not working for some reason. I've wrote it correctly, but when I hover over the link it doesn't do anything. <ul class="nav navbar-nav navbar-right"> <li class="active" role="presentation" data-aos="fade-down" data-aos-duration="900"><a href="{% url 'register' %}"><strong>Join Us?</strong></a></li> <li class="active" role="presentation" data-aos="fade-down" data-aos-duration="900"><a href="{% url 'login'%}"><strong>Log In</strong></a></li> Urls.py url('^delta/$', aircraft_delta, name='aircraft_delta'), #aircraft/detail/1 url('^aircraft/detail/(?P<id>\d+)/$', aircraft_detail, name='aircraft_detail'), #aircraft/ url(r'^aircraft/$', list_aircraft, name='aircraft_home'), #login/ url(r'^login/', login_view, name="login"), #logout/ url(r'^logout/', logout_view, name="logout"), #register/ url(r'^register/', register_view, name="register"), #upload/aircraft url(r'^upload/aircraft/$', aircraft_create), -
How to run Django and Wordpress using Nginx and Gunicorn at the same domain?
I have a Django app that is running on a domain e.g. www.example.com I want to create a Wordpress landing page, and point this landing page to the home url www.example.com and the wordpress admin site to www.example.com/admin or www.example.com/wp-admin. All the other URLs should be served by Django. So, I want: www.example.com -> wordpress www.example.com/admin or www.example.com/wp-admin -> wordpress All the other URLs to be served by Django Till now, this is my Nginx configuration using Django: upstream django_server { server unix:/path/to/gunicorn.sock fail_timeout=0; } server { listen 80; server_name www.example.com example.com client_max_body_size 4G; access_log /path/to/nginx-access.log; error_log /path/to/nginx-error.log; location /static/ { alias /path/to/static/; } location /media/ { alias /path/to/media/; } location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; if (!-f $request_filename) { proxy_pass http://django_server; break; } } error_page 500 502 503 504 /500.html; location = /500.html { root /path/to/static/; } } Any help would be greatly appreciated. -
Optimizing django select queries for Generic model
I have a generic model "EmailedItem" referencing a model "Item". I would like to loop over my list of items and print the time the email was sent. For now I am doing: items = Item.objects.all() for item in items: emailedItem = EmailedItem.objects.get(object_id=item.item_id) print emailedItem.created The problem is that this routine needs to be run pretty quickly and it takes a lot of time to do a select on the database for each item. Is there a better way to do so? Thanks a lot, -
how to disable elasticemail tracking url
How can I disable the tracking url on hyperlinks when using elasticemail I am using python(django) -
Django using more than 1 package for admin site
I am using 2 django packages: Admin sortable (For changing the order of models) and Django import export (For importing csv directly into my models). The problem is that if I add the 2 packages into my model admin e.g. class CategoryAdmin(SortableAdmin, ImportExportModelAdmin): they override each other. The buttons either show only for the Admin sortable or the Django import export. Is there anyway I can integrate both of them together? Alternatively, is there another package I can swap out so that I can achieve the same functions (1. change the order of models and 2. import csv directly into models) -
Store user specific data for each object
If you have eg an app that stores articles and each of these articles can be rated by the user. This rating is not visible to the other users and is user specific (no overall rating) ie each rating of the same article-object needs to be stored for each user. Currently I do this complete crazy stuff: class Article(models.Model): text = models.TextField(null=True, blank=True) def __unicode__(self): return self.text class UserArticleStorage(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, ) articles_rated_1 = models.ManyToManyField( Article, related_name="articles_rated_1", blank=True ) articles_rated_2 = models.ManyToManyField( Article, related_name="articles_rated_3", blank=True ) articles_rated_3 = models.ManyToManyField( Article, related_name="articles_rated_3", blank=True ) And I get them in the view by e.g. request.user.userarticlestorage.articles_rated_3 What is the normal way to store this user specific rating as an IntegerField? -
Tastypie api working with postman but not with python requests
I have tastypie api with api key authentication. Its working both ways for GET request, but for post request, it is not working. url = http://localhost:8000/api/path/?api_key=key&username=username in the view, when I tried to print request.user, it is regular/real user when request comes from postman. But with python requests, it is anonymous user. With python requests, I am doing this: url = http://localhost:8000/api/path/?api_key=key&username=username d = {"some": "data"} r = requests.post(url, data=json.dumps(d), headers={"content-type": "application/json"}) Please let me know for any questions. -
How do I make the navbar not stack?
I'm trying to make a that is horizontal but it is currently stacking, no matter the size of the screen. Current layout The template for the top_menu.html is - {% load site_tags wagtailcore_tags %} {% get_site_root as site_root %} <nav class="navbar navbar-default"> <div class="container-fluid"> <div class="navbar-header"> <a href="{% pageurl site_root %}" class="navbar-brand" title="{{ site_root.title }}"> Site Title </a> </div> <ul class="nav navbar-nav"> {% for menuitem in menuitems %} <li class="{% if menuitem.show_dropdown %}dropdown{% endif %}{% if menuitem.active %} active{% endif %}"> {% if menuitem.show_dropdown %} <a data-toggle="dropdown" class="dropdown-toggle" href="#">{{ menuitem.title }} <b class="caret"></b></a> {% top_menu_children parent=menuitem %} {% else %} <a href="{% pageurl menuitem %}">{{ menuitem.title }}</a> {% endif %} </li> {% endfor %} </ul> </div> </nav> and the top_menu_children.html is - {% load site_tags wagtailcore_tags %} <ul class="dropdown-menu"> {# Include link to parent because the parent link is a drop down #} <li><a href="{% pageurl parent %}">{{ parent.title }}</a></li> {% for child in menuitems_children %} <li><a href="{% pageurl child %}">{{ child.title }}</a></li> {% endfor %} </ul> The code is loaded on the base.html via {% block menu %} {% get_site_root as site_root %} {% top_menu parent=site_root calling_page=self %} {% endblock %} and the css/js is from Bootstrap and mdb. … -
django rest framework not return json
I have writen hello word programme and want to return json format data but it does not working. Please look into my code URL file from django.conf.urls import url from rest_framework.urlpatterns import format_suffix_patterns from login import views urlpatterns = [ url(r'^hello_world/$', views.hello_world), ] View file from django.shortcuts import render from rest_framework import status from rest_framework.response import Response from rest_framework.decorators import api_view # Create your views here. @api_view() def hello_world(request, format=None): return Response({"message": "Hello, world!"}) http://localhost:8000/login/hello_world/ hit a url get an error TemplateDoesNotExist at /login/hello_world/ rest_framework/api.html i want this data in json format -
How to make a cookie in Django (Python)
When I use this application (Filedownload, jquery) https://jqueryfiledownload.apphb.com/ There are some important issue in order for this plugin to work you must also write a cookie in an http header "Set-Cookie: fileDownload=true; path=/" How can I make a cookie in Django framework? (fileDownload, path) -
Conditionally apply login_required decorator in Django
I have a set of function in views.py which are currently only user-accessible. I'm asked to make it publicly accessible and currently I am using the @login_required decorator in my views. Is there a way to apply this decorator conditionally based on the object being served? For example, part of my views.py: @login_required def details(request, object_id): o = get_object_or_404(Model, pk=object_id) if o.user_id == request.user.pk: return render(request, 'app/details.html') else: return redirect('app:home') What I want to do: if o.is_public: @login_required def details(request, object_id): o = get_object_or_404(Model, pk=object_id) if o.user_id == request.user.pk: return render(request, 'app/details.html') else: return redirect('app:home') Of course, the code doesn't work since I need to first get the object. I believe there might be an elegant solution using Django as this is quite a common feature in web applications but I've gone through the docs to no avail. I think I should surround the @login_required decorator with another decorator but I'm not too familiar with decorators in Python. Any help is appreciated. -
Django 1.9.5 filebrowser 3.7.2 image not showing and in template image url is wrong
filebrowser 127.0.0.1:8000/admin/filebrowser/browse/? upload file success upload file image image url href: href="media/uploads/chrysanthemum.jpg" but the url is wrong. "/media/uploads/chrysanthemum.jpg" this url is right. "_versions/chrysanthemum_admin_thumbnail.jpg"> is wrong "/media/_versions/chrysanthemum_admin_thumbnail.jpg"> is right. settings.py: INSTALLED_APPS = [ 'grappelli', 'filebrowser', 'django.contrib.admin', ] STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = ( ("images",os.path.join(STATIC_ROOT, 'images').replace('\\', '/')), ("css", os.path.join(STATIC_ROOT, 'css').replace('\\', '/')), ("js", os.path.join(STATIC_ROOT, 'js').replace('\\', '/')), ) ADMIN_MEDIA_PREFIX = STATIC_URL + "grappelli/" site.directory = "media/uploads/" site.storage.location = BASE_DIR MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media').replace('\\','/') directory: directory -
Django, In this model is "null = True" bad or good?
CODE : class Contentsprofile(models.Model): imagepost = models.OneToOneField(Imagepost, null=True, blank=True) post = models.OneToOneField(Post, null=True, blank=True) comment = models.OneToOneField(Comment, null=True, blank=True) description = models.TextField(max_length=100, blank=True, null=True) postprofileCreatedAt = models.DateTimeField(auto_now_add=True) postprofileUpdatedAt = models.DateTimeField(auto_now=True) Class(like Imagepost, Post, Comment) for OneToOneField's 'to= ' arguments will must get Contentsprofile. And Contentsprofile will have only one models.OneToOneField value. If title = models.OneToOneField(Title, null=True, blank=True) have any value, the other OneToOneField will get null or " "value(I mean, empty value). What i'm considering is whether NOT NULL will be good for SQL qurey performane or not. Being newbie on programming, i don't know what is good choice. Would you give some advice? -
Django force user to fill out form on login
I need to have certain users fill out a specific form on login. Django should redirect the user to the form, whenever a certain condition is True for that user. I used a custom middleware to do it, but I am curious if there is a better approach. Any ideas? -
Defining and using a function within a Django custom command class
My script is supposed to transfer data from a source DB to two target ones. As the title says I'm using Django custom command to achieve that, my SQL library of choice is SQLAlchemy. Now - the command is a class, I have a bunch of different subclasses representing different entities and there's a great mess in the code that is supposed to update their representations in target databases, so below I'll try to recreate a representative fragment of code illustrating what I'm trying to do: class Command(BaseCommand): [system_constr_eng, system_def_eng] = [create_engine("sqlite://"), create_engine("sqlite://")] system_constr_eng.execute("ATTACH DATABASE 'system_constr.db' AS system_constr") system_def_eng.execute("ATTACH DATABASE 'system_def.db' AS system_def") common_md = MetaData() system_constr_db = declarative_base(bind=system_constr_eng,metadata=common_md,name='system_constr_db') system_def_db = declarative_base(bind=system_def_eng,metadata=common_md,name='system_def_db') Session = sessionmaker(bind=system_constr_eng) session = Session() class SrcLim(system_def_db): __tablename__ = 'Source_limits' min_val = Column(Float) max_val = Column(Float) type = Column(Integer, nullable=False, primary_key=True) hour = Column(Integer, nullable=False, primary_key=True) source = Column(Integer, ForeignKey('Sources._id'), primary_key=True) @staticmethod def update_SrcLim(minv, maxv, type, hour, source): if session.query(LimitZrodla).filter_by(typ=type).filter_by(zrodlo=source).filter_by(godz=hour).count(): session.query(LimitZrodla).filter_by(typ=type).filter_by(zrodlo=source).filter_by( godz=hour).max_val = maxv session.query(LimitZrodla).filter_by(typ=type).filter_by(zrodlo=source).filter_by( godz=hour).min_val = minv else: entity = LimitZrodla(min_val=minv, max_val=maxv, typ=type, godz=hour, zrodlo=source) session.add(entity) The code above is just my best shot at recreating what I'm dealing with, there may be typos, some names were changed from Polish to English to make it less … -
What's the differences between has_object_permission and has_permission in DRF:Permission?
I am confused with the BasePermission in Django-rest-framework. Here i defined a class: IsAuthenticatedAndOwner. class IsAuthenticatedAndOwner(BasePermission): message = 'You must be the owner of this object.' def has_permission(self, request, view): return False def has_object_permission(self, request, view, obj): # return obj.user == request.user return False Using in views.py class StudentUpdateAPIView(RetrieveUpdateAPIView): serializer_class = StudentCreateUpdateSerializer queryset = Student.objects.all() lookup_field = 'pk' permissions_classes = [IsAuthenticatedAndOwner] But it doesn't work at all. And i used to define this class: IsNotAuthenticated class IsNotAuthenticated(BasePermission): message = 'You are already logged in.' def has_permission(self, request, view): return not request.user.is_authenticated() It works well in the function class UserCreateAPIView(CreateAPIView): serializer_class = UserCreateSerializer queryset = User.objects.all() permission_classes = [IsNotAuthenticated] So, what's the differences between the examples above, and function has_object_permission&has_permission? -
Signal when model finishes saving in django-rest-framework
I'm creating django app which will send message through websocket when certain model is created. My model looks like this: class Notification(model.Model): owner = models.ForeignKey(User) datetime = models.DateTimeField(auto_now_add=True) resources = models.ManyToManyField(Resource, related_name='notifications', blank=True) recipients = models.ManyToManyField(User, related_name='notifications', blank=True) I want to send signal when model finishes saving. If I use m2m_changed signal then signal won't be called if m2m field are left blank. Even if fields are not empty I need to bind m2m_changed to both relations, which causes multiple message sent via websocket. If I use post_save then m2m_field are empty inside post_save receiver. Are there any other options? I tried writing custom signal but I'm not that of an expert in django and I have no idea how to know when model is finished with saving. Thanks -
Admin : Select category -> show subcategory using django
how to show category and subcategory : Admin : Select category -> show subcategory using Django class Category(models.Model): categoryName=models.CharField(max_length=100) def __unicode__(self): return self.categoryName class Subcategory(models.Model): subcategoryName=models.CharField(max_length=100) category = models.ForeignKey(Category, null=True, blank=True) def __unicode__(self): return self.subcategoryName class Product(models.Model): productName=models.CharField(max_length=100) productImage=models.ImageField(upload_to='documents/') category = models.ForeignKey(Category, null=True, blank=True) subcategory = models.ForeignKey(Subcategory, null=True, blank=True) def __unicode__(self): return self.productName admin product form -
How to link to same page and add a GET parameter? Additive GET parameters?
I have a page with a table and pagination. I can flick through the pages with <a href="?page={{ myobj.next_page_number }}"> <a href="?page={{ myobj.previous_page_number }}"> Now I want to add ordering to the tables. <th><a href="?sort=date&order=asc">Date</a></th> In the given example, I lose either the pagination or the ordering upon clicking one of the hyperlinks. I need to find a way to make the GET parameters additive. So when I am on page 2, the latter should show <th><a href="?page=2&sort=date&order=asc">Date</a></th> I hope there is a built-in solution for that. I am on Django 1.10, but wouldn't mind upgrading to 1.11 if necessary. -
Embedded authentication + LDAP user verification in Django. How to?
Intro Django version: 1.10 Python version: 3.5.2 I'm trying to implement an authentication based on a LDAP condition and I can't get my head around on how to achieve this. My project already uses Django's built-in authentication system, which works great and looks like this: # urls.py from django.conf.urls import include, url from django.contrib import admin from django.contrib.auth import views from coffee_app.forms import LoginForm urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'', include('coffee_app.urls')), url(r'^login/$', views.login, {'template_name': 'login.html', 'authentication_form': LoginForm}, name='login'), url(r'^logout/$', views.logout, {'next_page': '/login'}, name='logout'), ] # forms.py from django.contrib.auth.forms import AuthenticationForm from django import forms class LoginForm(AuthenticationForm): username = forms.CharField(label="Username", max_length=32, widget=forms.TextInput(attrs={ 'class': 'form-control', 'name': 'username' })) password = forms.CharField(label="Password", max_length=20, widget=forms.PasswordInput(attrs={ 'class': 'form-control', 'name': 'password' })) <!--login.html (relevant part)--> <form class="form-horizontal" action="{% url 'login' %}" method="post" id="contact_form"> {% csrf_token %} <fieldset> <div class="form-group"> <label class="col-md-4 control-label">{{ form.username.label_tag }}</label> <div class="col-md-4 inputGroupContainer"> <div class="input-group"> <span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span> {{ form.username }} </div> </div> </div> <div class="form-group"> <label class="col-md-4 control-label" >{{ form.password.label_tag }}</label> <div class="col-md-4 inputGroupContainer"> <div class="input-group"> <span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span> {{ form.password }} </div> </div> </div> <div class="form-group"> <label class="col-md-4 control-label"></label> <div class="col-md-4 text-center"> <br> <button value="login" type="submit" class="btn btn-warning" > LOG IN <span class="glyphicon glyphicon-send"></span> </button> </div> </div> </fieldset> … -
Django, Nginx & Varnish gzip params to be activated
I have a Django app with Gunicorn, going throught Varnish and served with Nginx. MyDjangoApp --> Gunicorn --> Varnish --> Nginx --> Client Which one of the gzip params I have to keep ? In Django ? MIDDLEWARE_CLASSES = ( # Remove Django Gzip middleware as we already have it in nginx ? 'django.middleware.gzip.GZipMiddleware', .... In Nginx ? http { gzip on; gzip_disable "msie6"; gzip_vary on; gzip_proxied any; .... In Varnish ? sub vcl_backend_response { if (bereq.url ~ "html$") { set beresp.do_gzip = true; } .... Do I have to activate on all confs or Just Nginx ? If I activate the GZipMiddleware in Django for ex, I should not need to activate it on Varnish & Nginx or I'm missing something ?