django,forms,filter,model,foreign-keys , Django - Feeding only part of Foreignkey in models

Django - Feeding only part of Foreignkey in models


Tag: django,forms,filter,model,foreign-keys

i'm new to django and as a exercise I want to make "home expenses". I've already did simple model and form : (from models)
#these are the type (groceries/clothes/etc. )
class TypWydatku(models.Model):
    typ_wydatku = models.CharField(max_length=25)

#these are the actual input with dates/prices/etc
class Wpisy(models.Model):
    uwagi=models.CharField(max_length=255, blank=True)

But now I would like to add another model, which will describe expenses connected to my car more specific. So I add another TypWydatku - Moto with id=3

Next step is to create new model with extra fields (mileage/ fuel tanked): 
class WpisyMoto(models.Model):
   #and more

I have the sipmlest forms as one can have rigth now :

class TypWydatkuForm(ModelForm):
    class Meta:
        model = TypWydatku
        fields = '__all__'

class WpisyForm(ModelForm):
    class Meta:
        model = Wpisy
        fields = '__all__'

class WpisyMotoForm(ModelForm):
    class Meta:
        model = WpisyMoto
        fields = '__all__'

I would like to have choice field 'wpis' in the template, where i want to see onlythose which have 'typ_wydatku'=3. How should I do it ?


From the docs for the ModelChoiceField field (which is the form field type Django will use to represent the ForeignKey field), this can be achieved by setting the form field's queryset attribute:

class WpisyMotoForm(ModelForm):

    class Meta:
        model = WpisyMoto
        fields = '__all__'

    def __init__(self, *args, **kwargs):
        super(WpisyMotoForm, self).__init__(*args, **kwargs)
        self.fields["wpis"].queryset = Wpisy.objects.filter(typ_wydatku__pk=3)


PHP+HTML: file not loaded from form

In my form a user can choose to upload a file. So, here's the correspondent field in the form. here is the html code: <p> <label>Allega fattura</label> <span class="field"> <input type="file" name="allegato_fattura" id="allegato_fattura" value="Sfoglia..." /> </span> and when the submit button is clicked, here we go: ... define("DIR_FATTURE","fatture/"); $fatturaFileName; $addedFattura...

DRF Update Existing Objects

I'm new to DRF and python so go easy on me... I can successfully get the RoadSegment objects, but I cannot figure out how to update an existing object I have the following model: class RoadSegment(models.Model): location = models.CharField(max_length=100) entryline = models.CharField(unique=True, max_length=100) trafficstate = models.CharField(max_length=100) With the following serializer:...

How can I resolve my variable's unexpected output?

I have a variable in django named optional_message. If I debug the variable then it says Swenskt but when I try to print the variable on my page the following comes out: (u'Swenskt',) and the variable can't be tested for its length etc. What should I do if I only...

Entering data into mysql database using php

Customer will complete a form and enter a pathway where they will want the CSV to be exported to. The pathway is entered using the top section of the php (below): <form action="register.php" method="post"> Enter file pathway where CSV will be saved: <input type="text" name="username" required="required"/> <br/> <input type="submit" value="Enter"/>...

Django add an attribute class form in

My form class from django import forms class Form(forms.Form): your_name = forms.CharField(label='Your name ', max_length=100) My app file from django import forms from my_app.forms import Form from captcha.fields import ReCaptchaField def register(form): form.captcha=CaptchaField() register(Form) Code in add an attribute captcha but it is not on the page. I...

Django file upload took forever with Phusion Passenger

I have a Django app deployed using Passenger (I did not choose mod_wsgi because mod_passenger is already there and being used). When I uploaded an MP3 file (900 kB), Google Chrome displays upload % which reached 100% pretty fast but then it took forever for the resulting page. The database...

php form get parameters from url and store it until the final page

