FAQ Database Discussion Community


Django: Passing value from template to view

django,django-forms,django-views,streaming,httpresponse
I HAD this situation: Clicking on a html submit button, I call views.stream_response which "activates" views.stream_response_generator which "activates" stream.py and return a StreamingHttpResponse and I see a progressive number every second up to m at /stream_response/: 1 2 3 4 5 6 7 8 //e.g. my default max value for...

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

Adding another model to a form?

django,django-forms,django-views
I'm trying to setup a form which draws in fields from 2 models. I tired to add the model's together like below but keep getting an error. model = Server, Tag The backend admin picks up the relationship between the 2 models and I can update it from the backend...

Django test client: login doesn't work

python,django,django-views
I'm having trouble logging in to test @login_required views in my Django test cases. I have a CustomUser model that looks something like this: class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField('email address', max_length=254, unique=True) username = models.CharField('username', max_length=30, blank=True) is_active = models.BooleanField('active', default=False, help_text='Designates whether this user should be treated as...

Is it possible to display a specific block from a template in django?

django,django-templates,django-views,django-urls,django-template-filters
Just like in html when you reference a section of a page with for instance<a href="#tips">Visit the Useful Tips Section</a> Would there be a way to do a similar thing in django if for instance I wanted to load my page straight to the tips section? I am extending base.html...

Best way to sign-up django project

django,django-models,django-views
I am working on a project about a workshop where you could sign up for it. When you sign up for an project, and you click on the project to go to the detailview you wil see a list of all the people that are currently signed up for that...

Like matching query does not exist - Django

python,django,django-models,django-views,django-queryset
I have created a like button that adds a user to a query when they like the photo, and removes them if they unlike the photo. The back-end works great! The front-end, not so much. I get the following error when I try to load the page: Like matching query...

Django update user is_active to True in a view

django,django-views
I have a django view as follows: @staff_member_required def approve(request, pk): prnt = Parent.objects.get(id=pk) prnt.request_status = 'A' prnt.user.is_active = True prnt.save() The view updates every field except the is_active field. Here User has OneToOne relationship with the Parent model. Where is the issue? the console doesn't throw any errors either....

django CreateView demands pk

