Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django-autocomplete-light Exception Type:NoReverseMatch
I can't find a solution for this, nothing seems to work. Basically i have four models nested into each other, each binded to the "upper" one with a foreignkey. I want to use autocomplete in the admin when I adding new onews because the default SELECT widget is not efficient. But I bumped into this and I'm stuck.. theapps/urls.py: from django.conf.urls import url, include from . import views from .views import type_autocomplete app_name = 'catalog' urlpatterns = [ url(r'^catalog/$', views.index, name='index'), url(r'^catalog/(?P<selected_brandurl>\w+)/$', views.brand_detail, name='brand_detail'), url(r'^catalog/(?P<selected_brandurl>\w+)/(?P<selected_markurl>\w+)/$', views.mark_detail, name='mark_detail'), url(r'^catalog/(?P<selected_brandurl>\w+)/(?P<selected_markurl>\w+)/(?P<selected_typeurl>\w+)/(?P<selected_engineurl>[^/]+)/$', views.engine_detail, name='engine_detail'), url( r'^type_autocomplete/$', type_autocomplete.as_view(), name='type-autocomplete', ), ] theapps/views.py: from dal import autocomplete class type_autocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): # Don't forget to filter out results depending on the visitor ! if not self.request.user.is_authenticated(): return b_mark.objects.none() qs = b_mark.objects.all() if self.q: qs = qs.filter(b_mark__istartswith=self.q) return qs theapps/forms from django import forms from dal import autocomplete from .models import c_type class type_form(forms.ModelForm): type_mark = forms.ModelChoiceField( queryset=c_type.objects.all(), widget=autocomplete.ModelSelect2(url='type_autocomplete') ) class Meta: model = c_type fields = ("__all__") It says: Reverse for 'type_autocomplete' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: [] -
Deletion of a model object via AJAX: how to hide deletion url from the user?
Django 1.10 DetailView renders "detail.html". In "detail.html" I place "Delete" button. In other words, I want users to be able to press "Delete" exactly from "detail.html" when they see the object itself. So, on pressing "Delete" button I call FrameDelete via AJAX. If deletion is not successful, I show alert message. For example, a user was at http://localhost:8000/frame/20/, then s/he presses deletion button, there occurs an integrity error - I forbid to delete objects used in foreign keys somewhere. Then alert message to the user appears. The user presses Ok. And s/he is redirected to http://localhost:8000/frame/20/delete/ I want them to stay at /frame/20/. I thought making an AJAX post request hides the underlying delete function, while the user stays at the detail page. But it happens that I was wrong, and frame_delete URL becomes visible to the user. Could you help me understand why such redirect happened? Shall I make a special redirect from frame_delete to frame_detail in fail function? urlpatterns = [ url(r'^frame/', include('frame.urls', namespace='frame')), ] urlpatterns = [ url(r'^(?P<pk>\d+)/$', FrameDetailView.as_view(), name="frame_detail"), url(r'^(?P<pk>\d+)/delete/$', FrameDelete.as_view(), name="frame_delete"), ] class Frame(models.Model): title = models.CharField(max_length=100, null=False, blank=False, default="", unique=True, verbose_name="Заголовок") def get_delete_url(self): return reverse("frame:frame_delete", kwargs=self.get_kwargs()) class FrameDelete(ActionDeleteMixin, DeleteView): model = Frame success_url = … -
Django WebApp + parser script, how should I implement this setup
I'm learning Django by building a project: single website parser that continuously looks for the user-defined keywords and returns URLs of the pages where these keywords are found (on this website). There is a Django web-app that allows users to create and store keywords in the sqlite3 DB. And there is a Python script I wrote, that takes keyword as an argument and does its logic then returns the URL. How can I glue these two parts together? I want my script to continuously run with the set keywords, but when user changes or updates the DB I would like to update the behavior of my script. Effectively I would like to know how control my while True script with the Django Web-App, given the example of the setup. Thanks for advance! -
Multiple save in model object django
I use driver cassandra for my db backend in django , here is my problem : when I wanna run multiple save in a model object instance , the first one save successfully but the others save wont update my record , here is a example : obj = Mymodel.objects.get(id=2) obj.field1 = 2 obj.save() obj.field2 = 3 obj.save() # this save don't work am I doying right or for every update i should refresh my model object like this : obj = Mymodel.objects.get(id=obj.id) regards -
NameError : the variable is not defined [on hold]
def last_done_step(selected_course,user): query_result = done.objects.filter(user=user, step__chapter__course=selected_course).order_by('-step__chapter__index','-step__index') if query_result.exists(): return qeury_result.first().step else: raise CourseIsNotStartedErrorError whats wrong about this function ? this error appeared NameError: name 'qeury_result' is not defined -
There's error "INSERT command denied" in mysql on Bluemix
Since there's error "INSERT command denied" in mysql on Bluemix. The permission can read only and unable to write. How should I do. Thank you -
Django-tastypie: doesn't save ToOneField
Cann't undersntand where is problem: class PostResource(ModelResource): place = fields.ToOneField(PlaceResource, attribute='place') user = fields.ToOneField(ProfileResource,attribute='profile') #action = fields.ForeignKey(ActionResource, 'action') def hydrate(self, bundle): ------------------------- bundle.data['place'] = _place bundle.data['user'] = qProfile.objects.get(user = bundle.request.user) return bundle class ProfileResource(ModelResource): username = fields.ForeignKey(UserResource, 'user', blank=True, null=True) class Meta: queryset = qProfile.objects.all() excludes = ['token'] resource_name = 'profile' def dehydrate_username(self, bundle): bundle.data['username'] = bundle.obj.user.username return bundle.obj.user.username class UserResource(ModelResource): class Meta: queryset = User.objects.all() excludes = ['email', 'password', 'is_active', 'is_staff', 'is_superuser'] resource_name = 'user' class PostInfo(models.Model): user = models.ForeignKey(qProfile, related_name="PostUser", on_delete=models.CASCADE, null=True, blank=True) text = models.CharField(max_length=250) photos = models.ForeignKey(PostPhoto, related_name="PostPhoto", on_delete=models.CASCADE, null=True, blank=True) place = models.ForeignKey(PlaceInfo, related_name="PostPlace", on_delete=models.CASCADE, null=True, blank=True) action = models.ForeignKey(ActionInfo, related_name="PostAction", on_delete=models.CASCADE, null=True, blank=True) date = models.DateTimeField(auto_now_add=True) bundle.data['place'] saves properly, but can't save user. Even if i will set into bundle.data['user'] bundle.request.user and change user ForeinKey to UserResource problem still here. This hydrate returns me Bad Request when i uncomment this line or line with 'action' definition: user = fields.ToOneField(ProfileResource,attribute='profile') -
How to deploy a website online?
Hello Friend's i had made a website using python django framework,now i want to put it live.so what step or processor will be follow to put it live. please tell or is there any tutorial let me know. -
Setting Django compressor in production with S3 as static file storage
I have been trying to setup django compressor.It is working fine in local environment but while in production i am not able to set compress root.I don't have any static root defined in my production settings file.I am using herkou memcahier to cache. Settings.py AWS_HEADERS = { # see http://developer.yahoo.com/performance/rules.html#expires 'Expires': 'Thu, 31 Dec 2099 20:00:00 GMT', 'Cache-Control': 'max-age=94608000', } AWS_STORAGE_BUCKET_NAME='hxxx' AWS_ACCESS_KEY_ID='xxxxxxxxxxxxx' AWS_SECRET_ACCESS_KEY='xxxxxxxxxxxxxxxxxxxxxxxxxxxx' #S3DIRECT_REGION = 'us-west-2' AWS_S3_CUSTOM_DOMAIN='xxxxxx.s3-website-us-west-2.amazonaws.com' STATIC_URL = "http://%s/" % AWS_S3_CUSTOM_DOMAIN STATICFILES_STORAGE = 'storages.backends.s3boto.S3BotoStorage' MEDIA_URL = "http://%s/" % AWS_S3_CUSTOM_DOMAIN DEFAULT_FILE_STORAGE = 'storages.backends.s3boto.S3BotoStorage' AWS_S3_SECURE_URLS = False AWS_QUERYSTRING_AUTH = False CACHES = memcacheify() COMPRESS_URL=STATIC_URL COMPRESS_STORAGE=STATICFILES_STORAGE INSTALLED_APPS = ('compressor',...) -
Server CPU goes 100% in 2 hours on Django WSGI Server on Elastic Beanstalk
I have django rest api application hosted on Elastic Beanstalk. I am seeing my server going up by 90% with C4.large instance. I have close to 1500/min sum requests being processed at any point of time. I have been trying to figure it out but not able to find whats going wrong. I have my DRF API + Celery Worker code base under one project. I extensively use pandas on my workers but not on DRF endpoints. Does having many requirements affect WSGI Server. amqp==1.4.7 anyjson==0.3.3 awscli==1.7.42 Babel==2.1.1 backports-abc==0.4 beautifulsoup4==4.4.1 billiard==3.3.0.21 boto3==1.1.1 botocore==1.1.12 celery==3.1.19 colorama==0.3.3 Django==1.8 django-braces==1.8.1 django-cors-headers==1.1.0 django-debug-toolbar==1.4 django-loaderio==0.3.0 django-oauth-toolkit==0.9.0 djangorestframework==3.1.3 docutils==0.12 flower==0.8.3 futures==2.2.0 google==1.7 greenlet==0.4.9 gunicorn==19.4.5 httplib2==0.9.2 jmespath==0.7.1 keen==0.3.20 kombu==3.0.30 livestreamer==1.12.2 Markdown==2.6.2 oauthlib==1.0.3 Padding==0.4 pubnub==3.7.4 pyasn1==0.1.8 pycrypto==2.6.1 PyMySQL==0.6.6 python-dateutil==2.4.2 pytz==2015.7 PyYAML==3.11 redis==2.10.5 requests==2.8.0 rsa==3.1.4 six==1.9.0 sqlparse==0.1.18 tornado==4.3 virtualenv==13.1.2 webapp2==2.5.2 eventlet==0.18.4 python-gcm==0.4 numpy==1.11.0 pandas==0.18.0 py2neo==2.0.8 neo4jrestclient==2.1.1 google-api-python-client==1.5.1 python-firebase==1.2 cassandra-driver==3.4.1 passlib==1.6.5 django-request-logging==0.4.6 django-cache-machine==0.9.1 genderize==0.1.5 logentries==0.17 psutil==4.3.1 -
i have csv file.when we have keep header is -1 output is ok but header is 0 getting differently.i used append option.please check below
this is my file. name,client,no Jason,Miller,42 Tina,Ali,36 Jake,Milner,24 Jason,Miller,42 Jake,Milner,24 Amy,Cooze,73 Jason,Miller,42 Jason,Miller,42 Jake,Milner,24 this is output file header is -1 with append option. name client no name client no Jason Miller 42 Jason Miller 42 Tina Ali 36 Tina Ali 36 Jake Milner 24 Jake Milner 24 Jason Miller 42 Jake Milner 24 Amy Cooze 73 Amy Cooze 73 Jason Miller 42 Jason Miller 42 Jake Milner 24 this is my outputfile header is 0 with append option. name client no 0 1 2 Jason Miller 42 Jason Miller 42 Tina Ali 36 Tina Ali 36 Jake Milner 24 Jake Milner 24 Jason Miller 42 Jake Milner 24 Amy Cooze 73 Amy Cooze 73 Jason Miller 42 Jason Miller 42 Jake Milner 24 -
Django TIME_ZONE definition ignored by time.tzname
I need use Timezone in a Django app. I defined in settings.py UTC timezone : TIME_ZONE = 'UTC' I put the following code in a view : import time print(time.tzname) But it displays me : ('Paris, Madrid') Do you know how to define timezone in all the Django app ? -
Django Text Query Search
I followed Julien Phalip example on how to create a django basic search engine. After implementing it, it worked but there's a problem. When I search with double keywords with comma and space in between it failed to return a result. For example, San Francisco US will return the results San Francisco,US won't return any result. San Francisco, US won't also return any result. The 'comma' is not helping maters. See the code below. def normalize_query(query_string, findterms=re.compile(r'"([^"]+)"|(\S+)').findall, normspace=re.compile(r'\s{2,}').sub): return [normspace(' ', (t[0] or t[1]).strip()) for t in findterms(query_string)] def get_query(query_string, search_fields): query= None terms= normalize_query(query_string) for term in terms: or_query= None for field_name in search_fields: q= Q(**{"%s__icontains" % field_name: term}) if or_query is None: or_query= q else: or_query= or_query | q if query is None: query= or_query else: query= query & or_query return query def my_search(request): query_string= '' hots= None if ('q' in request.GET) and request.GET['q'].strip(): query_string = request.GET['q'] entry_query= get_query(query_string, ['city','country',]) hots= Place.objects.filter(entry_query).order_by('-pub_date')[:3] return render_to_response('search/search_results.html', { 'query_string': query_string, 'hots': hots }, context_instance=RequestContext(request)) I want to 'normalize the query' so it will make it accept the 'comma' and return the result for the query. What am I missing? -
What i adjust for android login into RESTful api in this conditions?
I'm in conditions follows I have RESTful API using Django (DJango-rest-auth/You might see it http://django-rest-auth.readthedocs.io/en/latest/) I post parameters in json type like { "username": "blahblah", "email": "~~~blah@blah~.com", "password1": "blahblah", "password2": "blahblah" } and then I receive HTTP 200 OK Allow: POST, OPTIONS Content-Type: application/json Vary: Accept { "key": "99defb355414133f00ad88e15771e3a8b43e71f" } But i can't understand How to use this. django-rest-auth says { "name": "Login", "description": "Check the credentials and return the REST Token\nif the credentials are valid and authenticated.\nCalls Django Auth login method to register User ID\nin Django session framework\n\nAccept the following POST parameters: username, password\nReturn the REST Framework Token Object's key.", "renders": [ "application/json", "text/html" ], I think this means i use that "key" for authentication, for example, If i use retrofit2, i post id and password to my rest url, and receive key value from rest url. Then use key on sharedpreference to maintain user login. Is it right way? Im very new bie, please give me some hints what i learn or what should i do. What i want most is it : 1.login from android 2.to maintain login on android to use other contents which is in my restful api service. -
django rest framework multiple url arguments
In rest api view I need to have 2 objects. For example: class Foo(models.Model): .... class Bar(models.Model): .... What is correct way to get them? I mean how should I configure urls? I think this is not really good practice: url(r'^foo/(?P<pk>\d+)/bar/(?P<pk>\d+)/$', FooBarView.as_view()) Or: url(r'^foobar/$', FooBarView.as_view()) and then pass parameters: ?foo=1&bar=2. -
Update if exists or create Model in Django Rest
I got this model: class Like(models.Model): id = models.AutoField(primary_key=True) user = models.ForeignKey(settings.AUTH_USER_MODEL) post = models.ForeignKey('posts.Post', blank=True, null=True) RATING_CONVERSION = ( (1, '+'), (0, '0'), (-1, '-'), ) userRating = models.SmallIntegerField(choices=RATING_CONVERSION) def __int__(self): return self.id If post id and user id exists I need to update rating. I try to make it. Serializer: class LikeSerializer(serializers.ModelSerializer): user = serializers.PrimaryKeyRelatedField(queryset=ExtUser.objects.all(), required=False, allow_null=True,default=None) class Meta: model = Like field = ('user', 'post') validators = [ UniqueTogetherValidator( queryset=Like.objects.all(), fields=('user', 'post') ) ] def validate_user(self, value): return self.context['request'].user def create(self, validated_data): return Like.objects.create(**validated_data) And ViewSet class LikeViewSet(viewsets.ModelViewSet): queryset = Like.objects.all() serializer_class = LikeSerializer @detail_route(methods=['post', 'get']) def get_object(self): if self.request.method == 'POST': like = Like.objects.get(user=self.context['request'].user, post = self.context['request'].post) if like: return like else: return Like(id=self.kwargs.get('pk')) else: return super(LikeViewSet, self).get_object() I found a lot of information how to create or update using pk in Url, but I got parameters inside of JSON This method doesn't work - instead of update rating it creates new Model objects -
Why is Django reporting inconsistent values for this instance attribute?
I have the following simple Django model class: from django.db import models class MyClassA(models.Model): name = models.CharField(max_length=254) parent_a = models.IntegerField() def update_names(self, name, other_a_list): a_set = set([self] + other_a_list) for curr_a in a_set: curr_a.name = name curr_a.save() print "Updated MyClassA #%s's name to %s" % (curr_a.pk, curr_a.name) def related_a_instances(self): family_list = MyClassA.objects.filter(parent_a=self.parent_a) return [curr_a for curr_a in family_list if curr_a.name == "CREATED"] When I run the following code it, the last assertion fails: m1 = MyClassA.objects.create(parent_a=99, name="OPEN",) m2 = MyClassA.objects.create(parent_a=99, name="CREATED",) assert m2.name == "CREATED" m3 = MyClassA.objects.create(parent_a=99, name="CREATED",) assert m3.name == "CREATED" related_a_instances = m2.related_a_instances() assert related_a_instances == [m2, m3] m2.update_names(name="OPEN", other_a_list=related_a_instances) print "Checking that MyClassA m1 (%s) is OPEN. My Code says its %s. DB says %s" % (m1.pk, m1.name, MyClassA.objects.get(pk=m1.pk).name) assert m1.name == "OPEN" print "Checking that MyClassA m2 (%s) is OPEN. My Code says its %s. DB says %s" % (m2.pk, m2.name, MyClassA.objects.get(pk=m2.pk).name) assert m2.name == "OPEN" print "Checking that MyClassA m3 (%s) is OPEN. My Code says its %s. DB says %s" % (m3.pk, m3.name, MyClassA.objects.get(pk=m3.pk).name) assert m3.name == "OPEN" Here is the console output when the failure happens: Updated MyClassA #2's name to OPEN Updated MyClassA #3's name to OPEN Checking that MyClassA m1 … -
filtering models by foreign key
class course(models.Model): title = models.CharField(max_length=255) class chapter(models.Model): course = models.ForeignKey(course) index = models.IntegerField() class step(models.Model): chapter = models.ForeignKey(chapter) index = models.IntegerField() I have 3 models: course, chpater and step and i want to filter step by it course. step.objects.filter(chapter__course=current_step.course,chapter__index__gte=current_step.chapter.index,index__gt=current_step.index).order_by('chapter__index', 'index').first() but this error appear: AttributeError: 'step' object has no attribute 'course' how can i do that ? -
Delete via AJAX results in CSRF token missing or incorrect
Django 1.10 DetailView renders "detail.html". In "detail.html" I place "Delete" button. In other words, I want users to be able to press "Delete" exactly from "detail.html" when they see the object itself. So, on pressing "Delete" button I call FrameDelete via AJAX. Could you help me understand why I get the error: CSRF token missing or incorrect. class Frame(models.Model): title = models.CharField(max_length=100, null=False, blank=False, default="", unique=True, verbose_name="Заголовок") def get_delete_url(self): return reverse("frame:frame_delete", kwargs=self.get_kwargs()) class FrameDelete(ActionDeleteMixin, DeleteView): model = Frame success_url = reverse_lazy("empty") template_name = 'general/ajax/ajax_confirm_delete.html' class ActionDeleteMixin(): def get_context_data(self, **kwargs): context = super(ActionDeleteMixin, self).get_context_data(**kwargs) context["action"] = self.object.get_delete_url() return context js function post_delete(){ $.ajax({ method: 'POST', url: "{{ object.get_delete_url }}", success: redirect_to_frame_list, error: fail }); } function fail(jqXHR, textStatus, errorThrown){ debugger; } ajax_confirm_delete.html {% block content %} <form action="{{ action }}" method="post">{% csrf_token %} <p>Are you surely want to delete "{{ object }}"?</p> <input id="confirm" type="submit" value="Confirm" /> </form> {% endblock %} In the browser when inspecting element in Chrome: <form action="/frame/18/delete/" method="post"><input type="hidden" name="csrfmiddlewaretoken" value="bHZxf62Oa9WrapuacCm8gLVNlY2nJHllfwqPsAHoPO0RS8z8NnhMSv5tnIFQZKPP"> <p>Are you surely want to delete "18: Michael's news"?</p> <input id="confirm" type="submit" value="Confirm"> </form> ** In the browser when stop at the debugger breakpoint in fail function " <!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="content-type" content="text/html; … -
Why is there a difference in format of encrypted passwords in Django
I am using Django 1.97. The encrypted passwords are significantly different (in terms of the format). Some passwords are of format $$$: pbkdf2_sha256$24000$61Rm3LxOPsCA$5kV2bzD32bpXoF6OO5YuyOlr5UHKUPlpNKwcNVn4Bt0= While others are of format : !9rPYViI1oqrSMfkDCZSDeJxme4juD2niKcyvKdpB Passwords are set either using User.objects.create_user() or user.set_password(). Is this difference an expected one ? -
Create dynamic query for both AND & OR conditions using django
Basically based on multiple filters selected I have created below JSON. {"category1":["A","B","C"],"category2":["x","y","z"],"category3":["med1","med2"]} I am looking for below query created dynamically from above JSON query=((Q(category__name__contains="category1") & (Q(subcategory__name__contains="A")| Q(subcategory__name__contains="B")|Q(subcategory__name__contains="C")) )|(Q(category__name__contains="category2") & (Q(subcategory__name__contains="x")| Q(subcategory__name__contains="y")|Q(subcategory__name__contains="z")) )|(Q(category__name__contains="categor3") & (Q(subcategory__name__contains="med1")| Q(subcategory__name__contains="med2")) )) Product.objects.filter(query) Any ideas on how to do this? Do I have to use row sql query or can be done by Django query? -
oauth2client with django flowfield
Now that I got back to my googleapi django project, I found out that oauth2client no longer uses the flowfield class, and has a couple directory changes. I can probably cover the directory changes, but is there an alternative to the removal of flowfield? -
Django: IntegrityError and ajax
Django 1.10 DetailView renders "detail.html". In "detail.html" I place "Delete" button. In other words, I want users to be able to press "Delete" exactly from "detail.html" when they see the object itself. So, on pressing "Delete" button I call DeleteView via AJAX. function post_delete(){ $.ajax({ method: 'POST', url: "{{ object.get_delete_url }}", success: redirect_to_frame_list, error: fail }); } function fail(jqXHR, textStatus, errorThrown){ } Let us suppose there is an integrity error: a user wants to delete an object which is a foreign key somewhere. In debug mode there will be information about the error: IntegrityError at /frame/1/delete/ update or delete on table "frame_frame" violates foreign key constraint "item_item_frame_id_90270aea_fk_frame_frame_id" on table "item_item" DETAIL: Key (id)=(1) is still referenced from table "item_item". ... But on the client side without debug mode we have only jqXHR. In this case in fail function in jqXHR.responseText we have: " <!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <meta name="robots" content="NONE,NOARCHIVE"> <title>403 Forbidden</title> <style type="text/css"> html * { padding:0; margin:0; } body * { padding:10px 20px; } body * * { padding:0; } body { font:small sans-serif; background:#eee; } body>div { border-bottom:1px solid #ddd; } h1 { font-weight:normal; margin-bottom:.4em; } h1 span { font-size:60%; color:#666; font-weight:normal; … -
form data is not received
I am using Django and Bootstrap on frontend to write a single profile editing module. Plain form from Django is ugly, so I did some custimizing on the form. Here is the HTML form: <form actoin="{% url 'edit_profile' %}" method="post"> {% csrf_token %} <div class="form-group row"> <label for="chineseName" class="col-sm-2 control-label">name</label> <div class="col-sm-10"> <input name="chinese_name" class="form-control" id="chineseName" placeholder="name" value="{{form.chinese_name.value}}"> </div> </div> <div class="form-group row"> <label for="gender" class="col-sm-2 control-label">gender</label> <div class="col-sm-10"> <label class="radio-inline"> {% if form.gender.value == "M" %} <input type="radio" name="gender" id="gender1" value="M" checked> Male {% else %} <input type="radio" name="gender" id="gender2" value="M"> Male {% endif %} </label> <label class="radio-inline"> {% if form.gender.value == "F" %} <input type="radio" name="gender" id="gender1" value="F" checked> Female {% else %} <input type="radio" name="gender" id="gender2" value="F"> Female {% endif %} </label> </div> </div> <div class="form-group row"> <label for="age" class="col-sm-2 control-label">age</label> <div class="col-sm-10"> <input name="age" class="form-control" id="age" placeholder="年龄" value="{{form.age.value}}"> </div> </div> <div class="form-group row"> <label for="phone" class="col-sm-2 control-label">phone</label> <div class="col-sm-10"> <input name="phone" class="form-control" id="phone" placeholder="phone" value="{{form.phone.value}}"> </div> </div> <div class="form-group row"> <div class="col-sm-offset-2 col-sm-10"> <button type="submit" class="btn btn-default col-xs-12" id="confirm" style="display:none;">confirm</button> </div> </div> </form> Somehow request.POST is not receiving data from this form. When I switch this long HTML snippet into {{form}}, everything is fine. So view … -
Django upload only csv file
I am trying to import csv file i am able to import without any problem but the present functionality accepts all file types, i want the functionality to accept only csv file. below is the view.py and template file. myapp/views.py def list(request): # Handle file upload if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): importing_file(request.FILES['docfile']) myapp/templates/myapp/index.html <form action="{% url 'ml:list' %}" method="post" enctype="multipart/form-data"> {% csrf_token %} <p>{{ form.non_field_errors }}</p> <p>{{ form.docfile.label_tag }} {{ form.docfile.help_text }}</p> <p> {{ form.docfile.errors }} {{ form.docfile }} </p> <p><input type="submit" value="Upload"/></p> </form>