Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Can't get ModelForm Field to override the Model Field
I'm trying to add a DateTimeWidget and Initial value to the due_date field of my Model, I'm following the documentation as close as I can tell. No matter what I try, I can't get the field declared in my ModelForm class to override my existing field in the Model. https://docs.djangoproject.com/en/1.9/topics/forms/modelforms/#overriding-the-default-fields If I add a Widget separately it works, but then I don't know how to add an initial value unless I set the default in the model. Can someone point out what I'm doing wrong? from django import forms import datetime from datetimewidget.widgets import DateTimeWidget from .models import EstRequest def due_date(): due_date = (datetime.datetime.now() + datetime.timedelta(days=1)) return due_date class EstRequestModelForm(forms.ModelForm): class Meta: model = EstRequest due_date = forms.DateTimeField(widget=forms.DateTimeInput, initial=due_date) fields = [ 'market', 'plan', 'builder', 'due_date', 'notes', ] # widgets = { # # Use localization and bootstrap 3 # 'due_date': DateTimeWidget(attrs={'id': "due_date"}, usel10n=True, bootstrap_version=3) # } -
How to show many to many checked checkboxes on the template?
I'm trying to create a multi step form where there are checkboxes that are linked to objects, But I don't understand how I can show the checked values only on my the final step of my form. Models.py class FormOne(models.Model): fn = models.CharField(max_length=40) def __str__(self): return self.fn class FormTwo(models.Model): owner = models.ForeignKey(FormOne) name = models.CharField(max_length=40) def __str__(self): return self.name class Font(models.Model): font_name = models.CharField(max_length=100) font_family = models.CharField(max_length=100) font_link = models.CharField(max_length=100) font_checkbox = models.ManyToManyField(FormOne, blank=True) def __str__(self): return self.font_name Views.py def step3(request): context = {'Fonts':Font.objects.all()} return render(request, 'step3.html', context) step3.html {% for font in Fonts %} <p>{{ font.font_name }}</p> {% endfor %} let's say, I checked half of the checkboxes it will show me all the fonts existing in the database instead of the checked ones. How can I resolve it, what should I filter ? -
Get PDF from HTML page with xhtml2pdf Django
I get a little problem with my function letting to get a PDF file from my HTML view. It's maybe not possible to get what I want but I think you have a solution. From a form, I generate a resume which could be exportable to PDF file. My function looks like : def BirthCertificate_PDF(request, id) : birthcertificate = get_object_or_404(BirthCertificate, pk=id) data = {} template = get_template('BC_raw.html') html = template.render(Context(data)) file = open('test.pdf', "w+b") pisaStatus = pisa.CreatePDF(html.encode('utf-8'), dest=file, encoding='utf-8') file.seek(0) pdf = file.read() file.close() return HttpResponse(pdf, 'application/pdf') And my template looks like : <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> </head> <h2 align="center"> ACTE DE NAISSANCE </align> </h2> {% block content %} <h3 align = "right"> Acte de Naissance n° {{birthcertificate.id}} </align> </h3> <h3> Informations concernant l'enfant : </h3> <li> Nom de l'enfant : {{birthcertificate.lastname}}</li> <li>Prénom(s) de l'enfant : {{birthcertificate.firstname}}</li> <li>Est né(e) à : {{birthcertificate.birthcity}}</li> <li>Le : {{birthcertificate.birthday}} à {{birthcertificate.birthhour}}</li> <li>De sexe : {{birthcertificate.sex}}</li> <hr width = "50%"></hr> <h3> Informations concernant le père : </h3> <li>Fils ou fille du nommé : {{birthcertificate.fk_parent1.lastname}} {{birthcertificate.fk_parent1.firstname}}</li> <!-- Get only firstname and lastname element --> <li>Né le : {{birthcertificate.fk_parent1.birthday}}</li> <!-- Get only birthday element --> <li>A : {{birthcertificate.fk_parent1.birthcity}}</li> <!-- Get only birthcity element --> … -
foreign key model value in template
Is there anything that would prevent access to the default User model ? Model: class Chart( models.Model ): title = models.CharField( max_length = 255 ) author = models.ForeignKey( User, related_name = 'the_author' ) created_at = models.DateTimeField( auto_now = False, auto_now_add = True ) updated_at = models.DateTimeField( auto_now = True, auto_now_add = False ) def __str__( self ): return self.title The other model is User, from djangoALLauth. I didn't created this model, but is has an 'email' field I want to access. The view that build the template: def home( request ): """Home page handling""" most_favorited_charts = Chart.objects.order_by( '-favorites_count' )[ :10 ] newest_charts = Chart.objects.order_by( '-created_at' )[ :10 ] context = { "js_dow_data" : jsdow_data( ), "most_favorited_charts": most_favorited_charts, "newest_charts": newest_charts, "submit_value": "Save" } The template. I want to get the 'email' from User model, which is referenced as a foreign key from the Chart model as shown above. Here is the latest attempt from many other. See the block where I try to produce 'Email:" content: {% for chart in most_favorited_charts %} <div class="user-charts-links-div"><a class="chart-title" href="#">{{ chart.title }}</a> {% for author in chart.the_author.all %} Email: {{ author.the_author.email }}<br> {% endfor %} </div> </div> {% endfor %} It produces nothing and I … -
Using Django How Can I Automatically Update Information on a Template
I'm not looking for exact code, but rather some guidance on my problem. On one of my pages, I want to have a small section that will tell the user the disk space left on the server and I want this information to update every 30 seconds. I have the code already written to get the disk information. However, I am unsure on how to display that information and have it update. This is what I have, just to give you a visual: The HTML I'm working with: {% extends "Checklist/base.html" %} {% block main_content %} <form action="{% url 'Checklist:run' %}" method="post"> {% csrf_token %} <input type="submit" name="submit_button" value="Run"> </form> <label for="disk_space">Disk Space: </label> <input type="text" name="disk_space" value="{{ disk_space }}" id="disk_space"> {% endblock %} The Views Function for the HTML: def submit(request): #start scrtipt submit.preProcess = subprocess.Popen(['chmod', '+x /home/psvuser/Desktop/test.sh']) submit.process = subprocess.Popen(['/home/psvuser/Desktop/test.sh']) global sem sem = True disk_space = request.get('disk_space', '') disk_space = diskSpace() start_time= int(round(time.time())) f = open("/home/psvuser/Desktop/writer.txt", "a") f.write(str(start_time)) f.write(", ") return render(request, 'Checklist/stop.html') I have an idea on how to periodically refresh the page, however, I don't know how to display 'disk_space' onto the html. -
logout remote user from django website using Mod Auth NTLM for Apache 2.4.x
how can i logout a remote user from a django website? I am using Mod Auth NTLM for Apache on windows. so far i have tried to return a 401 response when the user tries to logout which did not work. def get(self, request, *args, **kwargs): logout(request) return render(request, self.template_name,{},status=401) these are my apache settings <Location / > AuthName "Private location" AuthType SSPI NTLMAuth On NTLMAuthoritative On NTLMOmitDomain on <RequireAll> <RequireAny> Require valid-sspi-user </RequireAny> <RequireNone> Require user "ANONYMOUS LOGON" Require user "NT AUTHORITY\ANONYMOUS LOGON" </RequireNone> Require sspi-group MYGROUP\DEPARTMENT </RequireAll> RequestHeader set X-Remote-User expr=%{REMOTE_USER} </Location> -
why use apache solr when ajax can search?
I was working on a Django Project, I found that to implement a search bar I can use Apache Solr(with Haystack) or ElasticSearch or similar search engine. What I was wondering is why to use these search engines when ajax can search for results. I understand the question is broad but didn't found a suitable answer. -
Unzip user uploaded files through models in Django
The user can upload zip file through models.py but I can not then unzip the file to iterate through the images and display them in my template. Models.py from django.db import models from django.core.urlresolvers import reverse from django.contrib.auth.models import User from django.conf import settings from .validators import validate_file_extension class Post(models.Model): title = models.CharField(max_length=140) body = models.TextField(max_length=250) date = models.DateTimeField(auto_now=True, auto_now_add=False) album_image = models.FileField(validators=[validate_file_extension]) user = models.ForeignKey(User, default=1) def get_absolute_url(self): return reverse('photos:detail',kwargs={'pk':self.pk}) def __str__(self): return self.title views.py Post create and index view works/ or at least worked until i changed from uploading a single image to uploading zip files and trying to iterate class IndexView(generic.ListView): template_name='photos/post.html' def get_queryset(self): return Post.objects.filter(user=self.request.user) def DetailView(request,pk=""): model = Post z = zipfile.ZipFile() ### I am unsure of what goes here!! context = { "images": z, } template_name = 'photos/detail.html' return render(request,template_name,context) class PostCreate(generic.CreateView): form = PostForm() model = Post fields = ['title','body','album_image'] if form.is_valid(): instance = form.save(commit=False) username = form.cleaned_data['username'] album_image = form.cleaned_data['album_image'] instance.save() context = { "form": form, } detail.html {% extends "homepage/header.html" %} {% block content %} {% for image in image%} <img src ="{{image.url}}" style="width:304px;height:228px;"> {% endif%} <h1>{{post.title}}</h1> <h3>{{post.user}}</h3> <h3>{{post.body}}</h3> <h3>{{post.date}}</h3> {% endblock %} -
In django form how to add checkboxes instead of radio button?
I have a form where for one specific field I can have multiple choices. Something like What would you like to eat this weekend? Choice 1: Italian Choice 2: Mexican Choice 3: Greek Choice 4: Indian I have radio button for all possible choices but because weekend is a multiple meals most of the time people want to select more than just one item. That makes me think it may be a good idea to have checkboxes associated with all possible choices. How do I go about converting my radio buttons into a checkboxes ?? Please advise. Thanks. -
No wkhtmltopdf executable found
I'm trying to get a PDF file from my HTML template using pdfkit library and wkhtmltopdf but I get an error and I don't find any solutions on Stackoverflow. I read this topic : Can't create pdf using python PDFKIT Error : " No wkhtmltopdf executable found:" But nothing for the moment ... I tried two things : def BirthCertificate_PDF(request, id) : birthcertificate = get_object_or_404(BirthCertificate, pk=id) pdfkit.from_file('BC_raw.html','test.pdf') return render(request, 'BC_raw.html', {"birthcertificate" : birthcertificate}) and def BirthCertificate_PDF(request, id) : birthcertificate = get_object_or_404(BirthCertificate, pk=id) path_wkhtmltopdf = r'/usr/local/lib/python2.7/site-packages/wkhtmltopdf' config = pdfkit.configuration(wkhtmltopdf = path_wkhtmltopdf) pdfkit.from_file('BC_raw.html','test.pdf', configuration = config) return render(request, 'BC_raw.html', {"birthcertificate" : birthcertificate}) And I get this error each time : Exception Value: No wkhtmltopdf executable found: "/usr/local/lib/python2.7/site-packages/wkhtmltopdf" If this file exists please check that this process can read it. I made : chmod 755 but still nothing. Do you have a solution ? EDIT : I made ls -lth command : MacBook-Pro-de-Valentin:site-packages valentinjungbluth$ ls -lth total 8864 drwxr-xr-x 12 valentinjungbluth admin 408B 21 déc 16:22 pdfkit drwxr-xr-x 10 valentinjungbluth admin 340B 21 déc 16:22 pdfkit-0.6.0.dist-info drwxr-xr-x 11 valentinjungbluth admin 374B 21 déc 16:22 wkhtmltopdf drwxr-xr-x 9 valentinjungbluth admin 306B 21 déc 16:22 wkhtmltopdf-0.2.dist-info drwxr-xr-x 14 valentinjungbluth admin 476B 20 déc 12:06 pyPdf … -
How to access other model's attribute in one model via Foreign key in django?
class Grade(models.Model): name = models.CharField(u'年级', max_length=64) school = models.ForeignKey('School', verbose_name=u'学校') def __unicode__(self): return self.name class Class(models.Model): name = models.CharField(u'班级', max_length=64) grade = models.ForeignKey('Grade', verbose_name=u'年级', related_name='grade') def getGradeName(self): return self.grade.name def __unicode__(self): return self.name class Student(models.Model): name = models.CharField(u'姓名', max_length=64) sex = models.CharField(u'性别', max_length=64) id_num = models.CharField(u'身份证号', max_length=64) student_num = models.CharField(u'学号', max_length=64) class_id = models.ForeignKey('Class', verbose_name=u'班级', related_name='class_id') grade = class_id.name def __unicode__(self): return self.name I want to get students'class'grade and then assign it to grade in Model Student. How to get Grade's name in model Student? -
Does Django 1.10 still need South to manage migrations?
I am following online instructions on starting a Django project the right way. The instructions are based on an earlier version of Django. From my (admittedly limited) knowledge of Django. The latest release of Django (1.10 at the time of posing this question), already handles migrations seemingly well - by way of the manage.py script. My question then is this: Do I still need to install South to manage my migrations, or can I simply skip that part of the instructions, and use manage.py to deal with my db schema changes? -
Display dropdown Choice field in Django admin
I am begin to Django and I start create a simple personal blog. I want to create model Category that related to parrent Category. I have read about display Foreign Key's choices in django-admin. It only work with some static choices. But I cannot query data from database for choices. This is how I am trying to do: class Category (models.Model): name = models.CharField(max_length=255) slug = models.CharField(unique=True, blank=True, max_length=255) parent_category = models.CharField(max_length=255, blank=True, choice = CATEGORIES_CHOICE) I want CATEGORIES_CHOICE = Category.object.all(). Any one have an idea to resolve this. -
Pypi deployed package - No matching distribution found for
This seems to have been asked a few times but none of the solutions are working for me. So i have a package deployed to pypi but when i try to pip install i get a No matching distribution found for To deploy it, i did: python setup.py sdist python setup.py bdist_wheel --universal twine register dist/*.whl twine upload dist/* I tried building the wheel without the universal as well with no luck. Any ideas why i am getting the error? -
Json data via ajax to database in django project
How to get json object from the javascript file(static files) by ajax into the django view and then to database in a django project? What will be the possible content in the views file of the app and models.py file also to transfer json data to database? -
Accessing django models from a new script
I have seen many answers on how to use django models outside the project. But I have no success with any. I was trying to implement this answer but I get an error. I have created a new file "script.py" inside my app. script.py from django.conf import settings settings.configure( DATABASE_ENGINE = 'sqlite3', DATABASE_NAME = '/home/shivam/study/Python/automation/project/db.sqlite3', DATABASE_USER = '', DATABASE_PASSWORD = '', DATABASE_HOST = '', DATABASE_PORT = '', TIME_ZONE = 'America/New_York', ) from models import * When I run this script, I get an error. Traceback (most recent call last): File "script.py", line 11, in <module> from models import * File "/home/shivam/study/Python/automation/project/videos/models.py", line 11, in <module> class video(models.Model): File "/home/shivam/study/Python/automation/env/local/lib/python2.7/site-packages/django/db/models/base.py", line 105, in __new__ app_config = apps.get_containing_app_config(module) File "/home/shivam/study/Python/automation/env/local/lib/python2.7/site-packages/django/apps/registry.py", line 237, in get_containing_app_config self.check_apps_ready() File "/home/shivam/study/Python/automation/env/local/lib/python2.7/site-packages/django/apps/registry.py", line 124, in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. Can somebody help me with this? -
Django REST: weird dot in url-reverse
The router code: ... domain_nested_routers_lookup = 'domain' router = routers.DefaultRouter() router.register('accounts', DomainViewSet) ... domains_router = NestedSimpleRouter(router, r'accounts', lookup=domain_nested_routers_lookup) The reason for such a move is because project old API used the term domain, that is not getting changed to account. The serializercode: class DomainSerializer(...): link = serializers.HyperlinkedIdentityField(view_name='domain-detail', lookup_field='short_name') Now the problem is that this code: self.api_reverse('domain-detail', self.domain.id) returns: u'/rest/accounts/domain_0.1' And I don't understand by what magic .1 is added (1 is an id of domain object). The correct output should be: u'/rest/accounts/domain_0 -
Django form rendering with initial data
I have a question model and answer models depending whether the question is multiple choice or text input. In my views I am trying to render the form with initial data. The initial data will get the user answer if it has already been answered and it works fine but when a question appears whose answer has not been given by the user then the RelatedObjectDoesNotExist exception is thrown and it says "UserTextAnswer has no my_answer" which is given in templates. My Models: Question_Types_Choices = ( ('multiple_choice', ('multiple_choice')), ('text_input', ('text_input')) ) class Question(models.Model): text = models.TextField() active = models.BooleanField(default=True) question_type = models.CharField(max_length = 250, choices =Question_Types_Choices) timestamp = models.DateTimeField(auto_now_add=True , auto_now=False) def __unicode__(self): return self.text[:10] class FreeTextAnswer(models.Model): answers = models.ForeignKey(Question) text = models.TextField(blank=True, null=True) active = models.BooleanField(default=True) timestamp = models.DateTimeField(auto_now_add=True , auto_now=False) def __unicode__(self): return self.text[:10] class UserTextAnswer(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL) question = models.ForeignKey(Question) my_answer = models.ForeignKey(FreeTextAnswer) my_points = models.IntegerField(default=-1) timestamp = models.DateTimeField(auto_now_add=True, auto_now=False) def __unicode__(self): return self.my_answer.text[:10] In my views: def single(request,id): if request.user.is_authenticated(): queryset = Question.objects.all().order_by('-timestamp') instance = get_object_or_404(Question, id=id) try: user_text_answer = UserTextAnswer.objects.get(user=request.user, question=instance) except UserTextAnswer.DoesNotExist: user_text_answer = UserTextAnswer() except UserTextAnswer.MultipleObjectsReturned: user_text_answer = UserTextAnswer.objects.filter(user=request.user, question=instance)[0] except: user_text_answer = UserTextAnswer() try: free_text_answer = FreeTextAnswer.objects.get(answers_id=instance.id) except FreeTextAnswer.DoesNotExist: free_text_answer = … -
text field and button alignment
I have a Django Form like this : class FriendrequestMixinForm(forms.Form): email = forms.EmailField() def __init__(self, *args, **kwargs): self.helper = FormHelper() self.helper.layout = Layout ( Row (Div('email', css_class="col-md-6"), FormActions (Submit('submit', 'Add'), Button("cancel", "Cancel")))) super(FriendrequestMixinForm, self).__init__(*args, **kwargs) The buttons are aligned like this : Example Layout How can I align the buttons at the bottom of the Email Field in one row Thanks for your help -
sorl thumbnail not working
I'm having an issue with getting sorl thumbnail to work. I've added sorl.thumbnail to INSTALLED_APPS and in the template at the top {% extends 'base.html' %} {% load thumbnail %} I've also checked if pillow is properly installed. Tested it <span class="test">{% thumbnail "http://animal-dream.com/data_images/cow/cow5.jpg" "1300x700" as image %}{{ image.url }}{% endthumbnail %}</span> Did the above just to see the output. When I check $('.test') <span class="test"></span> -
Non blocking requestin in django save models
I would like to send to a server the json version of a model. but i would like to send it with a non blocking request def save(self, *args, **kwargs): ''' On save, update timestamps ''' if not self.id: self.created = timezone.now() r = requests.post('http://localhost:9040/put_img/', json=self.to_json()) return super(IdImg_Data, self).save(*args, **kwargs) Any idea how to do that in the save function ? thanks and regards -
Django tastypie POST 400 bad request
I have the following problem with Django 1.7 and django-tastypie 0.13.3, upgrading from Django 1.6 and django-tastypie 0.9.14. urls.py from relationships.api import RelationResource v1_api = Api(api_name='v1') v1_api.register(RelationResource()) In the template this code is called: var Relationships = Relationships || {}; $.ajaxPrefilter(function(options, originalOptions, jqXHR){ if(options["type"].toLowerCase() != "get") { options["contentType"] = "application/json"; options["data"] = JSON.stringify(originalOptions["data"]); } }); Relationships.Relation = can.Model({ attributes: { id: 'to_int' }, convert: { to_int: function(raw) { return parseInt(raw); } }, models: function(data){ return data.objects; }, model: function( attributes ) { return new this(attributes); }, findAll: "GET /api/v1/relationships/", findOne: "GET /api/v1/relationships/{id}/", create: "POST /api/v1/relationships/", update: "PUT /api/v1/relationships/{id}/", destroy: "DELETE /api/v1/relationships/{id}/" },{ }); Relationships.Button = can.Control({ init: function(element, options){ }, 'click': function(el, ev){ var following = Boolean(el.data('following')); var from_user = el.data('from_user'); var to_user = el.data('to_user'); var url = '/api/v1/relationships/'; var from_user_uri = '/api/v1/users/' + from_user + '/'; var to_user_uri = '/api/v1/users/' + to_user + '/'; var self = this; if(following) { Relationships.Relation.findAll({ 'from_user': from_user, 'to_user': to_user}, function(items){ if(items.length == 1) { var item = new Relationships.Relation(items[0]); item.destroy(function(){ }); } }); } else { var item = new Relationships.Relation({'to_user': to_user_uri}); item.save(function(){ }); } } }); This gives an error: POST http://0.0.0.0:8000/api/v1/relationships/ 400 (BAD REQUEST) This code worked fine with the previous … -
modelformset_factory foreignkey triggers database query
My model has a foreignkey: class Status(models.Model): status_code = models.CharField(max_length=10, verbose_name="Status Code") description = models.CharField(max_length=256, verbose_name="Description") def __unicode__(self): return "%s - %s" % (self.status_code, self.description) def __str__(self): return "%s - %s" % (self.status_code, self.description) class PickUp(models.Model): name = models.CharField(max_length=60, verbose_name="Name") status = models.ForeignKey(Status, verbose_name="Status", default=None, blank=True, null=True) deleted = models.BooleanField(default=False) def __unicode__(self): return self.name This is my (abbreviated) view: def index(request): context = dict() PickupFormSet = modelformset_factory(PickUp, fields='__all__', form=PickupForm) qs = PickUp.objects.filter(deleted=False, date_processed=None).prefetch_related('status') context['pickupformset'] = PickupFormSet(queryset=qs) return render(request, "index.html", context) This is part of the template: {% for pickup in pickupformset %} {% if pickup.id.value %} <tr> <td>{{ pickup.id }}{{pickup.deleted}}</td> <td>{{pickup.name}}{{pickup.name.value}}</td> <td>{{pickup.status}}</td> </tr> {% endif %} {% endfor %} Each record displayed triggers a database query to get the status description. SELECT `frontend_status`.`id`, `frontend_status`.`status_code`, `frontend_status`.`description` FROM `frontend_status` Do you know why or how I can prevent this? -
Django - Page not fully loaded after exception in form
In my django project, I have a view that displays details of an event. In that view there is a link to another view that contains the form to register people to that event. If the maximum number of participants is reached and someone still tries to register, my view throws an exception. And returns from the formular-site back to the event-site. But the event-site is not fully loaded, I think the queries are no performed. I don't know how to write the return function. Additionally, is there a syntax error in my exception? When I create new instances of registration in the shell, I can save as many as I want. def validate_category_full(category_id): cat = Category.objects.get(id=category_id) regs = cat.registration_set.all() if len(regs) >= cat.max_people: raise ValidationError('Category is already full.') def registration(request, category_id, event_id): """Add a new registration to a category.""" cat = Category.objects.get(id=category_id) myevent = Event.objects.get(id=event_id) if request.method != 'POST': form = RegistrationForm() else: form = RegistrationForm(request.POST) try: validate_category_full(cat.id) except(ValidationError): return render(request, 'events/event.html', {'myevent': myevent, 'error_message': 'Event is full.',}) else: if form.is_valid(): reg = form.save() return HttpResponseRedirect(reverse('events:category', args=(cat.id,))) context = {'form': form, 'cat': cat, 'myevent': myevent} return render(request, 'events/registration.html', context)` -
A way to save the generated HTML from Django Views?
I'm trying to save all the HTML pages from the model objects I'm querying in. For instance for every model_id I have in the database, I want to save the http://127.0.0.1:8080/model_id. I'm currently connecting to the local server shown above, and pinging through every http://127.0.0.1:8080/#id1, http://127.0.0.1:8080/#id2, http://127.0.0.1:8080/#id600..etc. Is there a way I can get the html without using the local server to query?