Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python django custom query result in html
Just started to learn python django framework ,i am trying to display a custom query result in html page. def index(request): with connection.cursor() as cursor: cursor.execute("SELECT * FROM polls_post") context ={ 'all_posts':cursor.fetchall() } In my html page <ul> {% for post in all_posts %} <li>{{ post }}</li> {% endfor %} </ul> But it displays the value as tuples ,so how can i get query result with table column name such as i can print the values like this way <ul> {% for post in all_posts %} <li>{{ post.title }}</li> <li>{{ post.name }}</li> {% endfor %} </ul> -
get the function from the model in the template
iam creating a cv app and dont know how i can get the get_relative_length function from the model in my template, the data doesnt come throught, I need help, iam new to django I really appreciate your help model from __future__ import unicode_literals #from django.db import models # Create your models here. from datetime import datetime from dateutil import relativedelta from django.db import models from django.utils.translation import ugettext_lazy as _ #from djangocms_text_ckeditor.fields import HTMLField class CreateCV(models.Model): title = models.CharField(verbose_name=_('Title'), max_length=255) company = models.CharField(verbose_name=_('Company'), max_length=255) start_date = models.DateField(verbose_name=_('Start date'), help_text=_( "The date when you started this position - only the month and year will be displayed")) end_date = models.DateField(verbose_name=_('End date'), blank=True, null=True, help_text=_( "The date when this position ended - only the month and year will be displayed. You don't have to define this if it is your active post.")) active_post = models.BooleanField(verbose_name=_("Active position?"), help_text=_( "Check this if this is your active post. You won't have to add the end date in that case.")) description = models.TextField(verbose_name=_("Description"), help_text=_("Give a short description about your work and responsibilities."), max_length=2048, null=True, blank=True) website = models.CharField(verbose_name=_("Website"), help_text=_("Provide a link to the company's website."), max_length=255, null=True, blank=True) show_year = models.BooleanField(verbose_name=_("Show Year"), help_text=_('Displays how long the current … -
How to filter the form in django template
I am trying a form POST using django with django-bootstrap3. The form has those fields: name, email, phone, company, subject, and message. The templates code is as follows. Question: If I do not want to use all fields of form to generate tempate, such as only use name, email and phone, how to implement? I guess I can filter the form but I do not know how to do. {% load bootstrap3 %} {% block contact-page %} <div class="container"> <div class="center"> <h2>Drop Your Message</h2> <p class="lead">We are looking forward to hearing from you.</p> </div> <div class="row contact-wrap"> <div class="status alert alert-success" style="display: none"></div> <form action="" method="post" class="form"> {% bootstrap_form form %} {% buttons %} <button type="submit" class="btn btn-primary"> {% bootstrap_icon "star" %} Submit </button> {% endbuttons %} </form> </div><!--/.row--> </div><!--/.container--> {% endblock %}} -
Django - rendering two dimensional dictionary data to template
For my polling project using chartjs. In chart there would be multiple lines same as poll options. For example - Are you a programmer? Yes No Then chart would generate 2 lines for Yes and No vote records. In view, I created a two dimensional dictionary to store poll options. But I am facing problem with rendering two dimensional dictionary data to template. In template file I coded for chartjs. There is an option to set data for lines like following code - datasets: [{ label: '# of Votes', data: [12, 19, 3, 5, 2, 3], backgroundColor: [ 'rgba(255, 99, 132, 0.2)', ], borderColor: [ 'rgba(255,99,132,1)', ], borderWidth: 1 }] Above code generates single line but I need to make it dynamic for multiple lines. Here is my two dimensional dictionary dataset - {8: {1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: 0, 12: 0}, 7: {1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: 1, 12: 0}} I am trying to create dataset with following code - {% for key, value in vote_records.items %} … -
Deep learning based web service with Apache Spark?
Suppose I have millions of data about customer and I want to automate analytics of user’s tendency, updating(training and predicting) dataset with deep learning, and apply it for recommendation of pruducts as feedback in that web service. Is that all possible if I use apache spark, tensorflow, and Django? -
delete a django JWT token
I am using the Django rest framework JSON Web token API that is found here on github (https://github.com/GetBlimp/django-rest-framework-jwt/tree/master/). I can successfully create tokens and use them to call protected REST APis. However, there are certain cases where I would like to delete a specific token before its expiry time. So I thought to do this with a view like: class Logout(APIView): permission_classes = (IsAuthenticated, ) authentication_classes = (JSONWebTokenAuthentication, ) def post(self, request): # simply delete the token to force a login request.auth.delete() # This will not work return Response(status=status.HTTP_200_OK) The request.auth is simply a string object. So, this is of course, not going to work but I was not sure how I can clear the underlying token. EDIT Reading more about this, it seems that I do not need to do anything as nothing is ever stored on the server side with JWT. -
How to unpack rar/zip archive after it was uploaded via FileField in Django?
My model class Banner(models.Model): ... html5_banner = models.FileField(upload_to='banners/html5/%Y/%m/%d', blank=True) How to replace /media/banners/html5/date/archive.zip with /medid/banners/html5/date/archive/archive_content on model saving stage? -
NoReverseMatch at django
I'am getting a weird URL error in my project or I'am missing something. I want to get the profile ID and show the informations in a template called "profile.html". Quite simple isn't it? But I'am getting NoReverseMatch error everytime I call this "profile url". My urls.py: from django.conf.urls import url, include from django.contrib import admin from sugar import views urlpatterns = [ url(r'^area51/', admin.site.urls), url(r'^search/', views.search, name="search"), url(r'^terms/', views.terms, name="terms"), url(r'^thanks/', views.thanks, name="thanks"), url(r'^create_user/', views.create_user, name="create_user"), url(r'^profile_edit/', views.profile_edit, name="profile_edit"), url(r'^upload_photos/', views.photo_upload, name="photo_upload"), url(r'^recover/', views.recover_account, name="recover"), url(r'^login/', views.log_user_in, name="login"), url(r'^logout/', views.log_user_out, name="logout"), url(r'^register/', views.register, name="register"), url(r'^profile/(?P<sugarid>\d+)/$', views.profile, name="profile"), url(r'^payment/', views.payment, name="payment"), url(r'^home', views.home, name="home"), url(r'^paypal/', include('paypal.standard.ipn.urls')), url(r'^$', views.home, name="home"), ] My profile view: def profile(request, sugarid): if not request.user.is_authenticated(): return redirect("home") variables = {} exists = SugarUser.objects.filter(user_id=sugarid) if exists: user = SugarUser.objects.get(user_id=sugarid) if not check_payment(user): return redirect("payment") midList = [] lastList = [] queryPhotos = UserPhoto.objects.filter(user_id=sugarid).order_by("-id")[:8] featuredPhoto = queryPhotos.values().first() midPhotos = queryPhotos[4:] for mid in midPhotos: midList.append(mid) if len(midList) < 4: result = 4 - len(midPhotos) for r in range(result): midList.append(None) lastPhotos = queryPhotos[1:4] for last in lastPhotos: lastList.append(last) if len(lastList) < 3: result = 3 - len(lastPhotos) for r in range(result): lastList.append(None) variables['name'] = user.name variables['status'] = user.status variables['description'] = … -
How to pass initial value to a custom fields in ModelAdmin?
I am trying to extends django user auth through onetonefield in model. Here is the model: from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) nim = models.CharField(max_length=10, blank=True) def __str__(self): return self.user.username With basic admin panel i get to create user instance first and then profile. But i use custom forms on admin panel so i can create it on one form.This is the forms look: Profile add form this is forms.py from django import forms from django.contrib.auth.models import User from .models import Profile class ProfileForm(forms.ModelForm): username = forms.CharField(required=False, max_length=150) password = forms.CharField(required=False, max_length=50, widget=forms.PasswordInput) class Meta: model = Profile fields = ('username', 'password', 'nim') and this is admin.py from django.contrib import admin from django.contrib.auth.models import User from .forms import ProfileForm from .models import Profile class ProfileAdmin(admin.ModelAdmin): form = ProfileForm def save_model(self, request, obj, form, change): username = form.cleaned_data['username'] password = form.cleaned_data['password'] user = User.objects.create_user(username=username, password=password) user.save() obj.user = user obj.save() admin.site.register(Profile, ProfileAdmin) With this all i can create profile instance just fine. But when i try to change/edit profile it didn't show initial value for username and password fields, only nim field did. empty username … -
No named cycles in template. 'row1,row2' is not defined
In my django inline formset, form html: {% block body %} <h2>Profile</h2> <hr> <div class="col-md-4"> <form action="" method="post">{% csrf_token %} {{ form.as_p }} <table class="table"> {{ familymembers.management_form }} {% for form in familymembers.forms %} {% if forloop.first %} <thead> <tr> {% for field in form.visible_fields %} <th>{{ field.label|capfirst }}</th> {% endfor %} </tr> </thead> {% endif %} <tr class="{% cycle row1,row2 %} formset_row"> {% for field in form.visible_fields %} <td> {# Include the hidden fields in the form #} {% if forloop.first %} {% for hidden in form.hidden_fields %} {{ hidden }} {% endfor %} {% endif %} {{ field.errors.as_ul }} {{ field }} </td> {% endfor %} </tr> {% endfor %} </table> <input type="submit" value="Save"/> <a href="{% url 'profile-list' %}">back to the list</a> </form> </div> {% endblock %} When I tried to open form it gives TemplateSyntaxError at /profile/add/ No named cycles in template. 'row1,row2' is not defined How could I avoid this error? -
How to order a SELECT statement by the number of matching foreign keys?
Imagine a "house" table in a database has 7 foreign keys: Location Price Population Size Schools Shops Transport (Some of the relationships are in fact many to many relationships). I want to show a list of houses, sorted in descending order by the number of matching foreign keys. The best result would be where all 7 foreign keys have values, including a large number of values in the many to many relationships. The next best result would be where all 7 foreign keys have values, but have fewer values in the many to many relationships. The next best result would be where 6 of the foreign keys have a value. The next best result would be where 5 of the foreign keys have a value. And so on until only 1 of the foreign keys has a value. Is there a way to do this type of sorting in SQL? Thank you. -
access django urls from javascript
url(r'^(?P<code>[-\w]+)/$',views.Listing.as_view(),name='stat_details'), How can I access this django url from my javascript file where I am sending an ajax call to this url: /mycode/ $(document).ready(function(){ var url = {% url stat_details code='abc' %}.replace('abc', 'mycode'); alert(url); $.ajax({ url: url, success:function(result){ populateTable(result.data.m_data); }, error:function(xhr){ alert("Fail"+ xhr.status+ " "+ xhr.responseText); } }); }); This doesn't work.Can someone help me in correcting this. Thanks -
Pycharm, starting script does not run
According to official docs and this previous question, one just have to put code into the starting script field in settings. I have done this, but my code does not get run. My starting script is: import sys; print('Python %s on %s' % (sys.version, sys.platform)) import django; print('Django %s' % django.get_version()) sys.path.extend([WORKING_DIR_AND_PYTHON_PATHS]) if 'setup' in dir(django): django.setup() import django_manage_shell; django_manage_shell.run(PROJECT_ROOT) from www.models import * print("test") test = "test" After restarting the console, the app models are not available, no "test" is seen, and test object does not exist. However, some of it does get run because django is successfully imported: In[3]: django Out[3]: <module 'django' from '/home/emil/GP/env/lib/python3.5/site-packages/django/__init__.py'> How do I get the console to automatically run the script I put? Specifically, I want it to autoimport the models. -
Managing databases in Django models, sqlite and mongoengine
I'm making some project in Django, something to manage assets in warehouses. I want to use two databases to this. First is sqlite database, with contains any data about users. Second is mongoDB database, here I want to store all the assets data. The question is, how to tell to my model classes, whose bases they should use (models responsible for user registration etc - sqlite, models responsible for managing assets data - mongoDB)? I read about DATABASE_ROUTERS and using Meta classes, but it's solutions for supported databases by Django (or maybe I don't know something), I dont know if it's good and possible to integrate it with mongoengine. Thanks for any tip! -
python shell - new line
i'm following a tutorial in a book and im having some issues with the "\n". here is the code that i am asked to type in python shell: from django.template import Template, Context template = Template( '{{ ml.exclaim }}!\n' 'she said {{ ml.adverb }}\n' 'as she jumped into her convertible {{ ml.noun1 }}\n' 'and drove off with her {{ ml.noun2 }}.\n' ) mad_lib = { 'exclaim':'Ouch', 'adverb':'dutifully', 'noun1':'boat', 'noun2':'pineapple', } context = Context({'ml': mad_lib}) template.render(context) so whenever i enter this into the python shell, it comes returns it as this all at once: u'Ouch!\nshe said dutifully\nas she jumped into her convertible boat\nand drove off with her pineapple.\n' I'd like to have it come out like this all on separate lines: Ouch! she said dutifully as she jumped into her convertible boat and drove off with her pineapple. All help is appreciated. -
HTTP 504 Gateway Time-out when serving static file with Django (Nginx + Gunicorn)
I've been having problem hosting my Django project on Amazon EC2. Using Gunicorn and Nginx to host the site, I get the following error when trying to load my page in the browser (excerpt from the Javascript console): Failed to load resource: the server responded with a status of 504 (Gateway Time-out): https://example.com/favicon.ico I believe Nginx has some problems finding my static files, but I'm not sure why. Here's my Nginx config: server { listen 443 default; client_max_body_size 100M; server_name www.example.com; keepalive_timeout 5; ssl on; ssl_certificate /etc/letsencrypt/live/www.example.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/www.example.com/privkey.pem; # the domain name it will serve for charset utf-8; # path for static files root /opt/app/staticfiles; location /static { root /opt/app/staticfiles; } location / { # checks for static file, if not found proxy to app try_files $uri @proxy_to_app; } location @proxy_to_app { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; proxy_pass http://app_server; } } /var/log/nginx/access.log and cat /var/log/nginx/error.log don't show anything. For HTTP code 504 it is usually a problem that a long request is hanging and eventually times out, but I'm not sure how it applies to my project, since I'm only trying to load the site. Not sure how to debug this issue, so any help is … -
Django Loading Screen when trying to connect to webpage
Is there a way that I can implement a loading screen when the browser is trying to connect to my website? That is, when, on Chrome for example, "Waiting for " is displayed in the bottom left-hand corner. Examples of what I am looking for include the loading screens of these websites: https://dashboard.heroku.com/ and https://www.comodo.com/ My website is made using Django, but if there's another tool that can help me accomplish this, I'd love to know about it too. -
Djang-registration, mail activation fails after force email unique (bad signature)
I have a problem with django-registration. Everything works fine until I forced unique email. I have very basic skeleton of app. This is works fine: auth_patterns = [ url(r'^', include('registration.backends.hmac.urls')), ] urlpatterns = i18n_patterns( url(r'^admin/', admin.site.urls), url(r'^$', login_required(HomeView.as_view()), name='index'), url(r'^accounts/', include(auth_patterns)), ) But when I added url(r'^register/$', RegistrationView.as_view(form_class=RegistrationFormUniqueEmail), name='registration_register' ), in auth_patterns I get activation link on mail http://localhost:8000/en/accounts/activate/98a3585128c1b6899e4493768d4e62a52764fc5f/ but after click I got Account activation failed from my template (activate.html) I have no errors in browser console/ or ./manage.py runserver outputs, nothing. When I tried to debug registration plugin I've noticed that registration plugin return user as None in this code (registration.backends.hmac.views.ActivationView): def validate_key(self, activation_key): """ Verify that the activation key is valid and within the permitted activation time window, returning the username if valid or ``None`` if not. """ try: username = signing.loads( activation_key, salt=REGISTRATION_SALT, max_age=settings.ACCOUNT_ACTIVATION_DAYS * 86400 ) return username # SignatureExpired is a subclass of BadSignature, so this will # catch either one. except signing.BadSignature: return None It throw BadSignature, but why? Anyone had this problem? How to resolve it? -
How to render html django page to pdf?
Hello and thank your for your time. I have a task to render html page with dynimacal data and turn it to pdf. And i have a problem with it. def makepdf(request): if request.POST: chatvs = Competirors.objects.get(id = int(request.POST.get('competitor', ''))) jivo_staff = Manager.objects.get(id = int(request.POST.get('manager', ''))) business = Field.objects.get(id = int(request.POST.get('filed', ''))) business = business.link.all().order_by('?')[0:3] context = { "chatvs" : chatvs, "jivo_staff" : jivo_staff, "business" : business, } tmpl = get_template('marketing/jivopdf.html', ) html = tmpl.render(context) # and i have a problem there with pdfkit I was using pdfcrowd API, but it cuts all css styles and doesn't make it looks nice. As for wkhtmltopdf/pdfkit - i don't know how to give it a rendered html page, as it access only url/file/string. Is there a way to render ready html page? -
ampersand in views for python django
I came across something new when going over some login registration code. what is the point of the ampersand here (**request.POST)? It runs with or without them, but wonder what the benefit of having them does. def register(request): regstatus = User.userManager.register(**request.POST) if regstatus[0]: request.session['user.id'] = regstatus[1] return redirect(reverse('login:index')) else: for message in regstatus[1]: messages.warning(request, message) return redirect(reverse('login:index')) -
Annotate queryset with whether matching related object exists
I have two models with an explicit many-to-many relationship: a thing, auth.user, and a "favorite" model connecting the two. I want to be able to order my "thing"s by whether or not they are favorited by a particular user. In Sqlite3, the best query i've come up with is (roughly) this: select *, max(u.name = "john cleese") as favorited from thing as t join favorite as f on f.thing_id = t.id join user as u on f.user_id = u.id group by t.id order by favorited desc ; The thing tripping me up in my sql-to-django translation is the max(u.name = "john cleese") bit. As far as I can tell, Django has support for arithmatic but not equality. The closest I can come is a case statement that doesn't properly group the output rows: Thing.objects.annotate(favorited=Case( When(favorites__user=john_cleese, then=Value(True)), default=Value(False), output_field=BooleanField() )) The other direction I've tried is to use RawSQL: Thing.objects.annotate(favorited=RawSQL('"auth_user"."username" = "%s"', ["john cleese"])) However, this won't work, because (as far as I'm aware) there's no way to explicitly join the favorite and auth_user tables I need. Is there something I'm missing? -
Reusing the same URL pattern in Django
I'm building a simple web store. There are Category objects and Product objects. I want the URLs for both to be at the top level, ie a Category named "Jacket" would be at http://example.com/jacket and a Product named "Foo" would be at http://example.com/foo. I'm not sure how to handle this in my URLs since both match the same regular expression. I can just have a single DetailView which overwrites get_object(), first checking for a product with the slug and then checking for a category with the slug and returning whichever it finds first. (In the event of both a product and cateogry having the same slug, I'd want to serve the product.) Is there a better way to handle this? -
Django render is not refreshing page after a form submission
After almost a full day trying to make things work, I resign... I need some help because I don't understand where I'm doing things the wrong way. I searched SO and stumbled on many answers about redirection and so on... Let me give you some context : I have a simple form where one can upload a file, so far, it's working well. I want the user to be redirected to another page after the upload is successful and this is where it fails :'( My views.py : # Create your views here. def thank_you(request): data = {'text': 'Thank you for your file'} print('thank you blablabla') print(data) return render(request, 'app/thank_you.html', data) def home(request): if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): uploaded_file = request.FILES['file'] new_file = UploadFile(file=uploaded_file) new_file.save() return redirect(reverse(thank_you)) else: form = UploadFileForm() data = {'form': form} return render(request, 'app/drop_file.html', data) I do see the 2 prints in the 'thank_you' function, meaning that the redirect is working as expected. But the view doesn't refresh and I'm stuck. And if I try to access the url directly (going to http://.../thank_you/ ) it does show correctly. The form looks like that : <form id="my-dropzone" class="dropzone" action="{% url 'home' %}" … -
Django (1.8): STATICFILES_DIRS is not working
I am new to Django and I would like some help for the static folder setting. In my index.html I have code like below: {% load staticfiles %} <!doctype html> <!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]--> <!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8"> <![endif]--> <!--[if IE 8]> <html class="no-js lt-ie9"> <![endif]--> <!--[if gt IE 8]><!--> <html class="no-js"> <!--<![endif]--> <head> <meta charset="utf-8"> <title>www</title> <meta name="description" content=""> <meta name="viewport" content="width=device-width"> <link rel="shortcut icon" href="/favicon.ico"> <!-- Place favicon.ico and apple-touch-icon.png in the root directory --> <!-- build:css styles/vendor.css --> <!-- bower:css --> <!-- endbower --> <!-- endbuild --> <!-- build:css(.tmp) styles/main.css --> <link rel="stylesheet" href="{% static 'styles/main.css' %}"> <!-- endbuild --> <!-- build:js scripts/vendor/modernizr.js --> <script src="{% static "bower_components/modernizr/modernizr.js" %}"></script> <!-- endbuild --> </head> <body onLoad="studioHanel.StudioHanel()"> ...... some html ...... </body> </html> in the settings file I have the following to define the actual static folder path location. Which is pointing correctly to the location of the CSS, JS files. For some reason there are not captured. Am I missing sth here? thanks in advance. STATIC_URL = '/static/' STATICFILES_DIRS = ( # os.path.join(BASE_DIR, 'CordeliaHanelBackend', 'static'), '/var/www/CordeliaHanelFrontend-master/www/app', ) -
Html not displaying django
Views.py: def index(request): return HttpResponse(TemplateView.as_view(template_name="index1.html")) urls.py: url(r'^about/$', TemplateView.as_view(template_name="index1.html")), url(r'^$', views.index, name='index'), File is in the same directory v1.10