Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Issue rendering with nested tables in Django
So I'm trying to loop two tables within each other. I have a list of tasks that each have a list of materials. I'd like to next the tables within each other. However, the code below doesn't render the second task into columns. So, when it loops it seems as if the table structure is destroyed. I'm using Django/Python. <div class="table-responsive"> <table id="taskTable" class="table"> {% for task in projecttype.projecttask_set.all %} <h5>Task - {{ task.name }}</h5> <thead class="alert-success"> <tr> <th>Quantity</th> <th>Units</th> <th>Cost</th> </tr> </thead> <tbody> <tr> <td>{{ total_units_required }}</td> <td>{{ task.base_unit_label }}</td> <td>{{ task.base_unit_cost }}</td> </tr> </tbody> <table id="materialTable" class="table"> <thead> <tr class="alert-info"> <th>Material</th> <th>Cost per Task Unit</th> <th>Material Cost</th> <th>Total Cost</th> </tr> </thead> {% for material in task.materials.all %} <tbody> <tr> <td>{{ material.name }}</td> <td>{{ material_quantity_per_task_base_unit }}</td> <td>{{ total_material_quantity }}</td> <td>{{ total_material_cost }}</td> </tr> </tbody> {% endfor %} </table> {% endfor %} </table> </div> enter image description here -
view inheritance from my model
I'm learning Python/Django and i'm trying to do too much, so I'm going to start with the baby steps to figure out my bigger problem. My problem starts with the basic definition of my profile view. def profile(request): args = {'user':request.user} print (request.user) return render(request, 'accounts/profile.html', args) When I review the print it will display as @NHoff. Oddly enough when I view the url for the template, it displays all my user information. My username doesn't have an @ anywhere in it. Although in the pre-existing database i'm working with all data is linked to a domain\username. Which is why i'm unable to link to the pre-existing data. In my AbstractBaseUser model I created formattedusername in the user table using the following: def save(self, *args, **kwargs): self.formattedusername = '{domain}\{username}'.format( domain='HCA', username=self.username) super(User, self).save(*args, **kwargs); How Can I get the formattedusername over into my def profile instead of request.user? formattedusername is the primary key i'd like to use. If that's not possible, how can I force a hardcoded domainname\ prior to my username from request.user. -
machine learning with django
Iam new to machine learning and django.I am trying to implement a machine learning algorithm using django(for UI ). I tried like this In my views.py from django.shortcuts import render from mlapp.models import capgemini from django_pandas.io import read_frame from django.http import HttpResponse import csv from sklearn.linear_model import LinearRegression from sklearn.cross_validation import train_test_split from mlapp.forms import create_capgemini def index1(request): dataReader = open('/home/vishnu/newml/ml4/src/mldata/mlapp/datafiles /mlapp/data.csv', 'r') for row in dataReader: row = row.split(',') capgem=capgemini() capgem.name=row[0] capgem.age=row[1] capgem.number=row[2] capgem.save() dataReader.close() return render(request) def home(request): if request.POST: form = create_capgemini(request.POST) if form.is_valid(): name = form.cleaned_data['name'] age = form.cleaned_data['age'] number = form.cleaned_data['number'] new_developer = capgemini(name=name, age=age, number=number) new_developer.save() else: return render(request, 'mlapp/base.html', {'form' :home}) else: form = create_capgemini() qs=capgemini.objects.all() df=read_frame(qs,fieldnames=['name','age','number']) #print(df) X=df[['age']] y=df[['number']] X_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.0) #print(X_train) #print(X_test) #print(y_train) test=capgemini.objects.get(pk=1) test_1 =test.age lm =LinearRegression() lm.fit(X_train,y_train) prediction = lm.predict(test_1) print(prediction) context={'prediction':prediction} #print(lm.coef_) return render(request, 'mlapp/base.html', {'form' :form},context) In forms.py from django import forms class create_capgemini(forms.Form): name = forms.CharField(max_length=100) age =forms.IntegerField() number = forms.IntegerField() In models.py from django.db import models class capgemini(models.Model): name = models.CharField(max_length=100) age = models.IntegerField() number = models.IntegerField() def __unicode__(self): return self.name In base.html <!DOCTYPE html> <html lang="en"> <head> <body> <form method="post" action="{% url "home" %}" > {% csrf_token %} <!-- This line inserts a … -
Django Inline Formset - possible to follow foreign key relationship backwards?
I'm pretty new to django so I apologize if this has an obvious answer. Say you have the following three models: models.py class Customer(models.Model): name = models.CharField() slug = models.SlugField() class Product(models.Model): plu = models.Charfield() description = models.Charfield() class Template(models.Model): customer = models.ForeignKey(Customer) product = models.ForeignKey(Product) price = models.DecimalField() The inline formset would look something like: TemplateFormSet = inlineformset_factory(Customer, Template, extra=0, fk_name='customer', fields=('price')) Is it possible to follow the Template formset's Product foreign key backwards so you could display the plu and description fields within the same table? For example something like this: <table> <tbody> {% for obj in customer.template_set.all %} <tr> <td>{{ obj.product.plu }}</td> <td>{{ obj.product.description }}</td> <td>{% render_field formset.form.price class="form-control form-control-sm" %}</td> </tr> {% endfor %} </tbody> </table> The formset's fields appear with the html above but the data from the bound form instance doesn't appear and I can't save by editing the empty fields. I've also tried below but each formset is repeated for each object (for x formsets there are x*x rows): <tbody> {% for obj in customer.template_set.all %} {% for form in formset %} <tr> <td>{{ obj.product.plu }}</td> <td>{{ obj.product.description }}</td> <td>{% render_field form.price class="form-control" %}</td> </tr> {% endfor %} {% endfor %} </tbody> Basically … -
Iterating through a class to retrieve json response - Synapse/Django
I have a django project and I am trying to integrate SynapsePay Api. I sent a request that returned a class as a response. I am trying to figure out how to cycle or parse the response to get to the json so that I can grab certain values from the response that was returned. I have looked everywhere and cant seem to find a solution or a way to get into a class objects and reach the json part of the return. Here is the response that I am getting... I want to grab the _id from both of the objects returned in the object response below. Does anyone know how I can do this?? [ <class 'synapse_pay_rest.models.nodes.ach_us_node.AchUsNode'>( { 'user':"<class 'synapse_pay_rest.models.users.user.User'>(id=...49c04e1)", 'json':{ '_id':'...639c24', '_links':{ 'self':{ 'href':'https://uat-api.synapsefi.com/v3.1/users/...49c04e1/nodes/...4639c24' } }, 'allowed':'CREDIT-AND-DEBIT', 'client':{ 'id':'...1026a34', 'name':'Charlie Brown LLC' }, 'extra':{ 'note':None, 'other':{ }, 'supp_id':'' }, 'info':{ 'account_num':'8902', 'address':'PO BOX 85139, RICHMOND, VA, US', 'balance':{ 'amount':'750.00', 'currency':'USD' }, 'bank_logo':'https://cdn.synapsepay.com/bank_logos/new/co.png', 'bank_long_name':'CAPITAL ONE N.A.', 'bank_name':'CAPITAL ONE N.A.', 'class':'SAVINGS', 'match_info':{ 'email_match':'not_found', 'name_match':'not_found', 'phonenumber_match':'not_found' }, 'name_on_account':' ', 'nickname':'SynapsePay Test Savings Account - 8902', 'routing_num':'6110', 'type':'PERSONAL' }, 'is_active':True, 'timeline':[ { 'date':1509998865218, 'note':'Node created.' }, { 'date':1509998865962, 'note':'Unable to send micro deposits as node allowed is not CREDIT.' } ], … -
Can't make 1 of the forms not reqired
I've got 2 forms on 1 page, It seems like this: <form method='post' enctype="multipart/form-data" id="formUpload"> {% csrf_token %} {{ image_form }} <button type="submit" class="js-crop-and-upload" name="crop" value="crop">Crop</button> {{ profile_form.as_p }} <button type="submit" class="btn" name="save_profile" value="save_profile">Submit</button> </form> This html form contain ProfileForm for profile data and ImageForm for Profile.image field. I want to save Images clicking button "submit" with name="crop" and save profile clicking button "submit" with name="save_profile". I could easily do this by splitting this html form like this: <form method='post' enctype="multipart/form-data" id="formUpload"> {% csrf_token %} {{ image_form }} <button type="submit" class="js-crop-and-upload" name="crop" value="crop">Crop</button> </form> <form method='post'> {{ profile_form.as_p }} {% csrf_token %} <button type="submit" class="btn" name="save_profile" value="save_profile">Submit</button> </form> But here if I would press submit "crop" - all data in profile form would be deleted. I'm really stuck, because when fill profile fields and press submit with name "save_profile" django tells me that fields from image_form are required and don't send POST to my view, also when some of the fields in profile_form are not filled I couldn't save image using image_form. Also I'm sending my view if this is needed: view: @login_required def profile_new(request): if Profile.objects.filter(user=request.user): return redirect('profile_edit') created_image = Photo.objects.filter(created_by=request.user) if request.method != "POST": profile_form = ProfileForm() image_form … -
Translate Function Success into Function then
I am trying to get django-rest-framework running with angularjs. In order to do the authorization I found django-rest-auth and angular-django-registration-auth Unfortunately the djangoAuth.js is using the depreciated function success within the 'request' variable and I get the following error message: TypeError: $http(...).success is not a function I tried to rewrite the code using the then function, but only end up in the error-Callback. What do I have to change? Thanks for your help. djangoAuth.js - Orginal auth .service('djangoAuth', function djangoAuth($q, $http, $cookies, $rootScope) { // AngularJS will instantiate a singleton by calling "new" on this function var service = { /* START CUSTOMIZATION HERE */ // Change this to point to your Django REST Auth API // e.g. /api/rest-auth (DO NOT INCLUDE ENDING SLASH) 'API_URL': 'localhost:8000/rest-auth', // Set use_session to true to use Django sessions to store security token. // Set use_session to false to store the security token locally and transmit it as a custom header. 'use_session': true, /* END OF CUSTOMIZATION */ 'authenticated': null, 'authPromise': null, 'request': function(args) { // Let's retrieve the token from the cookie, if available if($cookies.token){ $http.defaults.headers.common.Authorization = 'Token ' + $cookies.token; } // Continue params = args.params || {} args = args || … -
Keep div with and image the same height as other div with some text
I'm developing a web page in Django and in it there's a list of the last 5 news that I add with a for loop. The news item has an image on the left, and the title, date and the first 50 words of the news on the right. The image and the text are in separate divs inside another div. I would like to make the image div the same size as the text div, not the other way around. Not all the images have the same dimension. I prefer not to limit the size of the divs with a px value for responsive purposes. I'm using Bootstrap 3.3.7. Here is the Fiddle of what I have now. Is there a way to accomplish this with CSS? -
Unable to install uwsgi with pip on Ubuntu 16.04
I have taken VPS from godaddy and built a machine with Ubuntu 16.04. I want to host a Python (DJango) application. I successfully installed Nginix. Unfortunately, I am not able to install nginix with pip on this machine. When I run sudo pip install uwsgi I am getting the following error. Command "/usr/bin/python -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-kfJCaG/uwsgi/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-QJoglI-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /tmp/pip-build-kfJCaG/uwsgi/ Please help asap. -
Can't import Django model into scrapy project
I have a folder Project which contains Django project called djangodb and Scrapy project called scrapyspider. So it looks like: Project djangodb djangodb myapp scrapyspider scrapyspider spiders items.py scrapy.cfg __init__.py I want to import model Product from myapp app. The problem is that it returns import error: from Project.djangodb.myapp.models import Product as MyAppProduct ImportError: No module named djangodb.myapp.models Tried many things but couldn't avoid this error. Do you have ideas? -
Django BooleanField doesn't work on edit form
My situation: Models.py class Box(models.Model): is_empty = models.BooleanField(default=False) upload_date = models.DateTimeField(auto_add_now=True) Forms.py class BoxForm(forms.ModelForm): class Meta: model = Box fields = (is_empty,) Views.py def edit_box(request, pk): box = get_object_or_404(Box, pk=pk) if request.method == 'POST': form = BoxForm(request.POST, instance=box) if form.is_valid(): form.save() return redirect('home') else: form = BoxForm(instance=box) return render(request, 'form.html', {'form': form}) The problem is that when I enter into the template form and I want to change checkbox value I can't do it, it seems disabled and I dan't know why. -
ValueError: Cannot query “”: Must be “User” instance
I am trying to create a story-sharing website where user can get to specific author's profile to see all the stories which the author wrote. However I am getting an error. ValueError at /storyauthor/1 Cannot query "yumin": Must be "User" instance. Here is my model class StoryAuthor(models.Model): """ Model representing a author. """ user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) def get_absolute_url(self): """ Returns the url to access a particular story-author instance. """ return reverse('stories_by_author', args=[str(self.id)]) def __str__(self): """ String for representing the Model object. """ return self.user.username -
Method Not Allowed (POST) using DeleteView
I am new to Django and i using Class based views to add a delete option to my Restaurant List, However when i click the delete button i am getting a blank screen and getting the following error in the console "Method Not Allowed (POST):" Below is my code views.py from __future__ import unicode_literals from django.db.models import Q from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render, get_object_or_404 from django.views import View from django.contrib.auth.mixins import LoginRequiredMixin from django.views.generic import TemplateView, ListView, DetailView, CreateView,DeleteView from django.urls import reverse_lazy class RestaurantDeleteView(DeleteView): model = RestaurantLocation success_url = reverse_lazy('restaurants:list') urls.py from django.conf.urls import url, include from .views import ( RestaurantListView, RestaurantDetailView, RestaurantCreateView, RestaurantDeleteView, ) urlpatterns = [ url(r'^create/$', RestaurantCreateView.as_view(), name= 'create'), url(r'^$',RestaurantListView.as_view(), name= 'list'), url(r'^(?P<slug>[\w-]+)/$',RestaurantDetailView.as_view(), name="detail"), url(r'^(?P<slug>[\w-]+)/delete/$', RestaurantDeleteView.as_view(), name="restaurant-delete"), ] delete.html <form method="t" action="" >{% csrf_token %} <p>Are you sure you want to delete <strong> {{ obj }}</strong>?</p> <input type="submit" value="DELETE" /> </form> -
Using SQLite on AWS EB: no such table django_session
In my django app with the standard folder structure I have created an .ebignore file with the following content: # SQLite db.sqlite3 The purpose is that when I deploy to AWS EB my SQLite database won't get overwritten. I want to keep the SQLite database on my server unchanged when I modify my app. However, after I deploy ('eb deploy') and I visit the /admin url of my website I get the following error: no such table: django_session What's the correct way to re-deploy to AWS without overwriting the SQLite database? -
Django no reverse match at /
I'm trying to make a picture the url to the post the picture represents, and I must be doing something wrong, but I don't know what. I am getting this error when trying to visit the home page of my site. Error during template rendering In template .../home.html, error at line 48 Reverse for 'view_post' with keyword arguments '{'post_id': ''}' not found. 1 pattern(s) tried: ['post/(?P[0-9]+)/$'] and the code it showcases <a href="{% url 'view_post' post_id=post.post_id %}"><img src="media/{{ item.image }}"></a> Also this is my view def view_post(request, post_id): post = get_object_or_404(Post,id=post_id) return render(request,'gram/view_post.html',{'post': post}) And url url(r'^post/(?P<post_id>[0-9]+)/$', views.view_post, name='view_post'), Thank you for your help. -
Django - Selecting a particular object from a set of objects
I have the following models in my Django app: class Review(models.Model): ID = models.AutoField(primary_key=True) text = models.CharField(max_length=1000) review_user = models.ForeignKey("User", on_delete=models.CASCADE) review_book = models.ForeignKey("Book", on_delete=models.CASCADE) class Review_is_helpful(models.Model): ID = models.AutoField(primary_key=True) is_helpful = models.BooleanField() # associated user who gave the review, and the review itself review_user = models.ForeignKey('User', on_delete=models.CASCADE) on_review = models.ForeignKey('Review', on_delete=models.CASCADE) class Book(models.Model): ID = models.AutoField(primary_key=True) name = models.CharField(max_length=50) description = models.CharField(max_length=1000) class User(models.Model): ID = models.AutoField(primary_key=True) For every book, we will have any number of reviews, and for each review, users can tag the review as Helpful/Not helpful (or not tag at all). Now, if I have a Review QuerySet reviews, and a User object user inside a view function, I want to additionally have the following for each review in the QuerySet: 1. If the review has been tagged by the user as Helpful/Not helpful (the corresponding Review_is_helpful object exists), then the corresponding Review_is_helpful object should be there along with the review object. 2. If the user hasn't tagged the review as Helpful/Not helpful (the corresponding Review_is_helpful object does not exist), then any suitable false value, like None will be okay. I was looking for something along the lines of using reviews.annotate(...), but I'm not sure what … -
importing arbitrary fields of a model from excel by django-import-export
I am using Django I have a model like this class DialogText(models.Model): id = models.AutoField(primary_key=True) dialogId = models.ForeignKey(Dialog, on_delete=models.CASCADE, verbose_name="Dialog") whoSay = models.CharField(blank=True, max_length=255) text = models.TextField(blank=True, verbose_name="Dialog Text") image = models.ImageField(upload_to=textDirectory, blank=True, verbose_name="Picture") createdTime = models.DateTimeField(auto_now_add=True) state = models.CharField(blank=True, max_length=255) sayTime = models.CharField(blank=True, max_length=255) text_type = models.CharField(blank=True, max_length=255) I am using django-import-export to import my data from excel. But I don't want all fields of my model to be imported from excel. For example, I haven't any column named 'id' in excel or I should set 'createdTime' the current time of the server and don't import from excel. I have tried this but it didn't work: class DialogTextResource(resources.ModelResource): fields = ('whoSay', 'text', 'text_type', 'sayTime', 'state', 'image', 'dialogId') class Meta: model = DialogText class DialogTextAdmin1(ImportExportModelAdmin): resource_class = DialogTextResource Thank's for any help. -
Object not found, but does exist
I have an existing working site, that takes advantage of Adobe Lightroom's catalog being an sqlite3 db. The model is auto-generated. Whilst updating the code for the site (to TemplateView and streamlining), I thought I'd get adventurous and pull on one of the class models to get the information about how many times a face (person) appears in the photos. The model: class Aglibrarykeywordpopularity(models.Model): id_local = models.IntegerField(primary_key=True, blank=True, null=False) occurrences = models.TextField() # This field type is a guess. popularity = models.TextField() # This field type is a guess. tag = models.TextField(unique=True) # This field type is a guess. class Meta: managed = False db_table = 'AgLibraryKeywordPopularity' The 'tag' value is obtainable from another model, where it's called 'id_local': face_id = list(Aglibrarykeyword.objects.values_list('id_local', flat=True)) The values for the 'face_id' are all present in the previous 'tag' field when you view the db. However, when using: for a in face_id: face_pop.append(Aglibrarykeywordpopularity.objects.get(tag=a).occurrences) .. it complains that there are no matches. I've substituted 'a' for a number, or string of the number, even adding '.0' to the representation, and it still complains no matches. I've tried .filter...first() etc. slides.models.DoesNotExist: Aglibrarykeywordpopularity matching query does not exist My current work-around is going to output All() of … -
Django model accessed globally
I want to have a model accessed throughout the whole project in the templates, not to declare it on every view. Is this possible? What is the best way to do this? Something like User is accessed through request.user. -
Django: Working With Messages
I'm trying to create a messaging app similar to what we see on social networks. Here's my model, class Message(models.Model): sender = models.ForeignKey(User, related_name="sender") receiver = models.ForeignKey(User, related_name="receiver") ... timestamp = models.DateTimeField(auto_now_add=True) Everything is fine I can filter out the messages for request.user, but couldn't order the users. I wants to order the Users based upon to whom request.user sent a message & who sent a message to request.user most Recently, as we see on social networks. How can I do that? -
How to handle AuthAlreadyAssociated at Python-auth/Django-Social?
I use this python-social-auth/social-app-django to connect my web with social media I want to ask how to handle errors when the same account is used to sign up? For example, I signed up using facebook and I signed up again using twitter. both successfully registered into two separate accounts, when I logged in using my facebook and then on my account settings page, I want to connect my twitter that has been registered before it will display an error message "AuthAlreadyAssociated at / oauth / complete / twitter /" AuthAlreadyAssociated This message appears after I authorize on the twitter redirect page when it gets redirected back to my web. In short, how to deal with accounts that have been registered in other accounts? This is my views.py: @login_required def settings(request): user = request.user try: github_login = user.social_auth.get(provider='github') except UserSocialAuth.DoesNotExist: github_login = None try: twitter_login = user.social_auth.get(provider='twitter') except UserSocialAuth.DoesNotExist: twitter_login = None try: facebook_login = user.social_auth.get(provider='facebook') except UserSocialAuth.DoesNotExist: facebook_login = None can_disconnect = (user.social_auth.count() > 1 or user.has_usable_password()) return render(request, 'profile/settings.html', { 'github_login': github_login, 'twitter_login': twitter_login, 'facebook_login': facebook_login, 'can_disconnect': can_disconnect }) And this is my settings.html template: {% extends "base.html" %} {% load crispy_forms_tags %} {% block title %}Navhi Microblog - … -
Django aggregation and filtering
I am working with a model having a date, a group, and an identifier. I want to retrieve for each group the id of the minimum date value. My model: class MyModel(models.Model): group = models.ForeignKey('myapp.Group') date = models.DateTimeField(blank=True, null=True) The goal is to retrieve this: [ (u'group1', datetime.date(2016, 1, 23), 15 <- Id of the minimum date for group1), (u'group2', datetime.date(2015, 6, 25), 314 <- Id of the minimum date for group2), ... ] I tried the following: MyModel.objects.values_list('group').annotate(Min('date')).order_by('group') This works fine but gives me the date: [ (u'group1', datetime.date(2016, 1, 23)), (u'group2', datetime.date(2015, 6, 25)), (u'group3', datetime.date(2015, 6, 26)) ... ] I cannot find a way to add the id to those tuples without breaking the grouping clause in SQL. I tried to do a where date = min(date), but aggregation is forbidden in where clause. -
DjangoCMS render_model with HTML
I'm using Django CMS and the Aldryn News Blog app on a client site to display a blog listing. The default template code uses {% render_model article "lead_in" %} to display the "Lead in" excerpt text. However it is displaying p tags for me and I actually need them to render. https://pasteboard.co/GSq8XObQ.png https://pasteboard.co/GSq8ONF.png I have tried both: {% autoescape off %} {% render_model article "lead_in" %} {% endautoescape %} {% render_model article "lead_in" |safe %} The first does nothing and the second errors out. How can I get it to render the html tags? -
Hidden fields, auto assign values in django
I am still a newbie on django and Python. This is also my first question. I am trying to create a hidden field and auto assign a value to the hidden field. It can be either in the views or in the templates. I have a field "kind" that needs to be hidden. Also I need to assign a value to it depending on different views/templates so it populates the database. This is my class view: class Monthlypage(CreateView): template_name = 'monthly.html' model = models.Lead form = forms.LeadForm() fields = ['name','email','tel','kind'] This is my model form: class LeadForm(forms.ModelForm): def __init__(self, *args, **kwargs): kind = models.Lead.kind class Meta: model = models.Lead kind = forms.CharField(widget=forms.HiddenInput()) fields = ['name','email','tel','kind'] This is my model: class Lead(models.Model): name = models.CharField(max_length=265) email = models.EmailField(max_length=265) tel = models.IntegerField() kind = models.CharField(max_length=265) def __str__(self): return self.name def get_absolute_url(self): return reverse('registrations') This is my template: <form class="" method="post"> {% csrf_token %} {% bootstrap_form form %} <input type="hidden" name="kind" value="{{ form.kind.monthly }}" /> <input type="submit" name="" value="Submit" class="btn btn-info"> I have tried many options and spend 2 days using different solutions. But no matter what I do I can't seem to populate the kind field in the database. -
Django. Algorithm on the back of the server [on hold]
Need to make a schedule program with an algorithm on the back of the server. Is it possible to make it in "pure" python on the back or should I use something else, like Ajax to change data on the server? What should I use?