django,django-views
this is my CreateView: class LampCreateView(CreateView): model = Lamp template_name = 'shotmaker/test_cam.html' success_url = '/shotmaker/' and its url: url(r'^camera/create/$', views.LampCreateView.as_view(), name='lamp_create'), when I try to open the URL I get this: ValueError at /shotmaker/camera/create/ invalid literal for int() with base 10: 'create' when I pass pk into the url: url(r'^camera/create/(?P<pk>[-\w]+)$',...

Call a method as a field of ValuesQuerySet

django,django-models,django-views
I have a model and a method on it as follows: class Results(models.Model): t_id = models.TextField(blank=True) s_result_id = models.TextField(blank=True,primary_key=True) s_name = models.TextField(blank=True) s_score = models.FloatField(blank=True, null=True) ... (some other fields with huge data) def get_s_score(self): return 100 * self.s_score On a view, I am trying to call get_s_score method from...

reverse url of the blog article in template

django,django-templates,django-views,django-urls
{% url 'article' article.get_absolute_url %} wont' work as expected. Got error NoReverseMatch at /blog/ Url pattern is: url(r'^/(?P<slug>[-\w]+)-(?P<id>[-\d]+)/$', article, name='article'), where article is the function name....

Getting value of a ForeignKey instead ID

django,django-views
I have to pass a ForeignKey object in a json response, im doing it like this: data = {} p = Bets.objects.create( bet_id=request.POST['team'],number=number) data['success'] = p return HttpResponse(json.dumps(data), content_type='application/json') bet_id field is a ForeignKey and number is a CharField, if in data['success'] I pass p.number i can pass it with...

Django does not render my forms' fields

django,django-models,django-forms,django-templates,django-views
I have this model in models.py: class Life_events(models.Model): patient = models.ForeignKey(Demographic) HSCT_date = models.DateField('HSCT date',null=True,blank=True) HSCT_outcome = models.CharField('HSCT outcome',max_length=100, null=True, blank=True) partaker_in_clinical_trial= models.CharField('Partaker in clinical trial',max_length=200, null=True, blank=True) date_of_input= models.DateField(null=True,blank=True) def __str__(self): return str(self.patient) My forms.py contains: class LifeEventsForm(forms.Form): def __init__(self,...

Reverse for 'jobpost_detail' with arguments '()' and keyword arguments '{'slug': u'67itut'}' not found. 0 pattern(s) tried: []

python,django,django-models,django-views,mezzanine
I use django 1.7, python 2.7 I installed the search module vacancies vacancy created but maintaining job in the admin panel , there is an error . NoReverseMatch at / ru / admin / careers / jobpost / Reverse for 'jobpost_detail' with arguments' () 'and keyword arguments' {' slug ':...

Join in Django views

python,mysql,django,join,django-views
I have 2 Models in my django app. The corresponding tables for the two models are: Table 1: +-------------+---------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-------------+---------+------+-----+---------+----------------+ | id | int(11) | NO | PRI | NULL | auto_increment | | post_id | int(11)...

Django - View Other user profile

django,python-3.x,django-models,django-templates,django-views
I am using Django 1.6 to create a web app.. I have users and user profiles and have designed templates to display the profile information of the user. class UserProfile(models.Model): class Meta: app_label = 'xyz' user = models.OneToOneField(User, related_name='user_profile') description = models.CharField(max_length=200) ... other fields ... I have various edit...

Ajax button initiates every button, not just the one selected

javascript,jquery,ajax,django,django-views
I would like to create an ajax button that once clicked, the item becomes "purchased" by the user. Once the item becomes purchased, the button's text will be updated. The function works, however it is as if I clicked every button, not just one. For example, I have two items...

Render in django can't passing an argument

django,django-forms,django-templates,django-views
i'm new in django and i'm trying to create an application that user can change his/her password based on his/her id. So far is good, but when i'm trying to passing an argument from my views.py, there is a trouble that an argument can't passing to the html template. This...

Django doesn't parse a custom http accept header

python,django,http,django-views,django-rest-framework
Is there any way to allow Django app to accept the custom accept header like "application/vdn.name.v1+json"? I keep getting a response like this Could not satisfy the request Accept header. I am using Django Rest Framework as well...

How should I show results of BeautifulSoup parsing in Django?

python,django,django-templates,django-views,beautifulsoup
I'm trying to scrape a web page using BeautifulSoup and Django. Here's my views.py which do this task: def detail(request, article_id): article = get_object_or_404(Article, pk=article_id) html = urllib2.urlopen("...url...") soup = BeautifulSoup(html) title = soup.title return render(request, 'detail.html', {'article': article, 'title':title}) But when I use {{ title }} in django template...

different nltk results in django and at command line

python,django,django-views,nltk
I have a django 1.8 view that looks like this: def sourcedoc_parse(request, sourcedoc_id): sourcedoc = Sourcedoc.objects.get(pk=sourcedoc_id) nltk.data.path.append('/root/nltk_data') new_words = [] english_vocab = set(w.lower() for w in nltk.corpus.gutenberg.words()) #<---the line where the error occurs results = {} template = 'sourcedoc_parse.html' params = {'sourcedoc': sourcedoc,'results': results, 'new_words': new_words, 'BASE_URL': BASE_URL} return render_to_response(template,...

Django: form to query database

django,django-forms,django-templates,django-views,django-queryset
I want a user be able to make this query: Tell me all the people, without Phd, with full time contract with a contract among two dates. that translated into Django is: Contract.objects.filter( person__is_doctor = False, type_contract = 'full', starting_date__gte = start_date, ending_date__lte = end_date ) How could I make...

Dynamic url routing in django

django,django-views,url-routing
I have a RoutingUrl model which describes all the urls used on my site with the view (foreign key to the View model) that has to manage the url and some other routing information. The urls are continuously growing in size, and should also support the redirect. The models are...

Named groups in Django based off model field?

regex,django,django-models,django-views
I was trying to replicate a url regex equivalent to: url(r'^members/(?P<username>\w+)/$', 'profiles.views.single'), While I understand I am taking the users that exist within my database from: from django.contrib.auth.models import User I am wondering if I can change this to something a little more unique. I've been reading the documentation from:...

Filtering is not happening in the next page

python-2.7,django-views,django-filter,django-pagination
I have added pagination in my view. The pagination is working fine but when I am filtering my data and navigate to the next page it is not paginating through the filtered data, it goes to the actual next where filtering is not happened, here is my views and template...

Django Noob URL to from Root Page to sub Page

django,django-views
I've been struggling with this for a few hours can cant get it to work. I'm trying to learn python and django. I have a Django project where I want to use an app for all the sites web pages. My project looks like this: project src project urls.py views.py...

DjangoRestFramework - registering a user: difference between UserSerializer.save() and User.objects.create_user()?

django,django-views,django-rest-framework,user-registration
Suppose I want to register a user (I'm using the User model located in django.contrib.auth.models). Assume this is my serializers.py: class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('username', 'password', 'email', ) What's the difference between the following views, and which one is recommended when it comes to creating...

Divide option in django model query

python,django,django-models,django-views
This is my model: class DailyObj(models.Model): RedDate = models.DateField('RecDate') Name= models.CharField(Name,max_length=100,default=None) Total_Rec = models.DecimalField('Total Rec',max_digits=18,decimal_places=2,default=None) top10records = DailyObj.objects.filter(RedDate__gte = fromdate,RedDate__lte = todate,Total_Rec__gt=0).order_by('-Total_Rec')[:10] Here fromdate and todate are variables having proper date values. The above query works fine and returns the records which satisfy the given criteria. However I want each...

Cannot assign “u'2'”: “CartItem.product” must be a “Product” instance

django,django-models,django-forms,django-views
I'm trying to allow the customer to add an item (CartItem) to their cart. The CartItem is linked to my Products model via ForeignKey. I've created a list of products through the admin. I'm able to get the form (AddItemForm) to populate on the .html page and show the list...

How to have 2 Models/Views/Templates on one Page in Django?

python,django,django-models,django-templates,django-views
I know this has probably been asked a 1000 times but I still for the life of me can't find a decent answer. Reading tutorials, Stack and even looking at GitHub for examples - nothing is helping or even guiding me in the right direction. I have 2 separate Models/Views/Templates...

update / edit function in django one-to-one models

python,django,django-models,django-forms,django-views
i've made an edit form in django, and i have trouble in my update function. There is a relational models that using one-to-one relationship. When i run this function, data in User models stored properly, but not in the UserProfile models. This is my urls.py url(r'^update_user/(?P<pk>\d+)$', views.update_user, name='update_user'), This is...

Django views can't open .csv file by using pandas [IOError]

python,django,file-io,pandas,django-views
I got IOError when I open .csv file in views.py, it says I don't have the file in the directory, here is my directory: /survat #theproject /survatapp #theapp /modules __init__.py survat_core.py __init__.py views.py forms.py models.py prostate1.csv __init__.py settings.py urls.py wsgi.py /database sqlite.db /media /static /bootstrap Here is the traceback Environment:...

objects.all() query not working

python,django,django-templates,django-views
I am trying to make a form for user creation through django. The user(henceforth developer) can choose from a list of supervisors to get himself registered. Problem is, I am not getting the list of all the supervisors from the query. When I use objects.get(), I receive an error that...

Django insert into list if doesn't contain it

python,django,django-views
I want to insert into the notifications list, one notification of each type. and I have this: Result from the initial query (I guess is a list with queryset), named notifications: [<Notification: Should be first>, <Notification: New link>] And the restriction that I have is: for(note in notification): if len(note.region.all())...

How to submit POST request to '“current_url”/submit' in HTML's form action using Django templates?

django,django-templates,django-views,html-form
Let's say I have many posts and each post has a url example.com/post_id. Also there is a HTML form after this post where one can submit comment. If I had to submit this comment to this url: example.com/submit , then I could just do <form action="submit/" method="post">. But, I want...

required authentication in forms

django,django-forms,django-views,django-authentication
I have an issue with the authentication in some templates. In template where I pass form based in models I can only access if I am logged, but in template with forms non-based in models I can access without being logged Form non-model based: class ProvSearchForm(forms.Form): proveedor = forms.ModelChoiceField(queryset=Proveedor.objects.all(),required=True) mes...

Add m2m link in view

django,django-views
I have model: class Project(models.Model): name = models.CharField('Name of project', max_length=100, null=False) users = models.ManyToManyField(settings.AUTH_USER_MODEL) Now I want to add current user in users in CreateView. Like this: class ProjectCreate(CreateView): model = Project fields = ['name'] template_name = 'project_form.html' success_url = reverse_lazy('project_list') def form_valid(self, form): self.model.users = self.request.user return super(ProjectCreate,...

Combining multiple django apps into one view, what am I doing wrong?

python,django,django-templates,django-views
I have a Django project with multiple apps that I need to combine and render as a single page. I have the following sections of code: One of the views I'm trying to aggregate with other views: class ResourceList(generic.View): model = Submissions template_name = 'url_list.html' def get(self, request, *args, **kwargs):...

Trying to translate fields of my classes (Django internationalization Cap)

python,django,django-models,internationalization,django-views
Today i am translating my training project, yesterday i was reading The Django book (Cap: Internationalization) and i have achieved translate my templates completely. Now I have a new issue. I have some dynamic content that i wanna translate, but i don't know how proceed beyond add the pseudonym of...

Access image urls from Django ForeignKey relationship

django,image,django-models,django-templates,django-views
I currently have a model defined the same way as this one: class Object(models.Model): name = models.CharField(max_length=50) class ObjectImage(models.Model): object = models.ForeignKey('Object', related_name='images') image = models.ImageField(upload_to='./objects') I am trying to access the urls of all the images for each object so that they can be displayed in a template. I...

Using reverse relations in django class based views

django,twitter-bootstrap,django-views,django-class-based-views
Django newbie here so please bare with me!! :) I have a django model as follows: class Category(models.Model): category_name = models.CharField(max_length=250, blank=True, null=True) class Meta: verbose_name = "Category" verbose_name_plural = "Categories" def __unicode__(self): return self.category_name class Product(models.Model): category = models.ForeignKey(Category) model_name = models.CharField(max_length=255, blank=True, null=True) class Meta: verbose_name = "Product"...

Django 'dict' object has no attribute 'getlist'

django,django-views
Inspired by this blog post, I am trying to make a views that handles profiles searches by saving the search parameters into session so that the query can be preserved through pagination. Here is the views: def profile_search(request): args = {} qs=[] if not request.method == 'POST': if 'search-profiles-post' in...

DateField — “enter a valid date” message

django,django-forms,django-views
I'm a bit confused as why it keeps returning the 'enter a valid date' message. Is it my formatting? I've tried different combinations of %m-%d-%Y, but still no luck. models.py class DeliveryDate(models.Model): cart = models.ForeignKey('Cart', null=True, blank=True) date = models.DateField() def __str__(self): return str(self.cart.id) return self.date views.py def add_delivery_date(request): the_id...

Django, context dict not passing through to template? (for loop returns nothing)

django,django-templates,django-views
I did a search for this but couldn't find anything, so here it is.. My views are set up like this, the status.html for loop works fine but the tasks.html doesn't register my for loop at all, and I don't see what I'm doing wrong when comparing the 2 view...

Search Django Objects order_by(child_model_field)

django,django-models,django-admin,django-views
I have two models in my Django application. The first one is Journey and Second is Schedule. The Schedule models has a foreign key of Journey model. the schema of these models is as follow. class Journey(models.Model): pass class Schedule(models.Model): journey=models.ForeignKey(Journey) day=models.CharField(max_lenth=3, choices=days) start_time=models.TimeField() def __unicode__(self): return self.day What I...

Load common content for the whole Django site

django,django-views
I want to load a list notifications for almost all the web application I am building. Should I do in every view function or View Class?

Is it possible to process arbitrary content with the Django template processor?

python,django,django-templates,django-views
My web app contains a banner serving API. Abridged banner model: class Banner(models.Model): name = models.CharField(max_length=50) ad_tag = models.TextField() active = models.BooleanField(default=True) priority = models.IntegerField(null=True, blank=False) def __unicode__(self): return self.name The banner serving API accepts some GET parameters and, based on these parameters, returns a Django template that spits out...

Problems with rendering page on Django framework

python,django,django-templates,django-views
I have categories of the news and news and i don't know how to render the page with the list of news that belong to the same category. Hope You will help me with that. this is my model.py file: from django.db import models class Category(models.Model): class Meta: verbose_name_plural =...

Value Error when render used (django 1.7.1)

django,django-views
I've an error Traceback: File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response 111. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/user/accounter/apps/accounter/views.py" in unit_view 24. return render(request, 'accounter/unit.html', context) File "/usr/local/lib/python2.7/dist-packages/django/shortcuts.py" in render 48. return HttpResponse(loader.render_to_string(*args, **kwargs), File "/usr/local/lib/python2.7/dist-packages/django/template/loader.py" in...

Pass formset as an argument to a function in Django

django,django-forms,django-views
I want to pass a formset as an argument to a function and want to validate the formset. If the question is not correct somebody please correct the question. This is my function: def valid_check(*args): valid = True for arg in args: if not arg.is_valid(): valid = False return valid...

objects.all() queryset not working with view to template; many-to-one relationship

django,django-templates,django-views
I am trying to make this template call a function that has worked in the past with a many-to-many relationship. This time it is a many-to-one. the detail.html template {{ icecreamflavor.name.all }} The view: from django.shortcuts import get_object_or_404, render from django.views import generic from .models import IceCream, IceCreamFlavor # Create...

Delegate from different Django app

django,python-3.x,django-views
Say I have two Django apps, abc and xyz. The abc app is a package that should be installed using pip3, and xyz is some custom app using features from abc. How can xyz provide a delegate method to be used in a view in abc? Say abc need to...

Creating multiple model instances in DRF3

django,django-models,django-views,django-rest-framework
1) I would like to create multiple model instances with one API call, like asked here: How do I create multiple model instances with Django Rest Framework? I tried the solution named in the link, with no success. I am trying to upload multiple files in one API call. Result:...

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

accessing list or dictionary values for use in view function

django,django-views
Let's say I used a loop to generate either a list or dictionary of variables: a = {} b = [] k = 1 count = TaskBox.objects.all().count() output = "" while k <= count: ck = str(k) newline = output.join("box"+ck+" = InboxEntry.objects.filter(box="+ck+")") c.append(newline) b['box'+ck] = "InboxEntry.objects.filter(box="+ck+")" k += 1 yielding:...

How to implement Post/Redirect/Get in django pagination?

django,django-templates,django-views
I have a view that filters out results for a posted search form: def profile_advanced_search(request): args = {} if request.method == "POST": form = AdvancedSearchForm(request.POST) qs=[] if form.is_valid(): cd = form.cleaned_data s_country=cd['country'] s_province=cd['province'] s_city = cd['city'] if s_country: qs.append(Q(country__icontains = s_country)) if s_province: qs.append( Q(province__icontains=s_province)) if s_city: qs.append( Q(city__icontains=s_city)) f...

How to deal with optional GET argument?

python,django,django-models,django-views
I have a GET request that sometimes has pk argument and sometimes hasn't. I want to have 1 view that deals with it, but my attempts to write it are not successful. Here is what I have: @ajax @login_required def search_dist(request): try: pk = request.GET.get('pk') except Exception: dist_list = request.user.distributors.all()...

django views List to Detail search parameter

django,django-views
I have 2 models: Ovt which is documents header data only (ovtnumber = mycommonfield) Ovr which is all rows that refer to Ovt with field that isn't a pk ( refer only one Ovt by the mycommonfield). I need to to access the list of rows in Ovr that refers...

Python: “is not None” not working as expected

python,django,python-2.7,django-views
In a multi-page survey application I am creating I have a jQuery UI slider bar which is used to provide a rating for an image. This returns a numerical value to my Python/Django view which is stored in a list slider_DV_values On a later Data Verification survey page the participant...

Convert argument to string [closed]

python,django,django-views
Never work with Struct before. When hire a developer for some work, he used this, but it doesn't work. And developer doesn't answer... Please, can someone help with the problem? From views.py, that you can see below, I got error Struct() argument 1 must be string, not unicode in 'InvId':...

How do I loop through a nested context dictionary in Django when I have no idea the structure I will recieve

django,django-templates,django-views
I have a dictionary I am passing to a template that looks something like this: {'leasee': {'respond': {'hour': True, 'day': True}, 'contact': {'phone': True, 'facebook': True, 'email': True, 'other': True, 'text': True}, 'licence': '987654321', 'help': {'beautySupplyProvider': True, 'photographer': True}, 'phoneNumber': '12345678910', 'name': 'Chris', 'certifications': {'yes': True, 'long': 'All of them'},...

django can't find views…page not found error

python,django,django-views,django-urls
I am trying to print a response from the view.. but django shows the page not found error(404) My main project.urls are:- from django.conf.urls import patterns, include, url from django.contrib import admin from django.conf import settings from . import views urlpatterns = patterns('', # Examples: # url(r'^$', 'ultimatefinalblog.views.home', name='home'), #...

Updating model objects in the database on Django

django,django-models,django-views
I am new to Django and for learning purposes I am trying to build my own site using the linkedn API to display my profile. The following is a a example of my code. To see the whole lot: https://github.com/javiee/django-site models.py class Profile(models.Model): user = models.ForeignKey(User) first_name = models.CharField(max_length=20) last_name...

How to tell a Django view who called it?

django,django-templates,django-views
I have two Django views that render two separate templates. Each of these templates will contain a link to the same third view. That third view will render a template that should display one button if the first Django view/template link redirected to it but render a different button if...

Generating html pages off Django database entries

django,django-templates,django-views
I am trying to get a url mapping to follow this example /user/user-name/list/list-name-goes-here I created this regex (unsure if it's correct) url(r'^user/(\w+)/list/(?P<listname>\w+)/$', mylistpage, name='lists'), So users currently have the ability to insert a series of lists and they print onto their main profile page. I want them to click on...

How to encrypt plain text to md5 / sha1 in django?

python,django,django-views
i want to create an application that admin can make user with a new messages that encrypted into database. I have the core function and all can work properly. But, i still can't encrypt the message from text to md5/sha1. I have read and try this and this. But, i...

How to calculate percentage with facility in Django 1.7

django,templates,django-views
How to calculate percentage in Django 1.7? I need return [{'gender': 'F', 'perc': 55.0%}, {'gender': 'M', 'perc': 45.0%}] In this case, i try from myproject.core.models import Person from django.db.models import Count g = Person.objects.values('gender').annotate(perc=Count('gender')).order_by('gender').values('gender', 'perc') total_itens = Person.objects.count() But not result, and i try gender_m = Person.objects.filter(gender='M').count() gender_f = Person.objects.filter(gender='F').count()...

Why when i logout in django after i updated my data appears this error?

python,django,django-views
i'm new in django and i'm trying to create an application that Admin have CRUD function. My problem is when admin updated other user, and then logged off, log off function worked properly. But, when admin updated him/her self then admin logout, appears this error KeyError at /simofa/logout/ 'username' Request...

Substract one integer from another and save

django,django-views
I need to substract one integer form another and save the result. Its some kind of payment method. Never do that before, so the code below - its what I'm trying to do in my view: def checkoutstatus(request, article_id): if request.POST: article = Article.objects.filter(id=article_id) article.article_users.add(request.user) balance = int(UserProfile.objects.filter(balance=user_balance)) cost =...

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

What is the best practice for storing UI messaging strings in Python/Django?

python,django,django-views
I'm wondering what the "best practice" is for storing medium length strings to be used in a UI in Python/Django. Example: I have an error.html template that takes an error_description field. This is a few sentences explaining to the user what went wrong, and what they might do to address...

Why won't HttpResponseRedirect update the URL?

django,django-views,django-urls
I want an optional slug in my applications's URLs, like how Stack Overflows does its URLs: http://stackoverflow.com/questions/<question_id>/<question_slug>, where <question_slug> is optional. That is, if you go to http://stackoverflow.com/questions/<question_id>, you'll be redirected to http://stackoverflow.com/questions/<question_id>/<question_slug> My urls.py: url(r'^myapp/(?P<thing_id>\d+)/edit_thing/$', views.edit_thing, name='edit-thing'),...

Django Rest Framework - how to get Http header information in urls.py

python,django,django-views,django-rest-framework,django-urls
I am making a Django-based API and here is my urls.py. from django.conf.urls import include, url api_version = "v1" urlpatterns = [ url(r'^v1/', include( "api."+ api_version +".urls", namespace=api_version )), ] What I want to do is to retrieve API version from http accept header. I tried to use django.http.HttpRequest module,...

Error saving all valid forms from a formset in django

python,django,django-forms,django-views
I have a formset but I can only save the last form: my view: @login_required(login_url='/login/') def CCView(request): newAdFormSet = formset_factory(CodigoCortoForm) if request.method == 'POST': formset = newAdFormSet(request.POST, request.FILES) if formset.is_valid(): for form in formset.forms: if form.is_valid(): form.save() return HttpResponseRedirect('/home/') else: formset = newAdFormSet() return render_to_response("codcorto.html", {'form':formset}, context_instance=RequestContext(request)) Th view only...

How should I handle different failure scenarios during Django authenticate()?

python,django,authentication,django-views
I'm writing a custom authentication backend in Django 1.7 and it could fail for one of two reasons: invalid credentials or some kind of internal error, e.g. a database issue. Depending on the failure, I want to provide a different error message to the user. IE "Username or password is...

Do something once in django

django,django-views
I want to create two groups once per project's life. So, I read about AppConfig And I created core.appconfig.py: from django.apps import AppConfig from django.contrib.auth.models import Group class RolesConfig(AppConfig): name = 'roles_config' verbose_name = 'Roles configuration' def create_roles(self): driver = Group.objects.create(name='driver') manager = Group.objects.create(name='manager') driver.save() manager.save() And the in settings.py:...

Django-changes made to admin are not reflected in the template without restarting the server

python,django,django-templates,django-views
The changes I'm making to the database from my admin interface are not reflected unless I restart the server. Here's my models.py file- class InventoryManager(models.Manager): def getActiveId(self): return self.filter(currentlyActive=True) .... .... class Inventory(models.Model): .... .... .... name = models.CharField(_("item name"),max_length=30) category = models.CharField(_("breakfast/lunch/dinner"), max_length=2,choices=TIME_OF_SERVICE, default="lunch") foodType = models.CharField(_("veg/non-veg"), max_length=7,choices=TYPE_OF_FOOD,...

Correct

django,django-forms,django-templates,django-views
I have been having some trouble getting a Django SessionWizardView to submit data to my database and I am trying to isolate the issue. I note from the Form documentation As well as its elements, a form must specify two things: where: the URL to which the data corresponding to...

how to post a new comment through a method in django?

python,django,django-views,django-comments
I am using 'django_comments' for commenting in my site. Now i want to post a new comment via a method in my 'views.py'. I searched and only found posting comments using {{ forms }} in templates. So how can i post a new comment through a method. Please help me.....

Auto close a file opened in django __init__.py

python,django,csv,django-views
I am creating a simple web application to search india pin codes (contained in a single csv file 'all_india_pin_code.csv'). This file is opened in __init__.py of my django app as below: cf = open('all_india_pin_code.csv') and this file handler is used in the app's views.py method like this: cf.seek(0) re =...

How to save the value of a jQuery sliderbar into a Person model?

jquery,django,django-models,django-forms,django-views
I am trying to save the value of an jQuery element I added to my SurveyWizardForm into my class Person(models.Model): and therefore my database. All of the other elements in my form were created the normal way, by creating the necessary fields and widgets in my forms.py and the data...

Why I get MultiValueDictKeyError in django?

django,django-views
I have an Article app that used to worked fine before I added an image field headimage to it. Here is the model: class Article(models.Model): nid = models.IntegerField(default=0) headimage = ImageWithThumbsField(upload_to='images', blank=True, sizes=((200,200),(400,400)) title = models.CharField(max_length=100) author = models.CharField(max_length=100, blank=True) translator = models.CharField(max_length=100, blank=True) body = models.TextField() teaser = models.TextField('teaser',...

Django urls.py not rendering correct template

python,django,templates,django-views,django-urls
This is my urls.py """s7h URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.8/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home...

Where did Django form wizard go in django 1.8?

django,django-forms,django-views
There is a documentation about form wizard for version 1.7 but not for 1.8. I have looked at release notes and there is no mention of this. So where did it go? (Also there seems to be no class named SessionWizardView anywhere in 1.8).

Django: reverse(view_function) does raises NoReverseMatch

django,url,django-views
Reversing by view-name works, and reversing by view-method, too. But if the URLs use a prefix reversing by view-method does not work. At least in my case. Old code url=reverse('myapp:foo-view') New code. Both versions don't work url=reverse(foo_view) url=reverse(foo_view, prefix='myapp') Again, reversing by view-method works perfectly if the URLs have no...

How to create Django form for a photo grid?

python,django,django-forms,django-templates,django-views
I'm trying to create a Django form that will contain a grid of one to ten photos. There will be two radio button groups below each photo, one to indicate if the viewer approves or rejects that photo and a second group to indicate if the photo needs to be...

auto relate a foreign Key Field to a pk object django

django,forms,django-views
I have two models: class Post(models.Model): title = models.CharField(max_length=200) class Addimg(models.Model): post = models.ForeignKey('Post') image = models.ImageField(upload_to='%Y/%m/%d') Now I have a view for Addimg model to append Images to a Post: def addimg(request): if request.method == "POST": form = AddimgForm(request.POST, request.FILES) if form.is_valid(): addimg = form.save(commit=False) addimg.image = request.FILES['image'] addimg.save()...

Add extra field to the formset while saving the formset

django,django-models,django-forms,django-views
I want to know the alternate method to save data to the database that are not coming from the html form. This is my models.py: class product(models.Model): user = models.ForeignKey("user") product = models.CharField(max_length=128) cost = models.IntegerField() This is my forms.py: class productform(forms.ModelForm): class Meta: model = product fields = ["product","cost"]...

Single Address Linked to Multiple Users Even when Using OneToOneField(User)

django,django-views
So the problem I'm having is that when I add an address for a user, that address is being linked to all other users as well. I can see this also in my admin interface. And then even if I login as one user, edit the address, the address for...

Stumped by model manager's errant behavior when summing up/down votes and displaying an ordered list

python,django,python-2.7,django-views
This one might be tricky. I have a basic web app where users post interesting URLs, and upvote/downvote the best/worst ones. I'm using Python 2.7, Django 1.5. Problem statement is in bold at the end. In models.py, I have the following lines (take special note of lines marked with x):...

Django many-to many filter field

python,mysql,django,django-views,many-to-many
I want to add into the list if the region, contains that country, its a relation of M2M between the Region and Country models. i cant get to the attribute of the country code it says that "colon expected". what is missed in the if condition? views.py notification = Notification.objects.filter(**condition)....

Passing checkboxes values to view in django

django,checkbox,django-templates,django-views
I have a table with some database data <table id="id_list_table" class="table table-condensed"> <caption>Inputs list</caption> <thead> <tr> <th>#</th> <th id="input">Input</th> </tr> </thead> <tbody id="fbody"> {%for input in InputsAll%} <tr> <td>{{ input.input }}</td> <td> <a class="btn btn-primary btn-xs" href="{% url 'edit' %}?input_num={{input.id}}" id="edit">edit</a> <a class="btn btn-danger btn-xs" href="{% url 'delete'...

ManagementForm Data is Missing When Using Formset Prefix

python,django,django-forms,django-views,formset
Anyone know why this raise a ManagementForm Data is Missing when I use Formset Prefix? From Shell >>> from django import forms >>> from django.forms.formsets import formset_factory >>> >>> class CheckBox (forms.Form): ... overwrite = forms.BooleanField (required = False) ... >>> >>> data = { ... 'form-TOTAL_FORMS': '2', ... 'form-INITIAL_FORMS':...

Error saving records from ModelChoice Field in django form

django,django-forms,django-views,django-widget
I have a FormModel with an modelchoice field. The modelchoice widget is filtered based on the logged user class ProcFTPForm(forms.ModelForm): #id_archivo = forms.ModelMultipleChoiceField(queryset=Archivo_Descarga.objects.all(),required=True,widget=FilteredSelectMultiple("Archivo",is_stacked=False),label='') class Media: css = {'all':('/admin/css/widgets.css',),} js = ('/admin/jsi18n/','admin/jquery.js') def __init__(self,usuario, *args, **kwargs): super(ProcFTPForm, self).__init__(*args, **kwargs) self.fields['id_archivo'] =...

I want to create multiple context object in django views

html,django,python-2.7,django-views
def claim(request): entries = Child_Info.objects.all() ctx = { 'entries' : entries } return render_to_response('myapp/claim.html', ctx) How to pass more than one context here?...

authentication in django with extending one-to-one relationship

django,django-forms,django-views,django-authentication,django-login
i've made authentication system that user can login based on User Models. In User Models, it's extended with one-to-one relationship. When i insert login with username and password, it works. But when i insert login with username, password, and hak_akses. It doesn't work properly. I want authentication can work with...

Django: set_password isn't hashing passwords?

python,django,hash,django-forms,django-views
I've made a custom User registration form/view in Django so that I can include an additional user attributes through a different model. I've used set_password to set the password of the newly created user to the password entered in the form, but I've found that the passwords that are saved...

Listen for and receive payload from github webhook in Python/Django

django,post,github,django-views,csrf
My problem is very much like the one here: How do I receive Github Webhooks in Python The difference is, I am sure about my framework, that being Django. I have been able to register webhook for a particular repository, and did port forwarded using ngrok. The Payload delivered gets...

Where to check for 403 in a Django CBV?

django,django-views,django-class-based-views
I am making a basic app to teach beginners. Each user can write notes, but I want to make it so that a user cannot view or update a different user's notes. I have the following view, but I had to repeat myself. from django.core.exceptions import PermissionDenied ... class NoteUpdate(LoginRequiredMixin,...

django override model save() method

django,django-models,django-forms,django-views
I want to get request as a parameter in save() method. models.py class Profile(models.Model): uuid = UUIDField(auto=True) user = models.ForeignKey(User) name = models.CharField(max_length=128) dob = models.DateField() class Meta: db_table = 'profile' def save(self,*args,**kwargs): if not self.pk: self.user_id = 2 #here i need request.user instead of 2 super(Profile,self).save(*args,**kwargs) forms.py class ProfileForm(forms.ModelForm):...