Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Email Validation is not working: validate_email() , Django
try: validate_email(request.POST['email']) userkey=User.objects.get(username=request.user.username) get_UForm=UserProfile(request.POST or None) if any(c.isalpha() for c in request.POST['phone']): messages.warning(request,'With all due respect, Alphabets are not allowed in the mobile number') return HttpResponseRedirect(reverse('account_details')) if " " in request.POST['phone']: messages.warning(request, 'We need a valid mobile') return HttpResponseRedirect(reverse('account_details')) #If the user is re- updating his details if UserInfo.objects.filter(accusername=userkey).exists(): getUserobj = UserInfo.objects.get(accusername=userkey) if request.POST['affliation']: #print "aff" getUserobj.affliation = request.POST['affliation'] if request.POST['country']: #print "count" getUserobj.country = request.POST['country'] userkey.first_name=request.POST['firstname'] userkey.last_name=request.POST['lastname'] userkey.email=request.POST['email'] userkey.save() getUserobj.phone = request.POST['phone'] getUserobj.save() #if the user is updating his profile for the first time else: newobj=UserInfo(accusername=request.user,affliation=request.POST['affliation'],phone=request.POST['phone'],country=request.POST['country']) newobj.save() #if he changed password if request.POST['password']: #if both fields are equal if request.POST['password']==request.POST['againpassword']: if " " in request.POST['password']: messages.warning(request, 'You cant put Spaces in the password,Please !') return HttpResponseRedirect(reverse('account_details')) userU=User.objects.get(username=request.user.username) userU.set_password(request.POST['password']) userU.save() return HttpResponseRedirect(reverse('account_login')) #error message else: messages.warning(request,'Please make sure both passwords are same') return HttpResponseRedirect(reverse('account_details')) messages.warning(request, 'Yup saved your details, look forward to serve you better as always') return HttpResponseRedirect(reverse('account_details')) except forms.ValidationError: messages.warning(request,'Email field is not Valid') return HttpResponseRedirect(reverse('account_details')) except Exception as e: print e messages.warning(request, 'Oops, there are errors in the form') return HttpResponseRedirect(reverse('account_details')) validate_email is not working in django, i tried form.is_valid() prior to this way of code but that is also failing. The same code is working perfectly … -
Django password_change built in view , displays a popup box with all of my users to select from
Iam using django built in password_change view , and it is working fine , but the problem is that after i Enter my old and new password in the form correctly, a pop up window with all of my users shows up asking me to conform the user that i am changing his password, So any edia , how can i prevent that pop up window !! thanks -
Django, how to update DB based on the foreignkey value?
I have tried in Models (with "def save") but give me error "int() argument must be a string, a bytes-like object or a number, not 'Length'". I have fields "length" and "width" in foreignkey. And I want when submit a form to add value of "squaremeter" field to DB calculated based on the length and width selected def save(self, *args, **kwargs): self.squaremeter = self.length * self.width self.squaremeter.save() super(Product, self).save(*args, **kwargs) For two weeks I'm stuck in this issue -
How can I generate client_id in Application model in djang-oauth2-toolkit?
Noob question here! Is it possible to generate client_id directly in Application Model? like app = Application(user=request.user, name='API Test', grant-type='password', redirect_uri='localhost:8000/api/test') app.save() then automatically generates client_id and client_secret. -
Gevent - Loop Exit Pool
My code was running fine on a Ubuntu Django server with Nginx. I started getting some issues with the multiprocessing library. I changed to a new server, implemented Apache and increased the number of cores (8 cores) but I keep getting the error Loop Exit. Simplified version of code is this: from gevent.pool import Pool import speech_recognition as sr r = sr.Recognizer() with sr.AudioFile(AUDIO_FILE) as source: audio = r.record(source) def result(b): return(r.recognize_google_cloud(audio, language=b, show_all=True)) pool = Pool() language1 = str(language1) language2 = str(language2) results = pool.map(result, [language1, language2]) print(results) -
Django and ebay multi listing
I'm trying to mimic eBay's multi listing function. Basically, eBay allows users to specify two variations of their choice, for example size and color. Each variation will have different data, for example: Color: red, green Size: 12, 9 Then it gets a bit confusing, for example: quantity for color red, size 12: 15 quantity for color red, size 9: 12 quantity for color green, size 12: 20 quantity for color green, size 9: 59 The user will have to specify the quantity for each mixture of variation, first variation takes precedence. How can I apply this in database level? Currently I'm just producing a list like so: [color blue,size = 12,Quantity = 24,Price = 299,size = 23,Quantity = 43,Price = 298] Planning to store the list as string in a field, and using JSON to rebuild it. The problem is, unnecessary processing will be required for every request. For example if Quantity decreases, then I can't just edit a field, I would have to use flags to find right Quantity from the list (unnecessary processing), and make appropriate changes to the list, and then store it again. Looking for an alternative approach? I can't create fields for variations because they're … -
Django Framework: Python function in view.py unable to find the json file
I am trying to write into a json file through a python function. The python function dumps the python data structure into a json file using json.dumps funtion. The file gets created as well as the python data structure in form of json object is present in the json file but when javascript function present inside the python function tries to open and read the object it fails. I get the following error: Not found file_name.json I am pretty sure that the file is indeed present. def func(request): arr = [[]] message = '' arr[0].append('Hello') arr[0].append('There') arr.append([]) arr[1].append('Good') arr[1].append('Morning') arr[1].append('!') message = message + '<html><head><script type="text/javascript" src="outputjson.js"></script><script>function Hello(){alert(hello[1]);}</script></head>' with open('outputjson.js', 'w') as fo: jsonp_structure = "hello = "+json.dumps(arr)+" " fo.write(jsonp_structure) message = message + '<body><h1>This is shit and you know it</h1><input value="Click Bro" type="button" onclick="Hello();"></input></body></html>' return HttpResponse(message) I get the error stating: Not found: outputjson.js Do I need to explicitly tell Django where to look for the file ? -
error while submitting form in django
I can't get the following problem solved even with the answers to related questions on this site. At the moment I am doing the Django tutorial but got stuck with the form. The following error, that i get whem submitting a favorite song, is bugging me: OperationalError at /music/2/ {% for song in album.song_set.all %}Line 10 and googled looking for an answer but i can't seem to fix it. I appreciate any help. <form action="{% url 'music:favorite' album.id %}" method = "post"> {% csrf_token %} {% for song in album.song_set.all %} <input type = "radio" id = "song{{ forloop.counter }}" name = "song" value = "{{ song_id }}" /> <label for="song{{ forloop.counter }}"> {{ song.song_title }} {% if song.is_favorite %} <img src="http://http://i.imgur.com/b9b13Rd.png" /> {% endif %} </label><br> {% endfor %} <input type="submit" value="Favorite"> </form> enter code here def favorite(request, album_id): album = get_object_or_404(Album, pk = album_id) try: selected_song = album.song_set.get(pk= int(request.POST['song'])) except (KeyError, Song.DoesNotExist): return render(request, 'music/detail.html', { 'album':album, 'error_message': "You didn't select a valid song" }) else: selected_song.is_favorite = True selected_song.save() return render(request, 'music/detail.html', {'album': album}) -
How to Http post to django server from android?
I am trying to send post request to my django APi from but It does not give any error it works fine but still django does not recieve any data. My view goes like this. def add(request): if request.method == "POST": form = bookForm(request.POST) if form.is_valid(): data = form.save(commit=False) data.save() return redirect('/books') else: form = bookForm return render(request, 'book_edit.html', {'form': form}) And my Http post method is. try{ Log.w("this","Started"); HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("http://vidu171.pythonanywhere.com/books/add"); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); nameValuePairs.add(new BasicNameValuePair("title", params[0])); nameValuePairs.add(new BasicNameValuePair("author","vidu")); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = httpclient.execute(httppost); Log.w("htt response",response.toString()); }catch(Exception e){ Log.e("log_tag", "Error in http connection "+e.toString()); } I have given the permission the url to the form is http://vidu171.pythonanywhere.com/books/add . Thanks in advance -
How to print out pdf file when button clicked?
I want to print out pdf file without download it, like I have button print when I click it, my pdf file opened into new tab, where I can see my pdf file and two button like print and close. How to do it? Are there any suggestions? -
Unbound django form in view
I can't seem to figure out why I get the following error after submitting login form: <bound method BaseForm.non_field_errors of <LoginForm bound=False, valid=False, fields=(username;password)>> here's my code for the view: def accounts(request, **kwargs): login_form = LoginForm(request.POST or None) reg_form = RegistrationForm(request.POST or None) if request.method == "POST": if(kwargs["active_tab"] == "login"): if (login_form.is_valid()): username = login_form.cleaned_data.get('username') password1 = login_form.cleaned_data.get('password1') user = authenticate(username=username, password=password1) login(request, user) return redirect('/dashboard/') elif(kwargs["active_tab"] == "register"): if (reg_form.is_valid()): reg_form.save() username = reg_form.cleaned_data.get('username') password1 = reg_form.cleaned_data.get('password1') user = authenticate(username=username, password=password1) login(request, user) return redirect('/dashboard/') return render(request, 'login.html', dict({'regform':reg_form, "loginform":login_form}, **kwargs)) Shouldn't it be bound since both forms have request.POST passed as an argument? -
Django create static and template directories when using startproject/startapp
Is it possible to modify Django so the templates and static directories (including any subdirectories for existing apps) are created automatically? I also want the settings.py to be updated to reflect any changes. That is, to have the lines: STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] TEMPLATES = [ { ... 'DIRS': [os.path.join(BASE_DIR, 'templates').replace('\\', '/')], ... }, ] and possibly a flag when running ./manage.py startapp to add the appname to INSTALLED_APPS. I find I'm writing the same boilerplate code for each project and I feel like it could be easily streamlined. Of course there might be a good reason why these things have been left out of Django. I assume that it's because the locations of those directories are only convention and they want to allow devs to easily move them if needed, but I've never needed to do this. Ideally I'm looking for a fork of Django that would do this, so I wouldn't have to maintain it myself. I'm using Ubuntu, so I think I could alias the command to do those things, but I don't want to spend time doing that if someone else has already done it better. -
Unable to use OAUTH2 Django
I'm following this tutorial https://django-oauth-toolkit.readthedocs.io/en/latest/tutorial/tutorial_01.html, and unfortunately I'm stuck in this part "Point your browser to //localhost:8000/o/applications/ and add an Application instance" unfortunately when I go to that URL, I get the following error and redirected to "localhost:8000/accounts/login/?next=/o/applications/" and page not found error, is there something I'm doing wrong? -
How can I increase the capacity of PostGreSQL text indexing?
I want to do indexing on Django text field which has more than 60000 characters in some rows. Right now I am having the following error (for a much smaller row): django.db.utils.OperationalError: index row requires 8368 bytes, maximum size is 8191 Is there a limit on the size for indexing in PostGreSQL? -
allowed_host changes not effective
I've got an address say example.com and have added it to the allowed_hosts list. But when I access the site I get ALLOWED_HOSTS ['127.0.0.1', '::1', '178.XX.XX.XXX', 'xx80::xx81:xxx:xx3x:x12x%eth0'] in the debug error page, while the actual settings.py file reads ['178.XX.XX.XXX','example.com']. I figured the changes to settings.py aren't registered as I can remove 178.XX.XX.XXX from the list and still access the site (after clearing the browser cache) I've restarted nginx, gunicorn and the whole server to no avail. The whole thing is set up on ubuntu 16.04 running django 1.8 and using nginx and gunicorn. Any ideas where this override of allowed_hosts could be coming from? -
Convert pickled value
One of the tables of my database in Django contains the dictionary below. When dumping the table as .csv and looking at the column where the dict is stored, I get some awkward results. {""my_key"": {""__pickled__"":""gANjbnVtcHkuY29yZS5tdWx0aWFycmF5CnNjYWxhcgpxAGNudW1weQpkdHlwZQpxAVgCAAAAaThxAksASwGHcQNScQQoSwNYAQAAADxxBU5OTkr/////Sv////9LAHRxBmJDCAgAAAAAAAAAcQeGcQhScQku\n""} } In Python, the following yields an error asking for a specific encoding. pickle.loads(bytes(gANjbnVtcHkuY29yZS5tdWx0aWFycmF5CnNjYWxhcgpxAGNudW1weQpkdHlwZQpxAVgCAAAAaThxAksASwGHcQNScQQoSwNYAQAAADxxBU5OTkr/////Sv////9LAHRxBmJDCAgAAAAAAAAAcQeGcQhScQku\n)) The result should be an integer value smaller than 10. How do I decode the pickled value? -
Upload a ZIP file to Django Server with the fetch API (encoding issues)
I'm using the fetch API and the FileReader().readAsText(...) object to upload a files to a Django Server. The code works for GeoJSON files but ZIP files aren't being saved properly on the server. Python forces me to (re)encode zip files to UTF8 before writing the data to a file but the file expands to double its size after encoding and its not possible to unzip the file. This is the client fetch code let reader = new FileReader(); reader.onload = (function(f){ return function(filedata){ uploadDataWithFetch(filedata) } })(file,encoding) return (reader.readAsText(file,'utf-8')) This is the (Django) server code to save the file def save_file(file_data,dest_path): file_data_encoded = file_data.encode('utf8') with open(dest_path,'wb') as fd: fd.write(file_data_encoded) -
unique column value per row
I find it best to use an example, so here we go: Say I have a table with chores and a table with a weekly schedule like this: CHORES: |----+---------------+----------+-------| | id | name | type | hours | |----+---------------+----------+-------| | 1 | clean kitchen | cleaning | 4 | |----+---------------+----------+-------| | 2 | clean toilet | cleaning | 3 | etc SCHEDULE: |------+---------------+---------------+-----| | week | monday | tuesday | etc | |------+---------------+---------------+-----| | 1 | clean kitchen | clean toilet | etc | |------+---------------+---------------+-----| | 2 | clean toilet | clean kitchen | etc | etc I want to make sure that for one week, you can't have duplicate cells, so this wouldn't be allowed: SCHEDULE: |------+---------------+--------------+-----| | week | monday | tuesday | etc | |------+---------------+--------------+-----| | 1 | clean toilet | clean toilet | etc | etc What would I have to do in my models.py to get this behaviour? -
Why create an API for a website?
I am planning to make a website. I have heard that you should create a RESTful API for it first. I researched on why to do this and mostly every website said things that revolved around, it would make it easier if you make apps for it on various different platforms. I am not planning to make an app for my website, so should I still make an API for it.(If it makes any difference, my website will be built with Django and Python) -
Django ForeignKey object does not get saved when using UpdateView with InlineFormSet
I have a hard time proceeding with a special case. There's an UpdateView which I use in order to serve a standard form (a ModelForm specifically) and an inline formset. The views.py code looks like this: class Contract(LoginRequiredMixin, UpdateView): template_name = '/path/to/template.html' model = ContractModel form_class = ContractModelForm success_url = reverse_lazy('contract-list') def get_context_data(self, **kwargs): context = super(ContractVerificationUpdate, self).get_context_data(**kwargs) if self.request.POST: context['student_form'] = StudentsFormSet(self.request.POST) else: context['student_form'] = StudentsFormSet(instance=self.object) return context def form_valid(self, form): self.object = form.save(commit=False) context = self.get_context_data() student_form = context['student_form'] if student_form.is_valid(): self.object = form.save() student_form.instance = self.object student_form.save() return HttpResponseRedirect(self.get_success_url()) else: return self.render_to_response(self.get_context_data(form=form)) When I open up this update view, the student's assigned on this contract model are all shown as expected, but when I edit something on them (for example I edit a student's name), and I hit the save button, it doesn't get saved. With my debugger I've confirmed that it reaches the line student_form.save(), which should update the object I guess, though it doesn't save itself. What's wrong with this? It's possible that it's very easy to solve but my mind is really stuck at this point! Any kind of help or suggestions is greatly welcome! Thank you in advance! -
Does Django support alternate keys in DB models?
In addition to my primary key, I would like to set up one or more alternate keys in my model in Django. For example, perhaps the primary key in the customer table is a Django-generated ID. But, I may want another, alternate key to ensure that no customer-name, insert-date combination is duplicated. Is there a way to do this in Django or must I go out and do this in the database? Thanks! -
apache knocking over django devserver
Is it possible for an Apache install to prevent Django's inbuilt devserver from working? I have a situation where if I run Apache with wsgi, a test website works, but running the same server with runserver 0.0.0.0:8080 gives ERR_CONNECTION_REFUSED from local or remote (even with the apache2 service stopped). My knowledge of web details is hazy, I don't even know where to troubleshoot this problem - the devserver runs (runserver prints as expected and doesn't give any errors) but never receives a request, I have nothing in iptables. -
Django output json serialization
I am using Django REST framework. I am using Panda dataframe for data transformation and returning json object. However, I am getting errors while serializing the object and send it back in the Response. The json object is not queryset but dataframe. Any help? Thanks in advance. Regards, Seema -
django wagtail page not found when i don't use "127.0.0.1:8000"
I have added the following to my settings.py ALLOWED_HOSTS = ['0.0.0.0','127.0.0.1','192.168.0.05'] My url.py urlpatterns = [ url(r'^django-admin/', include(admin.site.urls)), url(r'^admin/', include(wagtailadmin_urls)), url(r'^documents/', include(wagtaildocs_urls)), #url(r'^search/$', search_views.search, name='search'), # For anything not caught by a more specific rule above, hand over to # Wagtail's page serving mechanism. This should be the last pattern in # the list: #url(r'', include(wagtail_urls)), # Alternatively, if you want Wagtail pages to be served from a subpath # of your site, rather than the site root: # url(r'^pages/', renders(wagtail_urls)), url(r'^i18n/', include('django.conf.urls.i18n')), ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += i18n_patterns( # These URLs will have /<language_code>/ appended to the beginning url(r'^search/$', search_views.search, name='search'), url(r'', include(wagtail_urls)), #url(r'^$', include(wagtail_urls)), ) The dilema is when I do "http://127.0.0.1:8000/en" it works just fine however when I do "http://192.168.0.5:8000/en/" from my mobile phone on the same lan or even from the laptop its hosted on I keep getting "Page not found (404)". What would cause such behavior did I overlook something in my url.py. I have tried running it as follows : python manage.py runserver 192.168.0.13:8000 python manage.py runserver 0.0.0.0:8000 Non of which helps. I know its not a firewall issue as the page not found is as a result of the django service responding. -
Is there a way to add data to the SQLite DB provided with Django with another python script?
Is there a way to run a python script that will add data to this SQLite DB then? I mean, a completely separate .py file that I will run in the shell, doing python thefile.py in an SSH connection? Of course, this file will be on the same server as the whole Django project. This way, I can easily access the data from the DB from my Django project, and display it the way I want in a pretty HTML/CSS web page. Thanks