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


Django - Feeding only part of Foreignkey in models

Question:

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)

#models.py
#these are the type (groceries/clothes/etc. )
class TypWydatku(models.Model):
    typ_wydatku = models.CharField(max_length=25)
    data_wpisu=models.DateField(auto_now_add=True)

#these are the actual input with dates/prices/etc
class Wpisy(models.Model):
    data_zakupu=models.DateField(default=timezone.now())
    data_wpisu=models.DateField(auto_now=True)
    typ_wydatku=models.ForeignKey(TypWydatku)
    kwota=models.FloatField('kwota')
    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):

#models.py 
(...)
class WpisyMoto(models.Model):
   wpis=models.ForeignKey(Wpisy)
   przebieg=models.IntegerField()
   uwagi=models.CharField(max_length=200)
   litry=models.FloatField()
   #and more

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

# forms.py
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 ?


Answer:

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)

Related:


Show only the requested forms using JS


javascript,jquery,html,html5,forms
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"...

How can i hook into django migrations for django 1.8


python,django,migration
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...

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


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...

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


django,sorl-thumbnail
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...

Permission denied Setuptools


python,django,curl,setuptools
I'm trying install setuptools in my Mac, but when I run command curl https://bootstrap.pypa.io/ez_setup.py -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:...

Django REST tutorial DEBUG=FALSE error


python,django,django-rest-framework
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...

Javascript/jQuery form validation


javascript,jquery,forms,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 file upload took forever with Phusion Passenger


django,apache,file-upload,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...

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


php,html,forms,joomla
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 MySQLClient pip compile failure on Linux


python,linux,django,gcc,pip
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...

Upload to absolute path in Django


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...

DjangoCMS 3 Filter Available Plugins


django,django-cms
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: show newlines from admin site?


python,html,django,newline,textfield
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!

Using .update with nested Serializer to post Image


django,rest,django-models,django-rest-framework,imagefield
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...

How can I resolve my variable's unexpected output?


django,python-2.7
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...

Javascript into HTML form


javascript,html,forms
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...

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


javascript,jquery,ajax,wordpress,forms
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....

Multiple AJAX forms with the same ID on the same page


javascript,php,jquery,ajax,forms
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...

How to use template within Django template?


python,html,django,templates,django-1.4
I have the django template like below: <a href="https://example.com/url{{ mylist.0.id }}" 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...

Why is Django widgets for TimeInput not showing


django,django-forms,django-templates,django-views
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 models.py, class TimeLimit(models.Model): before = models.TimeField(blank=True, default=time(7, 0)) # 7AM after = models.TimeField(blank=True,...

Correct PHP contact form syntax? [duplicate]


php,forms,validation
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...

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


python,django,osx,notifications,vagrant
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...

Put form fields two per line in bootstrap form


html,forms,twitter-bootstrap-3
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">...

DRF Update Existing Objects


django,django-rest-framework
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:...

Create angular page in Django to consume data from JSON


angularjs,django,django-templates
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= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script> </head> <body data-ng-app="myApp"> <div data-ng-controller="MainController">...

Codeigniter Form Validation Rule for match (password)


php,forms,codeigniter,validation
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 block inclusion not working. What did I miss?


django,django-templates
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...

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


ruby-on-rails,forms
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...

Django listview clone selected record


django
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...

Django: Handling several page parameters


python,django,list,parameters,httprequest
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....

Django test RequestFactory vs Client


django,unit-testing,django-views,django-rest-framework,django-testing
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...

Django: html without CSS and the right text


python,html,css,django,url
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


php,forms,symfony2,runtime-error
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...

Use django to expose python functions on the web


python,django
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...

django 1.8 CreateView Error


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

Django add an attribute class form in __init__.py


python,django,forms,django-forms
My form class from django import forms class Form(forms.Form): your_name = forms.CharField(label='Your name ', max_length=100) My app file __init__.py 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 __init__.py add an attribute captcha but it is not on the page. I...

upload_to dynamically generated url to callable


python,django,models
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...

django and python manage.py runserver execution error


python,django,manage.py
When I execute python manage.py 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 http://127.0.0.1:8000/ Quit the server with CONTROL-C. Traceback (most recent call last): File "manage.py",...

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


php,mysql,forms,get
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 (https://microworkers.com/vcode.php) in the final page and so workers can submit it as their proof of finishing my...

PHP+HTML: file not loaded from form


php,html,forms
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...

Entering data into mysql database using php


php,mysql,forms,mamp
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"/>...

Angular submit not called when required fields not filled


javascript,angularjs,forms
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...

Django template not found in main project directory error


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

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


python,django,pip,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...

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


json,django,django-templates,django-rest-framework
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(default=date.today) 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 })...

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


django,django-models,django-admin
In https://docs.djangoproject.com/en/1.8/ref/models/fields/#django.db.models.Field.default 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(default=datetime.datetime.now()) When in the admin page I create a new object I always get the same datetime, as if the callable is...

Get the first image src from a post in django


django,django-templates,django-views
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(default=timezone.now) publish = models.BooleanField(default=False) In the admin it looks like this:...

Form not submitted using jquery


javascript,jquery,html,forms
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 "...

Show message when there's no excerpt - Django templates


python,django,django-templates,django-template-filters
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...