I wrote a simple PHP survey application about movies and I am using one of the crowdsourcing services to collect data. In order to verify and rate workers, I have to generate VCODE ( in the final page and so workers can submit it as their proof of finishing my...

Use django to expose python functions on the web

I have not worked with Django seriously and my only experience is the tutorials on their site. I am trying to write my own application now, and what I want is to have some sort of API. My idea is that I will later be able to use it with...

Create angular page in Django to consume data from JSON

In an angular controller I have a list of items: app.controller('MainController', ['$scope', function($scope) { $scope.items = [ {"foo":"bar 1"}, {"foo":"bar 2"}, {"foo":"bar n"} ] }]); The following html page, based on angular, displays a list of item: <!DOCTYPE html> <html> <head> <title>list</title> <script src= ""></script> </head> <body data-ng-app="myApp"> <div data-ng-controller="MainController">...

Upload to absolute path in Django

I am trying to get upload_to of FileField to be an absolute path rather than relative to MEDIA_ROOT. If I make the path absolute I get a 400 error on post of file. If no leading / it stores under MEDIA_ROOT. The uploaded document needs to be held securely and...

Django test RequestFactory vs Client

I am trying to decide whether I should use Django's Client or RequestFactory to test my views. I am creating my server using DjangoRESTFramework and it's really simple, so far: class SimpleModelList(generics.ListCreateAPIView): """ Retrieve list of all route_areas or create a new one. """ queryset = SimpleModel.objects.all() serializer_class = SimpleModelSerializer...

Show only the requested forms using JS

As the image below illustrates, I have two forms and two buttons. Currently all the forms are visible. How can I only show the requested form "according to the option they have selected (from the blue buttons on the top)"? So, if the user clicked on the "send an invite"...

Multiple AJAX forms with the same ID on the same page

I have two AJAX newsletter subscribe forms on the same page (top and bottom). Both forms have the same ID. The top form works perfectly, however I'm unable to get the alert messages to appear in the bottom form. I found this question but wasn't sure how to implement the...

Rails: get f.range_field to submit null or nil as default value

In my app, I have a range_field where a user can select 0..100. But if they don't select anything, I want the form to submit "null" or nil as the value rather than a numerical value. Is this possible? If I use the below syntax, then everything works except value...

upload_to dynamically generated url to callable

I've seen a lot of post about this problem without really understanding how to solve it. I have this model: class Project(TimeStampedModel): name = models.TextField(max_length=100, default='no name') logo = models.ImageField() I'd like to have my image saved to media root following this template: <name>/logo/<filename> At first glance, I would like...

Display django runserver output from Vagrant guest VM in host Mac notifications?

I can think of many ways to skin this cat, and Googling hasn't shown an elegant solution either. Does anyone have an easy / elegant way to forward the output from Django's runserver command in a terminal connected to a guest Vagrant VM to the host to display to Mac's...

DjangoCMS 3 Filter Available Plugins

In the DjangoCMS3 documentation it says you can configure DjangoCMS behavior using CMS_PLACEHOLDER_CONF in your settings. For instance: CMS_PLACEHOLDER_CONF = { 'right-column': { 'plugins': ['TextPlugin', 'PicturePlugin'], ... This would make TextPlugin and PicturePlugin to be the only two plugins available inside any placeholder called "right-column". It works, but what if...

Django listview clone selected record

From an existing LISTVIEW is there a simple way to create a new record based on existing previos record? 1) select the record 2) call the CREATEVIEW 3) set as initail the data from point 1) would this be possible and which is best? A) Get data from 1) by...

Having Users IP Address Showing In My Email Form [duplicate]

This question already has an answer here: How to get the client IP address in PHP? 13 answers Hello I have created an email form but am very unfamiliar with how to code in a section that displays a users IP address in the email that is sent. Here...

Django: html without CSS and the right text

First of all, this website that I'm trying to build is my first, so take it easy. Thanks. Anyway, I have my home page, home.html, that extends from base.html, and joke.html, that also extends base.html. The home page works just fine, but not the joke page. Here are some parts...

Symfony 2 unable to pass entity repository to form

I have a form with a drop down and a set of checkboxes, i've used entity form field type to get the values via DB. it works with one of the entity but not with the other. i have this code seperately inside AddBadgesType there is NO AddBadges entity <?php...

sorl-thumbnail: Creating a thumbnail inside a for loop in a template

I am trying to create a thumbnail with the size of 100x100 px from an image. I am using a for loop, and the for loops works and the image is rendered but for some reason when I am trying to create a thumbnail it doesn't work. Here is my...

Django: show newlines from admin site?

