Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
get the text nicely aligned in Django site
I have a site and the following templates represent information: mysite/portfolio/templates/base_generic.html <!DOCTYPE html> <html lang="en"> <head> {% block title %}<title>My portfolio web-site</title>{% endblock %} <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <!-- Add additional CSS in static file --> {% load static %} <link rel="stylesheet" href="{% static 'css/styles.css' %}"> </head> <style> body { font-family: Georgia, Times, "Times New Roman", serif; background: #FFF8DC; } </style> <body> <div class="container-fluid"> <div class="row"> <div class="col-sm-2"> {% block sidebar %} <ul class="sidebar-nav"> <li><a href="{% url 'v_index' %}">Home</a></li> <li><a href="{% url 'skills' %}">All skills</a></li> <li><a href="{% url 'exp' %}">All experience</a></li> <li><a href="{% url 'cert' %}">All certifications</a></li> <li><a href="{% url 'admin:index' %}">Admin panel</a></li> <!--<li><a href="{% url 'logout' %}">Logout</a></li>--> {% if user.is_authenticated %} <li>User: {{ user.get_username }}</li> <li><a href="{% url 'logout'%}?next={{request.path}}">Logout</a></li> {% else %} <li><a href="{% url 'login'%}?next={{request.path}}">Login</a></li> {% endif %} </ul> {% endblock %} </div> <div class="col-sm-10 "> {% block content %}{% endblock %} {% block pagination %} {% if is_paginated %} <div class="pagination"> <span class="page-links"> {% if page_obj.has_previous %} <a href="{{ request.path }}?page={{ page_obj.previous_page_number }}">previous</a> {% endif %} <span class="page-current"> Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}. </span> {% if page_obj.has_next %} <a href="{{ request.path }}?page={{ page_obj.next_page_number }}">next</a> {% … -
Django, each user having their own table of a model
A little background. I've been developing the core code of an application in python, and now I want to implement it as a website for the user, so I've been learning Django and have come across a problem and not sure where to go with it. I also have little experience dealing with databases Each user would be able to populate their own list, each with the same attributes. What seems to be the solution is to create a single model defining the attributes etc..., and then the user save records to this, and at the same time very frequently changing the values of the attributes of the records they have added (maybe every 5~10 seconds or so), using filters to filter down to their user ID. Each user would add on average 4000 records to this model, so say just for 1000 users, this table would have 4 million rows, 10,000 users we get 40million rows. To me this seems it would impact the speed of content delivery a lot? To me a faster solution would be to define the model, and then for each user to have their own instance of this table of 4000ish records. From what … -
Ordering Django models.py alphabetically : refering to a model defined below
Quick question, I was trying to cleanup my models.py that was a bit all over the place; figured that ordering them alphabetically would be smart... Problem Some models refer to other models (via Foreign Keys) that are now defined below them in the file. I'm sure it's a easy fix, what should i do ? from django.db import models class Craft(models.Model): subdpt = models.ForeignKey(Subdepartment, on_delete=models.CASCADE) #### UNDEFINED NAME SUBDEPARTMENT ### title = models.CharField(max_length = 200) description = models.CharField(max_length = 200, blank = True) def __str__(self): return self.title class Subdepartment(models.Model): subdpt_name = models.CharField(max_length=200) def __str__(self): return self.subdpt_name class Meta: permissions = ( ("can_add", "Can add items in app"), ("can_edit", "Can edit items in app"), ) -
(django) paginator page_obj.page_range creates to many pages
When I'm using he paginator it always creates one unnescescairy page if the last page is fullfilled. On the unnescescairy page is the same content like the page before. I tried pagination, so I made a bit experience with that: I have 2 items in the list. If paginate_by is one, I get three pages. On the first is the first item, on the second and third page the second item. If I set paginate_by to two, I get two pages, both containing both items. If I set paginate_by to three or higher, I get what I wanted: not more pages than needed. If 2 items were enough that would be ok, but I want to be able to add items. My example code: (I don't know whether it causes the problem or not.) The relevant part of the paginated template: {% for i in paginator.page_range %} {% ifequal page_obj.number i %} <p>Hier</p> {% else %} <p>{{ i }}</p> {% endifequal %} {% endfor %} The view: class ArchivePagedView(generic.ListView): model = Article template_name = 'manifest/archive.html' paginate_by = 1 #self.kwargs['entries_per_page'] context_object_name = 'article_list' def get_context_data(self, **kwargs): context = super(ArchivePagedView, self).get_context_data(**kwargs) article_list = Article.published.all() #===================================== paginator = Paginator(article_list, self.paginate_by) page = self.request.GET.get('page') … -
django-mptt the way to change the hierarchy automatically and dynamically in response to the current get parameter in url
I want to make filtering system like the sidemenu in Gumtree using Django-mptt. I have hierarchy like so: g1 --g11 --g111 --g112 --g12 --g121 --g122 g2 --g21 --g211 --g212 --g22 --g221 --g222 When you come to my website, you can see g1 g2 it shows only top categories that has no parent. I can write this like so: nodes = Genre.objects.filter(level=0) And then, for example, when you click the link of g1, hierarchy changes like so: g1 --g11 --g12 I can write like so: nodes = Genre.objects.filter(tree_id=1).filter(level__lte=1) And then, if you click the g11, it shows like so: g1 --g11 --g111 --g112 But I don't know how to write down code to express it. if I write like: nodes = Genre.objects.filter(tree_id=1) it shows: g1 --g11 --g111 --g112 --g12 --g121 --g122 but I don't want to show g12, its children: g121 and g122. Can you teach me, please? And I want to know about the way to change the hierarchy automatically and dynamically in response to the current get parameter in url. For example, when we have get parameter "g1" in url currently like "?genre=g1", we will see below like I said above: g1 --g11 --g12 if we have "?genre=g12", g1 … -
How can I perform insertions in django with lookups and condition dependent insertions?
I am trying to optimise database insertion of a large data set through django. Here is a simple sample model that should be enough to demonstrate the issue I face. class School(models.Model): name = models.CharField(max_length=32) postcode = models.CharField(max_length=8) class Student(models.Model): name = models.CharField(max_length=32) school = models.ForeignKey(School) last_updated = models.DateTimeField(blank=True, null=True) first_registered = models.DateTimeField(blank=True, null=True) Given the example model above. I can currently create rows in the following manner school = app.models.School.objects.get_or_create(name='School 1', postcode='AB12 3CD') student = app.models.Student.objects.create(name='Student 1', school=school[0]) This works well for the simple "getting started" case, but there are potential issues when expanding to a larger data set and more complex models with more relationships. The school entry requires a database round trip every time. Race conditions are possible. I'll define a more real world problem. There is a master list of school and student data The students and school list is updated daily The data comes in no particular order Previous data may be present, but could also be removed Previous data may also be updated (outside scope of this question) If it is removed then that indicates the student is no longer a student In essence, each day a list is available with the current snapshot … -
OAuth2 in Django Rest Framework
I have developed an API with Django Rest Framework (DRF) and everything is working right. However, I need to implement OAuth2 on it. The question is, I can implement OAuth2 from scratch, but I already have a PHP API ready, which already has all the necessary table structure for the authentication system. Can I change how OAuth2 works in DRF to look at tables that already exist? I'm using the Django OAuth Toolkit for implementation. -
Dynamic dropdown in Django forms
I am trying to make dynamic dropdown option list in my django forms, but i cant display it by first dictionary 'key'. My choice dictionary in forms is containing two keys, 'name' and 'email'. And it is displaying options by second key('email'), instead of 'name'. Here is what i mean My model: class Supervisors(models.Model): name = models.CharField(max_length=200) email = models.EmailField(max_length=100) My form: supervisors = [] all_supervisors = Supervisors.objects.all() for user in all_supervisors: one_supervisor = {user.name.__str__() : user.name, user.email.__str__() : user.email} supervisors.append(one_supervisor) class PrintForm(forms.Form): contact_name = forms.CharField(required=True) contact_email = forms.EmailField(required=True) supervisor = forms.ChoiceField(choices=supervisors) content = forms.CharField( required=True, widget=forms.Textarea ) And my view: def print(request): if request.method == 'POST': form = PrintForm(data=request.POST, request = request) if form.is_valid(): contact_name = request.POST.get( 'contact_name' , '') contact_email = request.POST.get( 'contact_email' , '') form_content = request.POST.get('content', '') supervisor = form.cleaned_data['supervisor'] supervisor = dict(form.fields['supervisor'].choices)[supervisor] # Email the profile with the # contact information template = get_template('threeD/email/contact_template_for_printing.txt') context = Context({ 'contact_name': contact_name, 'supervisor': supervisor, 'contact_email': contact_email, 'form_content': form_content, }) content = template.render(context) email = EmailMessage( "New message from " + contact_name, content, "Message - " + supervisor + ' ', [supervisor], headers={'Reply-To': contact_email} ) email.send() messages.success(request, "Thank you for your message.") return redirect('/index/print/') else: form = PrintForm(request=request) context_dict … -
show fields in get all django panel
I am new at django panel, I want to show some particular fields in the index method but I see "NameClass Object" intead. I tried using fields and list_display but it didn't work. from django.contrib import admin from base_proyecto.models import * class AutorAdmin(admin.ModelAdmin): fields = ('nombre') list_display = ('nombre') admin.site.register(Autor) -
Django Account Activation Link can't use twice?
I am using Django-Registraion-Redux for registering user. When user get register and click on account activation link it gets activated but if user again click on same the link it show the same message as previous. This is not technically correct. So how to restrict user to click on the same link or how to show proper message to him -
Spirit forum in Django
Can anybody here help to to run spirit as a new Django project, I want to run that but there is no manage file. And there is no guide how to run the spirit forum as stand alone project. If anybody please provide a video or screenshot to setup the spirit it will be very helpful. I tried a lot but I failed so I am asking for help Related links: http://spirit-project.com https://github.com/nitely/Spirit thank you -
How to build a SaaS Application with Django?
I've been working on a recent project that requires the usage of a SaaS Application Model in the following way: Every User will have a unique dashboard with their own relevant data (e.g. Profile, No. Of posts, friends, etc.) Teams: Users are able to create, join or invite other members to join teams. Every user must only be a part of 1 team. And teams should have another team dashboard. Subscriptions: At least 3 different plans to choose from and define the limitations specifically Team Billing: Instead of individual subscription plans, teams should be allowed their own plans. Two factor authentication. I'm fairly new do Django and this is an experiment project I am working on to learn more in depth about Django and Python and would really appreciate if someone could give out some pointers as to how to go about building something like this. I've checked out Django Multi-tenant schemas and it seemed quite straightforward but I couldn't figure out how would team billing and subscription models be implemented. Any tips/guidance is highly appreciated. -
Django rest framework: Get detail view using a field other than primary key integer id
My Product model has an extra field named "product_id" which is a uuid string. Now I can get the product details based on the primary key id. I want to change this to get the product details using "product_id" field. My current urls.py url(r'^products/(?P<pk>[0-9]+)/$', views.ProductDetailCustom.as_view(), name='product-detail'), Now am calling like this. http://127.0.0.1:8000/api/v1/products/1460 I want this should be like this. http://127.0.0.1:8000/api/v1/products/04396134-3c90-ea7b-24ba-1fb0db11dbe5 views.py class ProductDetailCustom(generics.RetrieveAPIView): queryset = Product.objects.all() serializer_class = ProductCustomSerializer serializer.py class ProductCustomSerializer(serializers.ModelSerializer): class Meta: model = Product fields = ('url', 'id','product_id', 'title', 'description','structure','date_created',) I think I have to include a look field to achive this. -
How to use $http.post of angular js to post data in django forms
I am trying to post the form data without page refresh,first i used ajax call to prevent page refresh. Here is my ajax code for post:- $('#post-form').on('submit', function(event){ event.preventDefault(); console.log("form submitted!") // sanity check create_post(); function create_post() { console.log("create post is working!") // sanity check $.ajax({ url : "blog/create_post/", // the endpoint type : "POST", // http method data : { body : $('#id_text').val(), csrfmiddlewaretoken : $('input[name=csrfmiddlewaretoken]').val() }, // data sent with the post request // handle a successful response success : function(json) { console.log("Hey Its Done please Chcek the Updated List") console.log(json); // log the returned json to the console }, // handle a non-successful response error : function(xhr,errmsg,err) { $('#results').html("<div class='alert-box alert radius' data-alert>Oops! We have encountered an error: "+errmsg+ " <a href='#' class='close'>&times;</a></div>"); // add the error to the dom console.log(xhr.status + ": " + xhr.responseText); // provide a bit more info about the error to the console } }); }; }); This is my views.py:- def index(request): response_data= {} return JsonResponse({"body":list(q.text for q in Blog.objects.order_by('-id')[:10])}) def create_post(request): if request.method == 'POST': post_text = request.POST.get('body') post = Blog(text=post_text) post.save() return JsonResponse({"body":list(q.text for q in Blog.objects.order_by('-id')[:10])}) else: return HttpResponse( json.dumps({"nothing to see": "this isn't happening"}), content_type="application/json" ) So … -
How to get access to another module in same module in get_absolute_url with url revesre?
I need to reverse the URL in the module "Season" the structure of the URL goes like this, Series / serial_slug / season_slug / series_slug / But to get access to the seasons of the series you need so Series / serial_slug / season_slug / But I do not know how to access the serial module, if I access through ForeignKey, then the model should be on top of the Season model, and then the series will not work as it needs a model serial then a model season! Or who can help, how to correctly redistribute these models, I tried in different ways, and only in that position they work, and that is, Model Season / then model Serial / then model Series this is urls.py from django.conf.urls import include, url from .views import homeview, post_of_serial, post_of_season, post_of_serie urlpatterns = [ url(r'^$', homeview, name='homeview'), # /series/ url(r'^(?P<serial_slug>[\w-]+)/$', post_of_serial, name='post_of_serial'), # /series/Prison_Break/ url(r'^(?P<serial_slug>[\w-]+)/(?P<season_slug>[\w-]+)/$', post_of_season, name='post_of_season'), # /series/Prison_Break/season_5/ url(r'^(?P<serial_slug>[\w-]+)/(?P<season_slug>[\w-]+)/(?P<series_slug>[\w-]+)/$', post_of_serie, name='post_of_serie'), # /series/Prison_Break/season_5/2/ ] this is main piece of modules.py class Season(models.Model): id = models.AutoField(primary_key=True) name_of_the_season = models.CharField(max_length=40) slug = models.SlugField(unique=False, blank=True) name_for_easy_access = models.CharField(max_length=40) preview_of_season = models.ImageField(upload_to="previews/preview_for_season/", default=None,width_field="width_field", height_field="height_field") width_field = models.IntegerField(default=150) height_field = models.IntegerField(default=150) number_of_released_series = models.IntegerField(default=0) year = … -
Do a certain backend operation on clicking Django Admin save button
In a library system, I have the Userbooks (refers to books issued by a user) object registered with Django Admin. And when Django Admin creates a Userbooks object and saves it, the Book object (refers to books in library, also registered with Django Admin) associated with that UserBook with a one_to_one relationship, needs to have its boolean field 'is_issued' to be set to true. How can I do this backend action when Admin clicks the 'save' button? -
How to make relation between one model to another two models
I am creating simple forum site using Django framework, and I've created comment model, at this moment my comment model has OneToOne relation with Post, it means that every moment belong to specific post, but there is also another feature that I want to provide. Every comment model should has possibility to be related to Post object OR to Answer model. Answer model it is just as in Stack Overflow, you add a Post and another user can add an answer to it. I want to mention that answer is too related with Post with OneToOne relation I think it will be sufficient and dosen't need edition. Summarizing: How to allow adding comments to Post object or Answer object? Also I want to say that I was considering creating two comments models, namely PostComment, and AnswerComment but I've got a conclusion that is really bad solution. class Post(models.Model): subject = models.CharField(max_length=100) description = models.TextField(null=True) section = models.ForeignKey(Section, on_delete=models.CASCADE, null=True) author = models.ForeignKey(User, null=True, blank=True) created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) slug = models.SlugField(max_length=100, null=True) active = models.BooleanField(default=True) def __str__(self): return self.subject def publish(self): self.published_date = timezone.now() self.save() def close(self): self.active = False self.save() class Comment(models.Model): content = models.CharField(max_length=600) post … -
Error Setting up Django with uwsgi and nginx
I am setting up my Django (Tastypie) application with Nginx and uwsgi. But I am having trouble setting it up. /etc/uwsgi/emperor.ini [uwsgi] emperor = etc/uwsgi/sites logto = /var/log/uwsgi /etc/uwsgi/sites/ams.ini [uwsgi] project = AMS base = /home/user chdir = %(base)/%(project) #home = %(base)/Env/%(project) module = %(project).wsgi:application master = true processes = 5 socket = %(base)/%(project)/ams.sock chmod-socket = 666 uid = user gid = www-data vacuum = true logto = /var/log/uwsgi/log.log /etc/init/uwsgi.conf description "uWSGI application server in Emperor mode" start on runlevel [2345] stop on runlevel [!2345] setuid user setgid www-data exec /usr/local/bin/uwsgi --http :8000 --emperor /etc/uwsgi/sites /etc/systemd/system/uwsgi.service [Unit] Description=uWSGI Emperor service After=syslog.target [Service] ExecStart=/usr/local/bin/uwsgi --http :8000 --emperor /etc/uwsgi/sites Restart=always KillSignal=SIGQUIT Type=notify StandardError=syslog NotifyAccess=all [Install] WantedBy=multi-user.target /etc/nginx/nginx.conf ser www-data; worker_processes auto; pid /run/nginx.pid; events { worker_connections 768; } http { sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 2048; include /etc/nginx/mime.types; default_type application/octet-stream; ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE ssl_prefer_server_ciphers on; access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; gzip on; gzip_disable "msie6"; include /etc/nginx/conf.d/*.conf; include /etc/nginx/sites-enabled/*; } /etc/nginx/sites-available/ams.conf server{ listen 999; server_name _; error_log /home/user/AMS/logs/nginx_error.log; access_log /home/user/AMS/logs/nginx_access.log; charset utf-8; location /static/ { root /home/user/AMS/static/; } location / { uwsgi_pass unix:/home/user/AMS/ams.sock; include uwsgi_params; } } If I run uwsgi using the following … -
Filter the data for particular 15 days of all years in django
I am trying to print the data for particular 15 days of every year. For example to get the Employee's details who has birthdays with in 15 days. ` today = datetime.now() start_day = today.day start_month = today.month end_day = today + timedelta(days=15) end_date = end_day.day end_month = end_day.month user_dob_obj = UserProfile.objects.filter(Q(date_of_birth__month__gte=start_month, date_of_birth__day__gte=start_day) & Q(date_of_birth__month__lte=end_month, date_of_birth__day__lte=end_date)) ` -
django-mptt How to show hierarchy like my example?
I have a hierarchy using Django-mptt like below. g1 --g11 ----g111 ----g112 --g12 ----g121 ----g122 g2 --g21 ----g211 ----g212 --g22 ----g221 ----g222 First, I want to show hierarchy like below with no get parameters in url. g1 g2 like this, only top categories that have no parent. And then, if click the g1 or g2, For example, g1, I want to show g1 and g1's children like below. g1 --g11 --g12 In here, I don't want to show g11's children and g12's children, just g1 and g1's children(g11 and g12). Next, if click the g11, show like below. g1 --g11 ----g111 ----g112 How to make it like above. Please help me. Another source code is so: # models.py class Genre(MPTTModel): parent = TreeForeignKey('self', null=True, blank=True, related_name='children', db_index=True) name = models.CharField(max_length=50) def __str__(self): return self.name class MPTTMeta: order_insertion_by = ['name'] # views.py return render(request, 'classifieds/index.html', {'nodes': Genre.objects.all()}) # template {% load mptt_tags %} <ul> {% recursetree nodes %} <li> <a href="?{% url_replace request 'genre' node.pk %}">{{ node.name }}</a> {% if not node.is_leaf_node %} <ul class="children"> <a href="?{% url_replace request 'genre' children.pk %}">{{ children }}</a> </ul> {% endif %} </li> {% endrecursetree %} </ul> -
(django) url regex doesn't match
The url I try: http://127.0.0.1:8000/manifest/archive/?page=1. The regex pattern: (The original one I tried): r'^archive/(?P<reverse>[n]{0,1})/?\?page=[0-9]+/?' (An easier I also tried in the python console.) r'^archive/\?page=[0-9]+' (The easiest possible, just to try.) r'^archive/\?page=1' (But I escaped the question mark in the right way, don't I?) I tried all of these regexes in the python console and they worked nice, so I think the problem isn't about a wrong regex. So: why don't this work? Optional information: the projects url-conf: urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', RedirectView.as_view(url=reverse_lazy('manifest:index'))), url(r'^manifest/', include('manifest.urls', namespace='manifest')), ] note: the url 127.0.0.1:8000/manifest/index matches as it should, so can't be about everything is made wrong. -
django next url not working correctly
I have created a login page using default django(1.9.5) auth_view and the urls.py looks like this url(r'^login/$', auth_views.login, {"template_name": 'login.html'}, name='login'),`` and used the django specified html to generate the form and the html looks like this <form method="post" action="{% url 'login' %}?next={{next}}"> {% csrf_token %} <table class="login-form"> <tr> <td class="input-label">{{ form.username.label_tag }}</td> <td class="input-field"><input class="form-control" id="{{ form.username.id_for_label }}" maxlength="30" name="{{ form.username.html_name }}" type="text" /> </td> </tr> <tr> <td class="input-label">{{ form.password.label_tag }}</td> <td class="input-field"><input class="form-control" id="{{ form.password.id_for_label }}" maxlength="30" name="{{ form.password.html_name }}" type="password" /> </td> </tr> </table> {# Assumes you setup the password_reset view in your URLconf #} <p class="pull-left"><a href="{% url 'password_reset' %}">Forgot password?</a></p> <button type="submit" class="btn btn-default pull-right"/> Sign in <span class="fa fa-arrow-circle-right"></span> </button> <input type="hidden" name="next" value="{{ next }}"/> </form> Now if any user tries to visit a page like /admin and user is not authenticated, user is redirected to /login and after successful login he should be redirected to /admin as per user request. but I am landing in /login/admin instead. Where am I going wrong, Any help is appreciated. -
Django Rest Framework Serializer charfield not updating when source is given
I have a model field with choices charfield class Vehicle(models.Model): name = models.CharField(max_length=100) STATUS_CHOICES = ( ("N", "New"), ("U", "Used"), ("P", "Just Purchased") ) status = models.CharField(max_length=3, choices=STATUS_CHOICES) The serializer class also has charfield for status but with source argument to display the readable value class VehicleSerializer(ModelSerializer): status = serializers.CharField(source='get_status_display') class Meta: model = Vehicle When I try to update vehicles through patch request with data {'status': "U"}, there is no update performed. However the update occurs when I remove the source from serializer status field. Providing source is necessary to display proper value in web view. I know the option of changing the name of status in serializer to something other and using that in the template. Also there is the option to override update method in serializer, however my question is what is source doing to prevent the update? -
Django with Google Cloud Storage
Is there a complete example showing how to upload files to Google Cloud Storage using Django on Google Compute Engine? -
How to instantiate a model without validation?
I am trying to instantiate an object of a class that happens to be a model. I am trying to use this object as a stub so only some attributes are required. Some fields are required, but I don't really care about these in this scenario, I only want the other ones. However, validation is running when calling the constructor, so it is preventing the object from being instantiated. Is there a way I can make an instance of a class that inherits from models.Model without running the validation?