ok just braught it to work with only django: views.py def addimg(request, pk): post = get_object_or_404(Post, pk=pk) if request.method == "POST": form = AddimgForm(request.POST, request.FILES, initial={'post':post}) if form.is_valid(): addimg = form.save(commit=False) addimg.image = request.FILES['image'] addimg.save() return redirect('blog.views.list') else: form = AddimgForm(initial={'post':post}) return render(request, 'blog/appendimg.html', {'form': form }) forms.py class AddimgForm(forms.ModelForm):...
django,django-templates,django-views
You can have a part of the URL to be used as a parameters. Each parameter will be set based on the regex provided. an example here. One view can handle all your urls that contain the three parameters you mentioned. url(r'^members/near/(?P<from_uid>\d+)/profile/(?P<to_uid>\d+)/from//(?P<view_name>\W+)/$', MyView.as_view(), name = 'my_named_view') Then in your view...
You need to add an additional URL pattern: urls = [ url(r'^page2/$', views.page2, name='page2'), url(r'^$', views.index, name='home_page'), ] or alternatively, pass a parameter you can use to identify the page to be rendered to the view. Currently, you aren't mapping a URL to the function you want to call when...
django,django-templates,django-views,django-urls,django-template-filters
You can just add the fragment identifier right after the URL returned by the {% url %} template tag: <a href="{% url 'home' %}#tips">home</a> ...
python,django,django-models,django-views
pk = request.GET.get('pk') does not raise an exception. It gives you None instead, if pk isn't in GET. So your first case never executes. Try with: @ajax @login_required def search_dist(request): pk = request.GET.get('pk', None) if pk is None: dist_list = request.user.distributors.all() starts_with = request.GET.get('query') if starts_with: dist_list = request.user.distributors.filter( surname__istartswith=starts_with)...
python,django,django-models,django-views,mezzanine
You forgot to add the app's url.py to the root urls. Include the careers.urls like this: urlpatterns += patterns('', ... url("^$", direct_to_template, {"template": "index.html"}, name="home"), ... ("^careers/", include("careers.urls")), ... ("^", include("mezzanine.urls")), ... ) ...
regex,django,django-models,django-views
Try to replace unique_id in your function with unique_code def single(request, unique_code): try: uid = get_object_or_404(Address, unique_code=unique_code) final = uid except: raise Http404 return render_to_response('single_user.html', locals(), context_instance=RequestContext(request)) ...
django,django-forms,django-views
The wizard is part of the formtools package which has been split off into a separate repository. New project: https://github.com/django/django-formtools/ More info: https://docs.djangoproject.com/en/1.8/releases/1.8/#removal-of-django-contrib-formtools...
python,mysql,django,join,django-views
Try this: Model2.objects.filter(pk__in=Model1.objcts.values_list('post_id', flat=True)).values('p_slug'). I hope it helps.
django,django-models,django-forms,django-views
The issue lies at that line: cart_item = CartItem.objects.create(cart=cart, product=product) The create method expects product to be a Product instance, you are passing a string (u'2'). Use product_id instead of product: product_id = int(request.POST['product']) cart_item = CartItem.objects.create(cart=cart, product_id=product_id) This solves the code as it is but you should use the...
python,django,authentication,django-views
I ended up using try/except blocks in my View with custom errors that represent the relevant failure.
django,image,django-models,django-templates,django-views
You only need to provide Object to your template to access ObjectImages. They will be available this way: all_objects = Object.objects.all() context = {'all_objects': all_objects} render(render, your_template.html, context) And in your template, like this: {% for each_object in all_objects %} {% for each_image in each_object.objectimage_set.all %} {{ each_image.image }} {%...
python,django,django-templates,django-views
I had success with the following snippet by GitHub user mhulse. This allowed me to call {% allow_tags ad_tag %} in my template and process any Django template tags found in that field. from django import template from django.utils.safestring import mark_safe register = template.Library() # http://www.soyoucode.com/2011/set-variable-django-template # http://djangosnippets.org/snippets/861/ # http://stackoverflow.com/questions/4183252/what-django-resolve-variable-do-template-variable...
django,django-models,django-views
The best way is to first try the example in the documentation. If you do not have the patience to read through the documentation, here is an example of something you can try....
django,django-forms,django-views
First in your Django ModelForm let's change the date model field's widget without adding an extra field. This is done in the __ init __ method : from django.forms.extras.widgets import SelectDateWidget class DeliveryDateForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(DeliveryDateForm, self).__init__(*args, **kwargs) #Change date field's widget here self.fields['date'].widget = SelectDateWidget() class Meta:...
python,django,http,django-views,django-rest-framework
Try defining a custom renderer and setting the media_type attribute. from rest_framework.renderers import JSONRenderer class MyRenderer(JSONRenderer): media_type = 'application/vdn.name.v1+json' Then enable your renderer (see the docs for more info) REST_FRAMEWORK = { 'DEFAULT_RENDERER_CLASSES': ( 'path.to.MyRenderer', 'rest_framework.renderers.JSONRenderer', 'rest_framework.renderers.BrowsableAPIRenderer', ) } ...
django,django-models,django-views
Use the update_or_create() method: Education.objects.update_or_create( school_name=value['schoolName'], user = request.user, defaults={'field_study': value['fieldOfStudy'], 'degree': value['degree'], 'start_date': value['startDate']['year'] , 'end_date': value['endDate']['year']}) ...
python,django,django-forms,django-views,formset
The problem is in method cars rendering to a response.html page and displaying the rendered form at url http://..../vehicle/cars instead of vehicle/trucks. The "Management Form Error" was raised because "POST" happened the second times while still at url vehicle/cars form and not in vehicle/trucks form. Updated 5 hinted the problem....
django,django-forms,django-views,django-authentication,django-login
If you are using django's authentication function (i.e. from django.contrib.auth import authenticate), then you should check how authentication function has been implemented. check here from django's source code. Here in line 72: .... try: user = backend.authenticate(**credentials) except PermissionDenied: .... and backend.authenticate is implemented like this: def authenticate(self, username=None, password=None,...
No, you should not, Django provides several mechanisms to take care of that kind of issues. Context processors are functions that are called each time a template is rendered and which output populates that template's context. They allow you to have the same variables available everywhere in your templates. Custom...
django,python-3.x,django-views
Signals can help you achieve what you're looking for. From Django's documentation on the subject: Django includes a “signal dispatcher” which helps allow decoupled applications get notified when actions occur elsewhere in the framework. In a nutshell, signals allow certain senders to notify a set of receivers that some action...
You just need to override method get_context_data. And your first trial was almost there. class MyView(TemplateView): template_name = 'template.html' def get_context_data(self, **kwargs): genders = Person.objects.values('gender').annotate(cnt=Count('gender')).order_by('gender') total_items = Person.objects.count() items = [ {'gender': g['gender'], 'value': g['cnt'] * 100 / total_items} for g in genders ] return {'items': items} ...
django,django-views,django-rest-framework,user-registration
Neither of those is perfect. But View A looks promising. View A is a good start, but it is incomplete solution. Because User creation is not simply User.save, but rather you have to call User.create_user method. View B is the correct way to create user by calling User.create_user, however, the...
Each test method runs its own transaction which is rolled back at the end of the test. The data created in one test will not be available in another test. This login does not work because the user does not exist/was never created. If you need some common test data...
python,mysql,django,django-views,many-to-many
region.countries__in=country is an assignment, and because it is being performed in an if statement's condition, you are getting "colon expected". If you want to check for a country being related to a region you can do this: # country is the country's code n.region.filter(countries_code=country).exists() ...
python,django,django-forms,django-views
try this snippet function cloneMore(selector, type) { var newElement = $(selector).clone(true); var total = $('#id_' + type + '-TOTAL_FORMS').val(); newElement.find(':input').each(function() { var name = $(this).attr('name').replace('-' + (total-1) + '-','-' + total + '-'); var id = 'id_' + name; $(this).attr({'name': name, 'id': id}).val('').removeAttr('checked'); }); newElement.find('label').each(function() { var newFor = $(this).attr('for').replace('-'...
python,django,django-models,django-views
You could use a method like this: class DailyObj(models.Model): ... def total_crores(self): return self.Total_Rec / 10000000 It won't be stored in the database, but will be accessible in the template with something like this: {{ daily_obj.total_crores }} Or, in keeping with your query, something like this (assuming that top10records gets...
python,django,django-models,django-templates,django-views
You haven't said what you have tried to do to solve this, why you think it's "way overly complicated", or why it's causing you frustration. The thing to understand is that a view is entirely responsible for a page, ie the view creates the entire response when a URL is...
ok, so I didn't need to "extract" the variables from the dictionary in order to make use of them. I simply put a loop in my view code to generate the dictionary of variables, and then concatenated that dictionary with my http response dictionary: def display_prdInboxEntry(request, id): if request.method ==...
From an MVT (Model View Template) point of view, the balance modification of the UserProfile should be handled in the model it self not in the view. class UserProfile(models.Model): ## fields balance = models.IntegerField(default=0) def withdraw(self, amount): # you will need to check here if the # balance is enough...
python,django,templates,django-views,django-urls
Your s7h.views.home pattern has no terminating $ so it matches every URL.
python,django,django-views,nltk
The problem here is that the user running django don't have permission to read at /root. It does not happens when running django shell because you are running the shell as root, but the server is running as the www user (see, the first directory where nltk search is /var/www/nltk_data,...
If you look at the full traceback, you should be able to see that it is not the LampCreateView that is raising the exception. It sounds like you have another url pattern above the lamp_create which matches /shotmaker/camera/create/ first. For example: url(r'^camera/(?P<pk>[-\w]+)/$', views.OtherView.as_view(), name='other_view') url(r'^camera/create/(?P<pk>[-\w]+)$', views.LampCreateView.as_view(), name='lamp_create'), To solve the...
You need to save the user object manually: prnt = Parent.objects.get(id=pk) prnt.request_status = 'A' prnt.user.is_active = True prnt.user.save() # <---- here prnt.save() ...
django,django-forms,django-views
You can't use this syntax to use multiple model in a form. Admin backend makes extensive use of InlineModelFormSet to handle such relations. Take a look to https://docs.djangoproject.com/en/1.8/topics/forms/modelforms/#inline-formsets
django,django-views,url-routing
Investigating a bit into the django middleware hooks, it become evident that the process_request is not the best candidate for implementing the routing functionality. Indeed, from the documentation: It should return either None or an HttpResponse object. If it returns None, Django will continue processing this request, executing any other...
python,django,django-models,internationalization,django-views
Model translations are not supported by Django out of the box. Those packages implement that feature: django-hvad django-modeltranslation ...
python,django,django-templates,django-views,beautifulsoup
what's the result that you print out? have you try to use this? soup.title.string if you have to send html in to templates try: {% autoescape off %}{{ title }}{% endautoescape %} ...
Replace self.model.users = self.request.user with form.instance.save() form.instance.users.add(self.request.user) ...
reverse() does not support namespaced view references https://code.djangoproject.com/ticket/17914...
html,django,python-2.7,django-views
Why would you want more than one context? ctx is a dictionary, you can have as many items as you like in it.
python,django,hash,django-forms,django-views
In your views, I think it should be user.save() below the line user.set_password(user.password) You didn't write the brackets (parentheses). That's why save method is not being called after you hash the password....
struct.unpack('=H', urandom(2))[0] is just dumb. Just generate an integer in the readable way: 'InvId': random.randrange(2**16), ...
python,django,django-templates,django-views
The problem is neither while rendering the template or while calling the function, the problem is in the url definition. urls.py is only evaluated once when the server is first started. So when you write: url(r'^$', menu, {'Id' : getActiveItems()}), getActiveItems is evaluated then and never gets called again (until...
django,django-forms,django-templates,django-views
Since your form is submitting to the same url, you can simply use action="". If you prefer, you can use action="/surveyone/" If you don't want to hardcode the url in your template, then you need to name your url patterns: url(r'^surveyone/$', SurveyWizardOne.as_view([ SurveyFormIT1, SurveyFormH, ... ]), name="survey_one"), You can then...
Consider using a data migration: Create an empty migration file with manage.py makemigrations <app_name> --empty. Create a function that adds the default values to the database. def create_roles(apps, schema_editor): Group = apps.get_model('auth', 'Group') driver = Group.objects.create(name='driver') manager = Group.objects.create(name='manager') Add a RunPython operation to you migrations: class Migration(migrations.Migration): operations =...
django,django-models,django-forms,django-views
Don't do that in the model. Do it in the view. profile_form = ProfileForm(request.POST) if profile_form.is_valid(): profile = profile_form.save(commit=False) profile.user = request.user profile.save() ...
I didn't get exactly what you need. However from what I understood you want to get an object using the detail view. DetailView always by default get one object based on the passed PK in the URL. Here is an example from Django docs. If you have this URL pattern...
python,django,python-2.7,django-views
You might want to try the simple if slider_value1 != '' . This is a better option than if not slider_value1 because the latter will block out 0 also which you might not want to do.
django,django-templates,django-views
Here's a basic approach you can tweak for your convenience: Add a first_image field to your model: 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) first_image = models.CharField(max_length=400, blank=True) Now all you have to do is populate your first_image field on save, so...
django,django-models,django-views
You can't use the model's method in the values() method. But you can use the only() method to decrease the memory usage: Results.objects.only('s_result_id', 's_name', 's_score').filter(t_id=t_id1) ...
django,python-3.x,django-models,django-templates,django-views
Django has a default set of permissions (change, add, delete) for each model. You can use them in your template to hide the buttons or use a simple check if the user shown is also the user viewing the page. {% if perms.accounts.change_user %} Edit {% endif %} or {%...
When you change the user's password, their session is reset. Django takes care of reinjecting the session hash so that the user isn't automatically logged out, but values you stored in the session will be gone. I think you're trying to keep your logout view from crashing. In logout, change...
python-2.7,django-views,django-filter,django-pagination
please make the changes given below in the template, the code below will allow the pagination to get the filtered value and so it will paginate through the filtered value. Do the same changes for the next </table> <span class="step-links"> {% if leads.has_previous %} <a href="?page={{ leads.previous_page_number...
If I get your question, you can try this : notificationsPiorities = set([note.notificationType.priority for note in notifications ]) for(note in notification): if len(note.region.all()) == 0 and (note.notificationType.priority not in notificationsPiorities ): notifications.append(note) notificationsPiorities.add(note.notificationType.priority) Also, you may need to rename your variables. I can't tell for sure what are notification and...
python,django,csv,django-views
When you terminate the Django development server with Ctrl+C, this will kill the associated Python process and thus close all opened files. To check this behavior, you can make the following test: Start a Python interpreter and open a file: open('all_india_pin_code.csv') In a shell, check that the file was opened...
You'll want to use: data['success'] = p.bet.name Note that this will create a second SQL query against your db to load the Team object tied to p.bet. To save yourself a little bit of overhead, you can change this line: Bets.objects.create( bet_id=request.POST['team'],number=number) To this: Bets.objects.create( bet_id=request.POST['team'],number=number).select_related('bet') ...
django,django-forms,django-views,streaming,httpresponse
EDIT : ModelForm part removed, no need to save the data in DB so using classic form this way : Method 1 : Classic Form without Model using Django in your forms.py from django import forms class InputNumeroForm(forms.Form): numero = forms.IntegerField() in your views.py from django.shortcuts import render def stream_response(request):...
django,django-templates,django-views
You would need to name both arguments in your regular expression: url(r'^user/(?P<username>\w+)/list/(?P<listname>\w+)/$', mylistpage, name='lists'), More on that on Django documentation: URL Dispatcher: Named groups. Update: answering on the comments, to redirect to 404 if no username or listname, this would be handled in the view. For instance: User.objects.get_object_or_404(username=username) and from...
If you are absolutely sure, these strings never need to become dynamic just create a strings.py module and drop the strings there as variables ("constants") However, as the messages are user visible, you will most likely need to localize them at some point in your application's lifetime. Consequently, please make...
django,django-forms,django-templates,django-views
The render statement isn't expecting a trailing comma like when you're defining a tuple, which is most likely what's causing the error, however your code could use some refactoring.... from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User from django.core.urlresolvers import reverse from django.http import HttpResponseRedirect # assuming you're using your...
javascript,jquery,ajax,django,django-views
My apologies everyone. The solution was which value I passed in on my input. The correction was to change purchased.get_buyers to product.get_buyers. Thank you all for the help though!...
django,checkbox,django-templates,django-views
views.py if request.method == 'POST': #gives list of id of inputs list_of_input_ids=request.POST.getlist('inputs') Hope this solves pretty much of your problem.Check out this link Checkboxes for a list of items like in Django admin interface ...
django,django-templates,django-views
Index View First of all, when you are using Django Generic List View the object list in the template is called object_list. Check the above link to see django documentation. So to show all the IceCream names in the Index template you should do: {% for item in object_list %}...
python,django,django-templates,django-views
You cannot do this like that. Views are glorified functions. They have a single entry point (dispatch()) that is invoked by Django internals, and invokes the correct method on itself, depending on the HTTP method (here, get()). Casting the view to a string will just display its name, not call...
django,django-views,django-class-based-views
To answer your question: Overriding .get() and .post() is fine, since for security and integrity reasons, you would want both your get() and post() views to validate before displaying and especially modifying data. Now, if you want to refactor doing this in get or post, there are 2 easy ways...
jquery,django,django-models,django-forms,django-views
I eventually found a way of solving this. The overarching problem was that I was trying to add information to my Person Model which was not 'generated/originated' from my forms.py / models.py in the traditional way but rather was being 'generated' on the page from my jQuery script. I knew...
django,django-models,django-views,django-rest-framework
As of Django REST framework 3.1, it is not possible to submit multiple values using form data. This is because there is no standardized way of sending lists of data with associations, which is required for handling a ListSerializer. There are plans to implement HTML JSON forms support, which would...
python,django,django-forms,django-templates,django-views
On the contrary, this is exactly a job for formsets: 'multiple identical form "components" all within the same form' is precisely what they are. class ReviewPhotosForm(forms.Form): DECISION_CHOICES = ( ('approve', 'Approve'), ('reject', 'Reject') ) ROTATE_CHOICES = ( ('none,', 'None'), ('right', 'Right'), ('left', 'Left'), ('flip', 'Flip') ) # hidden field to...
django,unit-testing,django-views,django-rest-framework,django-testing
RequestFactory and Client have some very different use-cases. To put it in a single sentence: RequestFactory returns a request, while Client returns a response. The RequestFactory does what it says - it's a factory to create request objects. Nothing more, nothing less. The Client is used to fake a complete...
django,django-forms,django-templates,django-views
The Django admin uses AdminTimeWidget to display time fields, not the TimeInput widget that you are using in your code. There isn't a documented way to reuse the AdminTimeWidget outside of the Django admin. Getting it to work is very hacky (see the answer on this question, which is probably...
python,django,file-io,pandas,django-views
"Adding complete path and complete code in views.py, and I realized something, when I delete list function in views.py the graph worked just fine, I think there is a clash between list function and showimage function" Yes, indeed. Naming your view function list shadows the builtin type list in...
django,django-templates,django-views,html-form
It's a bad idea to try and parse/modify the existing URL. But there's no reason to. Your template presumably already has access to the post itself, so you should use this to construct the URL via the normal {% url %} tag. <form action="{% url "submit_comment" post_id=post.id %}" method="POST"> assuming...
python,django,django-templates,django-views
On CategoryNews view add news to render context. This will make news items available in templates. def CategoryNews(request, categoryslug): category = Category.objects.get(slug=categoryslug) news = News.objects.filter(category=category) return render (request, 'news/category_news.html', {'category' : category, 'newsitems': news}) Add named group to category url to make it dynamic. Rewrite url(r'^kids-garden/$', views.CategoryNews, name='category'), to url(r'^category/(?P<categoryslug>\w+)/$',...
python,django,django-views,django-rest-framework,django-urls
You can't access request on urls.py, see: How Django processes a request You can configure versioning on django-rest-framework and get version on request object like: class SampleView(APIView): def post(self, request, format=None): if request.version == '1': return Response(status=status.HTTP_410_GONE) Or use URLPathVersioning approach....
You're missing the enctype="multipart/form-data" in the HTML form tag. Otherwise no file data is sent by the browser. Nevertheless, you should not be referencing the request.POST and request.FILES dicts directly in your view: that's what the form is for: dform = ArticleForm(request.POST, request.FILES) if dform.is_valid(): article = dform.save(commit=False) article.user =...
django,django-views,django-urls
You should return the response: return HttpResponseRedirect(...) BTW consuder to use the redirect() shortcut which does the same thing but with much less code....
django,twitter-bootstrap,django-views,django-class-based-views
You can access the related products for each category using the related field manager products_set, eg: {{category.category_name}} //trying to change here by displaying all model_names!! <ul> {% for product in category.product_set.all %} <li>{{ product.model_name }}</li> {% endfor %} </ul> If you need more complicated filtering, you'd want to either do...
python,django,django-models,django-forms,django-views
You should construct UserProfileForm form with the UserProfile instance instead of User: profile = UserProfile.objects.filter(user=user).first() ... profile_form = UserProfileForm(data=request.POST, instance=profile) ... profile_form = UserProfileForm(instance=profile) If you are sure that profile is already exist then you can write: profile = user.userprofile instead of the filter().first() call....
The issue lies at that line: address = UserAddress.objects.get() As you do you not specify query parameters when trying to retrieve the address, Django retrieves the only address that you have in your database (if you had more than one or no address, it would fail). So you are always...
python,django,django-views,django-comments
You don't have to use a form, or a post request for that matter. All you need to do is create an instance of the comment model which you can do via Django's ORM. To do this, you would need to have all of the necessary parameters the model expects,...
django,django-templates,django-views
You need to define a custom template tag which returns the type of data. from django import template register = template.Library() @register.filter def data_type(value): return type(value) Then use it inside your template like this: {% for key, value in leasee.items %} <p> {{key}} </p> <ul> {%if value|data_type == 'dict' %}...
python,django,python-2.7,django-views
There probably are no Vote objects for newly created links. In that case, the annotated votes attribute will be None. I don't know a straight-forward way of fixing this right now, but I would guess that you can solve this by using F expressions.
python,django,django-models,django-views,django-queryset
You need to check that there are likes. Both in the view and in the template. Since the like variable could either have content or not, you could check first in the view. If it exists, add it to the dictionary. def photo_detail(request, photo_slug, username): u = MyUser.objects.get(username=username) obj =...
python,django,django-templates,django-views
You have to pass context to the html: from django.shortcuts import render from django.http import HttpResponse from TasksManager.models import Supervisor, Developer # View for create_developer def page(request): error = False # If form has posted if request.POST: if 'name' in request.POST: name = request.POST.get('name', '') else: error=True if 'login' in...
request.POST should be the dict-like QueryDict but not the simple python dict: from django.http import QueryDict request.POST = QueryDict('').copy() request.POST.update(request.session['search-profiles-post']) ...
python,django,django-views,django-urls
Here is your issue: In your URL patterns, url(r'^(?P<slug>\S+)$', views.detail, name="entry_detail"), url(r'^testingpage/', views.testview, name='testview'), The testingpage is being matched with ?P<slug>\S+ (for views.detail), before views.testview, and you probably have a raise 404 or something similar line of code to match slug. So, Change the order: url(r'^testingpage/', views.testview, name='testview'), url(r'^(?P<slug>\S+)$', views.detail,...
Hashing is not encrypting! A hash is a function that converts one message to another. Consider a hash function (LAME_HASH) that just takes the count of the number of characters in a string. LAME_HASH("TOOMANYSECRETS") >>> 13 LAME_HASH("SETECASTRONOMY") >>> 13 If I tell you my string is "TOOMANYSECRETS" and the hash...
django,django-templates,django-views,django-urls
its either: {% url 'article' article.slug article.pk %} or {{ article.get_absolute_url }} The latter will only work, if in your model you have something like this: class Article(models.Model): slug = models.SlugField() ... def get_absolute_url(self): return reverse('article', args=[self.slug, self.pk]) ...
django,django-models,django-forms,django-templates,django-views
Your form inherits from forms.Form, which does not know anything about models and ignores the Meta class. You should inherit from forms.ModelForm.