This is probably very simple. My database objects have a TextField. Now, when I add the contents of the TextFields to an html paragraph, there are no new lines. How can I make Django show those newlines? Thank you!

Callable in model field not called upon adding new object through Django admin

In we read that the callable of a default field value is called, every time a new object is created. In my model I have: when_first_upload = models.DateTimeField( When in the admin page I create a new object I always get the same datetime, as if the callable is...

Permission denied Setuptools

I'm trying install setuptools in my Mac, but when I run command curl -o - | python show a message telling: Processing setuptools-17.1.1-py3.4.egg Removing /Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/setuptools-17.1.1-py3.4.egg Copying setuptools-17.1.1-py3.4.egg to /Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages Adding setuptools 17.1.1 to easy-install.pth file error: [Errno 13] Permission denied:...

Codeigniter Form Validation Rule for match (password)

I am trying to write Form validation rules in my Controller to submit Change Password form in which I am checking the old password too. I am getting the old password(current) from db and placing it in a hidden input field. My Rules are simple and are given below $config=array(...

Django: Handling several page parameters

I have several possible parameter to process in a page. Assume x0, x1, x2,..., x1000. It seems awkward to get and process them one by one by request.GET.get('x0'), request.GET.get('x1'), ... Any idea to put them in a list, so that they can be processed in a loop....

Javascript/jQuery form validation

I got most of this form validation to work properly but the only issue is that when the form detects an error on submit and the user corrects the mistake, the error text won't go away. This can be confusing for the user but I can't seem to figure out...

django and python runserver execution error

When I execute python runserver command for my django_test projects I get following error: System check identified no issues (0 silenced). June 14, 2015 - 20:43:03 Django version 1.8.2, using settings 'django_test.settings' Starting development server at Quit the server with CONTROL-C. Traceback (most recent call last): File "",...

Get the first image src from a post in django

I have a model to write blogs. In that I'm using a wysiwyg editor for the Blog's descritpion, through which I can insert an image within the description. class Blog(models.Model): title = models.CharField(max_length=150, blank=True) description = models.TextField() pubdate = models.DateTimeField( publish = models.BooleanField(default=False) In the admin it looks like this:...

Why is Django widgets for TimeInput not showing

I'm trying to create a TimeInput field in a form and noticed that the widget isn't showing correctly. But when I check the localhost:8000/admin, I see the widget showing up correctly. My code is as follows. For, class TimeLimit(models.Model): before = models.TimeField(blank=True, default=time(7, 0)) # 7AM after = models.TimeField(blank=True,...

django 1.8 CreateView Error

I'm using django 1.8 to create a login form. But the template containing registration form does not render properly. my class SignUpView(CreateView): RegistrationForm = UserCreationForm fields = ['username','password1','password2'] model = User template_name = 'accounts/signup.html' my from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.forms import AuthenticationForm from crispy_forms.helper import FormHelper from...

How can i hook into django migrations for django 1.8

I am using django 1.8. Now i need to add some custom fields based permisions so i have created a YML file from python models like this description: permissions: ['ADMIN'] award: permissions: ['USER'] Its working fine but my issue if some chnages the field names or reomves some field then...

Is there a way to install django with pip to point to a specific version of python in virtualenv

I have a system with CentOS installed. It currently runs python2.6, but python2.7 is also installed. I want to run django 1.7, which is also currently installed. If I run django outside of a virtualenv, it is using python2.6 by default. I didn't install it myself. What I assume is...

Django REST tutorial DEBUG=FALSE error

I'm trying to learn to use the django REST framework via the tutorial. I've gotten to the section "Testing our first attempt at a Web API". When I start the server, I get: System check identified no issues (0 silenced). June 15, 2015 - 00:34:49 Django version 1.8, using settings...

Using .update with nested Serializer to post Image

I have an ImageField. When I update it with the .update command, it does not properly save. It validates, returns a successful save, and says it is good. However, the image is never saved (I don't see it in my /media like I do my other pictures), and when it...

Javascript into HTML form

Hi I am trying to implement a HTML form. Let's suppose it has 4 fields- Name , Age , City (dropdown- contains A,B,C,D) and Region. I want Region field to appear only when City selected is A or B and disappears if city is changed to C and D. Could...

Show message when there's no excerpt - Django templates

I have this field on a Django template: <p class="border_dotted_bottom"> {{ expert.description|slice:":300" }} <a href="{% url 'profile' expert.username %}">{% trans "read more" %}</a>.... </p> If this object (user) has no 'decription' (a text field) it shows the word 'None', I need to get rid of that, maybe if he doesn't...

How can I fill the table? (Python, Django)

I faced with a problem: I have 4 lists with data. And I need to fill the table with this data. It is the example of table: So, as you already understood, at first column must be data from a first list, at second - second list, ... I tried...

Django block inclusion not working. What did I miss?

In my base.html file I have this: {% block menu %}{% endblock menu %} and in base_menu.html I have this: {% extends "base.html" %} {% block menu %} <nav class="navbar navbar-inverse navbar-fixed-top"> ... stuff ... </div> {% endblock menu %} I would expect the menu html to show where the...

Put form fields two per line in bootstrap form

I am using Twitter Bootstrap (version 3) and in the form, I am trying to put these fields two per line, but i cant figure it out how to do it.. Here you can see it in bootply what i have done.. <div class="col-md-10"> <div class="form-group"> <legend>1st sth</legend> <div class="col-md-2">...

Django MySQLClient pip compile failure on Linux

Django documentation as of v1.8 recommends using mysqlclient connector for the framework. I'm attempting to pip install the package on Ubuntu 14.04 with Python 3.4 and running into a GCC error that I'm unable to find reference to. I'm not an expert on compiling software, so was hoping somebody can...

Run AJAX function on form submit button after javascript confirm() cancel

I have a form where and AJAX function runs on form submission to make sure that the data in the form doesn't conflict with data in the database. If a conflict is found, the AJAX function pops up a confirm() box. If the user clicks "OK", the form is submitted....

How to use template within Django template?

I have the django template like below: <a href="{{ }}" target="_blank"><h1 class="title">{{ mylist.0.title }}</h1></a> <p> {{ mylist.0.text|truncatewords:50 }}<br> ... (the actual template is quite big) It should be used 10 times on the same page, but 'external' html elements are different: <div class="row"> <div class="col-md-12 col-lg-12 block block-color-1"> *django...

Form not submitted using jquery

I have following form, <form method="post" action="test.php" id="offer1Form"> <input type="hidden" name="c" value="3883316"> <input type="hidden" name="qtyadd" id="qtyadd" value="1"> <input type="hidden" name="buyid" id="buyid" value="multi"> <input type="hidden" name="multi" id="multi" value="11,1;150,1;182,1;27,1; "> <input type="hidden" name="promocode" value="<?php echo $promote_code1?>"> <input type="hidden" name="continue" value="<?php echo "...

Django template not found in main project directory error

I am getting a 'template not found' error, although I've set up a correct template hierarchy (or so I thought) . ├── ├── twinja │   ├── │   ├── admin.pyc │   ├── │   ├── __init__.pyc │   ├── migrations │   │   ├── │   │   └── __init__.pyc │   ├──...

Angular submit not called when required fields not filled

I'm creating a form in Angular with Ionic. I don't want a red error class to be displayed unless a user has submitted the form. As such, my code looks like this: <form ng-submit="submit()" name="form"> <ion-radio ng-repeat="item in items" ng-model="data.type" name="type" ng-value="item.value" ng-class="{'error' : form.type.$invalid && formSubmitted }" </form> And...

How to work with django-rest-framework in the templates

Please bear with me. I am just learning django-rest-framework. And I really can't seem to grab it. model: class Day(models.Model): date = models.DateField( class ToDo(models.Model): date = models.ForeignKey(Day) name = models.CharField(max_length=100) very_important = models.BooleanField(default=False) finished = models.BooleanField(default=False) normal view: def home(request): days = Day.objects.all() return render(request, 'test.html', { 'days':days })...

Correct PHP contact form syntax? [duplicate]

This question already has an answer here: PHP: “Notice: Undefined variable” and “Notice: Undefined index” 11 answers I am trying to follow a PHP contact form tutorial from here! Seems pretty simple and I'm completely new to PHP. However, when running my project, I get so many "Notice" messages...