Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python: Django Post Response
I've a problem regarding response upon post request, I am doing a post request, then I am waiting for the response, where I am returning the serialized.data json form, but the problem is that I am not getting any response! When I do more than one request such as a 50 requests I'll get only one response! So I think it is a buffer problem, isn't it please help me find a way to get out of my problem! Thanks in advance... -
Django - invalid literal for int() with base 10: ',' when passing an array
I have the following script that passes a jQuery array in the url: jQuery(document).ready(function($) { $("#continue").click(function() { var selected = $("#meds").bootgrid("getSelectedRows"); var url = "{% url 'meds:prescription' 'test' %}"; url = url.replace('test', selected); window.location = url; }); }); and the following view: class PrescriptionView(generic.ListView): template_name = 'meds/prescription.html' context_object_name = 'meds' model = Medicament def get_queryset(self): return Medicament.objects.filter(id__in=self.kwargs['selected']) The selected array looks something like [3, 4] and the url passed looks like http://127.0.0.1:8000/prescription/3,4/ I keep getting the error : ValueError at /prescription/3,4/ invalid literal for int() with base 10: ',' I just assumed that the array passed will be treated as a python list so I used id__in in the filter so I can compare the ids to the items of the list/array. -
Why does resending a valid POST request cause CSRF failure?
In an academic task involving Django forms, the instructor made clear he required strict validation of POST data. For this reason, to test if my validation is correct, I launched Django development server, filled a form in my browser, opened the Network tab of Firefox Developer Tools, highlighted the POST request that was associated with this form and tried resending it, changing some data to invalid values but without touching csrfmiddlewaretoken or the csrftoken cookie. I got CSRF error. This time, I tried resending a valid POST request without changing anything. CSRF error again. At the same time, resending a valid request by reloading the page and getting past the warning: To display this page, Firefox must send information that will repeat any action (such as a search or order confirmation) that was performed earlier. works just fine. I do not understand. Why does sending a raw POST request cause CSRF errors even if it includes the correct value of csrfmiddlewaretoken (manually confirmed by inspecting page source) and the correct csrftoken cookie (manually confirmed by inspecting the value of this cookie as set by the server in the latest response)? What does reloading a page do besides resending the last … -
missing data(4 levels deep) SQLlite vs Postgres
In my django template I display value (4 levels deep) {{ leaseterm.lease.unit.number }} And the value gets displayed When I use SqlLite but after I have migrated to postgres (on Heroku) no value is displayed. How can I solve it? -
Django error redirecting
Cannot assign "HttpResponseRedirect status_code=302, "text/html; charset=utf-8", url="/carts/"": "Order.cart" must be a "Carts" instance". what does this error mean in django? New to django please help -
Django can't access request multiple times
i have view for editing user profile with ajax, i'm checking the request type, if its post just get Json data with request.body. but Django is giving me an error: 'You cannot access body after reading from request's data stream'. apparently i can only access request data one, so how do i check request type before reading the body. here is simplified code def edit_profile(request): if request.method == 'POST': # reading request for first time data_str = request.body.decode('utf-8') # second time data_json = json.loads(json_str) -
Django rest_social_auth log in. What to do with facebook token?
I am using django-rest-social-auth package to allow users authenticate in my Django rest app. I was able to retrieve a token from facebook for an user. Now, I don't know how to use that token. I am trying to access an endpoint that requires logged in users, but I see accesses only as anonymous user when I debug. I've been googleing this issue and tried a lot of different methods (different cookies, url params, etc.). This is my particular case: views.py @login_required def home(request): return render(request, 'home.html') I obtained my token calling http://localhost:8000/api/login/social/token/ (I was following the django-rest-social-auth readme) and it looks like: {"token": "4571b2dce1f3abec34b28a4c7bd981c248a30698"} I have that token linked with my user and I can see it in my admin (Home › Auth Token › Tokens) If I delete the @login_required I can access home without any issue. How can I send a request via postman to access that resource using my token? -
Django Heroku Application Error. Whats wrongs?
I am getting an application error while running my django app on heroku. Here are the results from heroku logs: 2017-04-08T17:24:50.000000+00:00 app[api]: Build started by user anmol.gulati9513@gmail.com 2017-04-08T17:25:11.732420+00:00 app[api]: Deploy f4ef15f by user anmol.gulati9513@gmail.com 2017-04-08T17:25:11.732420+00:00 app[api]: Release v10 created by user anmol.gulati9513@gmail.com 2017-04-08T17:25:11.987358+00:00 app[api]: Release v10 created by user anmol.gulati9513@gmail.com 2017-04-08T17:24:50.000000+00:00 app[api]: Build succeeded 2017-04-08T17:25:12.354075+00:00 heroku[web.1]: State changed from crashed to starting 2017-04-08T17:25:18.683488+00:00 heroku[web.1]: Starting process with command `gunicorn --pythonpath expense_manager expense_manager.wsgi --log-file -` 2017-04-08T17:25:20.881565+00:00 heroku[web.1]: State changed from crashed to starting 2017-04-08T17:25:20.880602+00:00 heroku[web.1]: State changed from starting to crashed 2017-04-08T17:25:20.868145+00:00 heroku[web.1]: Process exited with status 3 2017-04-08T17:25:20.728492+00:00 app[web.1]: [2017-04-08 17:25:20 +0000] [4] [INFO] Starting gunicorn 19.7.1 2017-04-08T17:25:20.729017+00:00 app[web.1]: [2017-04-08 17:25:20 +0000] [4] [INFO] Listening at: http://0.0.0.0:38551 (4) 2017-04-08T17:25:20.729116+00:00 app[web.1]: [2017-04-08 17:25:20 +0000] [4] [INFO] Using worker: sync 2017-04-08T17:25:20.732466+00:00 app[web.1]: [2017-04-08 17:25:20 +0000] [8] [INFO] Booting worker with pid: 8 2017-04-08T17:25:20.736689+00:00 app[web.1]: [2017-04-08 17:25:20 +0000] [8] [ERROR] Exception in worker process 2017-04-08T17:25:20.736693+00:00 app[web.1]: Traceback (most recent call last): 2017-04-08T17:25:20.736694+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.5/site-packages/gunicorn/arbiter.py", line 578, in spawn_worker 2017-04-08T17:25:20.736695+00:00 app[web.1]: worker.init_process() 2017-04-08T17:25:20.736696+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.5/site-packages/gunicorn/workers/base.py", line 126, in init_process 2017-04-08T17:25:20.736697+00:00 app[web.1]: self.load_wsgi() 2017-04-08T17:25:20.736699+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.5/site-packages/gunicorn/app/base.py", line 67, in wsgi 2017-04-08T17:25:20.736697+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.5/site-packages/gunicorn/workers/base.py", line 135, in load_wsgi 2017-04-08T17:25:20.736698+00:00 app[web.1]: self.wsgi = … -
how to access django object in ajax
I want to access django object in ajax code. But i am unable to access it. please guide me. my server code def attendance_table(request): if request.is_ajax(): try: CollegeCode = request.session.get('collegeCode') academicyear = logic.academicYearCal() eventquery = "SELECT e.EventId , e.EventLocation,e. EventStartDate,e.EventEndDate,e.EventHours,em.EventCode as EC ,em.EventName from Events " events = models.Events.objects.raw(eventquery, [academicyear, '1', CollegeCode]) context = {} events = serializers.serialize('json', events) context['events'] = events return JsonResponse(data=context) except Exception as e: return JsonResponse(data={'error':'error'}) Ajax Code $.ajax({ url:url, type:'GET', dataType:'JSON', success:function(response) { console.log(response.events); } }); in browser console the output is [{"model": "sample.events", "pk": "E22", "fields": {"eventcode": "1", "collegecode": "KIT", "eventopenflag": "1", "eventstartdate": "2017-07-23", "eventenddate": "2017-07-22", "eventlocation": "Shivaji memorials , kolhapur", "academicyear": "2017", "eventlevel": 5, "eventhours": 0}}] correct me please.. -
Opening a new browser tab invalidates Django's CSRF token, preventing form submission
Opening a Django 1.10 application in a second browser tab refreshes the CSRF token. This breaks all forms in the first tab -- i.e., previously opened forms can no longer be submitted because the old CSRF token is now invalid. How do I avoid this behavior? Step-by-step example: User is viewing a form in Tab A. User opens the application in Tab B. User returns to Tab A and attempts to submit the form. Error: Forbidden (403). CSRF verification failed. Request aborted. Some details: I would really like to permit multi-tab browsing in the application. The Django 1.10 release notes document a change to the CSRF mechanism: To protect against BREACH attacks, the CSRF protection mechanism now changes the form token value on every request (while keeping an invariant secret which can be used to validate the different tokens). Django's 1.9 CSRF documentation has a really good description of the usability problem. This paragraph has been removed in the 1.10 CSRF documentation, but it seems to describe the exact problem I'm encountering: Why not use a new token for each request? Generating a new token for each request is problematic from a UI perspective because it invalidates all previous forms. … -
How to login using django
Trying to login with django but I'm getting and IO error File "/home/samuel/Documents/code/revamp/gallery/views.py" in login_ajax 26. login(request, user) Exception Type: IOError at /ajax_login Exception Value: [Errno 21] Is a directory: u'/usr/local/lib/python2.7/dist-packages/django/contrib/admin/templates/admin' Request information: GET: No GET data here's the code from django.contrib.auth import authenticate, login def login_ajax(request): response = {'status': None} if request.method == 'POST': data = json.loads(request.body) user, password = data['user'], data['password'] user = authenticate(username=user, password=password) if user is not None: login(request, user) return HttpResponseRedirect('/') this way i can log in a user in using ajax. -
Django: Ignored `quotes: none` at 38:5, invalid value
In my server logs, there are a couple of entries saying: Ignored quotes: none at 38:5, invalid value I see the same output in the console when I run tests. Where is it coming from and how to fix it? -
Manually enter a value in django model form
I am using django's default User class. I have made a UserImage class to store users' images. class UserImage(models.Model): user_id = models.ForeignKey(User, blank=False) image_url = models.ImageField(upload_to='users/images/') In the ImageUploadForm form, I only want user to chose the image_url, and set user_id to currently authenticated user's id. This is the image upload form, class ImageUploadForm(forms.ModelForm): class Meta: model = UserImage fields = {'image_url'} Normally I save model forms like this, form = ProjectForm(request.POST or None, instance=project) if request.POST and form.is_valid(): form.save() return HttpResponseRedirect(reverse('projects:project_dashboard', kwargs={'project_id': project_id})) So how do I include the user_id field here? Should I make this a hidden field in the view? Or is there a better choice? -
CSS Not Rendering with Apache, Django, and mod_wsgi
I'm working dilligently to get Apache 2.4.7 to serve a Django 1.8.17 application using mod_wsgi 4.5.15 with Python 3.5.3 as a virtual environment. This is the only virtual environment I have on the machine (Linux Mint 17.3). All the dynamic content is coming through, but not all of the static content. I have several apps in my project and when I run collectstatic, it appears to be placing them all in a single correct location like it's supposed to. I checked them all and they are all there. I have given all files in that location permissions using "sudo chown -R www-data:www-data ... ". I have modified my Apache virtual host file to add alias's that point to my "media" and "static" directories using absolute paths. When that didn't work, I tinkered with settings.py and tried changing the dynamic code that determines STATIC_ROOT and STATICFILES_DIRS to absolute paths (that didn't work either, I changed them back) home/magic-rat/ | |_____+virtualenvs | | | |+ektropy_project | | | |+lib | | | |+python3.5 | | | |+site_packages | |_____+ektropy_project | |-manage.py |+static (for pinax) | | | |+dist | |+src | |+ektropy_project | |-wsgi.py | |+site_media | |+media STATIC HERE=> |+static | … -
Django - 'TemporaryFile' object has no attribute '_committed'
I want to save an image I pull from Google Places API in a Django ImageField. So I prepared the URL - the HTTP response for which is an image: city_image_url = ('https://maps.googleapis.com/maps/api/place/photo' '?maxwidth=%s' '&photoreference=%s' '&key=%s') % (maxwidth, city_image_ref, GoogleKey) I call it and save it in a variable (city_image) with urllib.request.urlopen(city_image_url) as response: city_image = NamedTemporaryFile() city_image.write(response.read()) city_image.flush() Then I create a City object and save it in its ImageField: created_city = City.objects.get_or_create(city_id=city_id)[0] created_city.city_image = city_image created_city.save() But I receive this error: Traceback (most recent call last): File "C:\Users\bnbih\Djangos\excurj_proj\population_script.py", line 74, in populate() File "C:\Users\bnbih\Djangos\excurj_proj\population_script.py", line 70, in populate created_city.save() File "C:\Users\bnbih\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\base.py", line 796, in save force_update=force_update, update_fields=update_fields) File "C:\Users\bnbih\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\base.py", line 824, in save_base updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) File "C:\Users\bnbih\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\base.py", line 886, in _save_table for f in non_pks] File "C:\Users\bnbih\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\base.py", line 886, in for f in non_pks] File "C:\Users\bnbih\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\fields\files.py", line 290, in pre_save if file and not file._committed: AttributeError: 'TemporaryFile' object has no attribute '_committed' -
Django join tables without foreign key using extra()
I need to perform a join operation on 2 tables in Django without an explicit foreign key. I've managed to do this on a single instance but the query fails if multiple objects are returned with the error more than one row returned by a subquery used as an expression django Does anyone have any tips on how I can perform this operation on the queryset? I have a manager method that returns the following: return self.extra( tables=('my_table_name',), where=('my_table_name.column=model_table.column',), select={ 'col1': 'SELECT col1 FROM my_table_name', 'col2': 'SELECT col2 FROM my_table_name' } ) -
Log user in on subdomain with Django
I'm building a web app with Django, using django-tenant-schemas. I'm trying to accomplish the following: User registers on the main domain, example.com In the background, a tenant is created at test.example.com and a user for this tenant The user is redirected to his new subdomain, test.example, and is automatically logged in I can't figure out how to log the user in. This is the registration view: def register(request): if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): webshop = Tenant() webshop.domain_url = form.cleaned_data['name'] + '.localhost' webshop.schema_name = form.cleaned_data['name'] webshop.save() with schema_context(form.cleaned_data['name']): f = form.cleaned_data user = CustomUser.objects.create_user(f['email'], f['password'], f['user_name']) send_registration_confirmation(user, form.cleaned_data['name']) redirect = 'http://' + form.cleaned_data['name'] + '.localhost:8000' return HttpResponseRedirect(redirect) else: form = RegistrationForm() return render(request, 'register.html', {'form': form,}) If I use the authenticate and login functions from Django, the user gets logged in on the main domain, but not on the subdomain. -
Django Forbidden (CSRF cookie not set.)
I was wondering what's up with the CSRF Cookie not set error that Django throws at me all the time. I created a view (see below) that is a callback for a payment. I have no influence of what is being sent to that view. I have checked other posts on StackOverflow, but I don't think any apply to me. Most of them can just implement a csrf protection into their forms, csrf_exempt their views, or they use rest_framework. class PaymentWebhook(View): def post(self, request, *args, **kwargs): # ... Now, I'm getting this error everytime when I do nothing about this function: Forbidden (CSRF cookie not set.): /payment/webhook Since this is about payments, can I just csrf_exempt this, or would that just open a security hole? By the way, I have even tried putting an exempt on this function, but it still throws that error. Any suggestions? -
Django form is adding characters when I am editing details
Here is how my form is set up (all the fields are the same): class AddColourForm(forms.Form): colour = forms.CharField( widget=TextInput(attrs={'class':'form-control'}), max_length=100, required=False, label = "Colour:", ) Here is my view: if form.is_valid(): selected_colour.code = form.cleaned_data['code'], selected_colour.name = form.cleaned_data['colour'], selected_colour.save() Here is what happens when it goes into the db: (u'red',) (u'#ff0000',) I have tried adding unicode() wrappers around the cleaned data before saving but that isn't working. Does anyone have any other suggestions? -
Get specific user information in Django template
i need some help, i've extended the custom user model but for some reason if in a template i get the needed field it doesn't show up anything. views.py: def index(request): utente = User.objects.filter(username__in=["user"]) return render(request,"blog/index.html", {'users' : utente}) html: {% for utente in users %} <img class="img-circle center-block" src="{{ utente.img.url }}" width="140" height="140"> <h2 class="text-center">{{ utente.get_full_name }}</h2> <p class="text-center">{{ utente.bio }}</p> {% endfor %} With this code i can only get the name with the "get_full_name". Any suggestions? -
assigning category to a post
hey I have a model like this class Categorys(models.Model): title = models.CharField(max_length=255,blank=True, verbose_name="Title") def __str__(self): return self.title class Post(models.Model): category = models.ForeignKey(Categorys,choices=settings.CATEGORY,blank=True,null=True, verbose_name="Category") when I try to add a category I get the following error: Cannot assign "u'design'": "Post.category" must be a "Categorys" instance. Can anybody tell me whats up? -
django form custom attrs widget imagefield
I have a model Prova: class Prova(models.Model): id = models.AutoField(primary_key=True) codice= models.TextField(blank=True, null=True) foto = models.ImageField(upload_to='stati/uploads/', blank=True) and this is the form: class ProvaForm(forms.ModelForm): class Meta: model = models.Prova fields = ('codice','foto',) widgets = { 'codice': forms.Textarea(attrs={'rows':1, 'cols':15, 'autofocus':'autofocus', }), 'foto': forms.ClearableFileInput(attrs={'type': 'camera'}), } the customization of the codice field is working, but not the foto. I want to change the type of html input from 'file' to 'camera'. Tried also ImageField and 'foto': forms.FileInput(attrs={'type': 'camera'}), What am I missing? -
KeyError in Django form kwargs
def user_info(request, template_name='social/retrieve_user_data.html', username=None): user = User.objects.get(username=username) if request.method == 'POST': form = UserInfoForm(request.POST, user) print(form.is_valid()) if form.is_valid(): form.save() else: print('not post') form = UserInfoForm(user) return render_to_response(template_name, RequestContext(request, { 'form': form, })) class UserInfoForm(forms.Form): def __init__(self,*args,**kwargs): self.user = kwargs.pop('user') super(UserInfoForm,self).__init__(*args,**kwargs) This is producing a KeyError with exception value u'user'. What is wrong here? In both cases, form is initialized with a valid value of user. Why am I getting a keyerror> -
Hidden file field doesn't save into database
I'm trying to unhide initially hidden media filefield in form (type="hidden" > type="file") using jQuery so user can upload a file after clicking a button. The unhiding portion works flawlessly but despite file going in POST.FILES (I checked by print(request.FILES) at the beginning of the view) it's not saved into the database. When I comment out widgets={'media': HiddenInput,} in forms.py and the filefield is visible from the beginning the file is saved to database without problems. I guessing it could be some validation problem (django thinks it should be hidden field but gets file???). How can I solve this problem so the file is saved to database from unhidden file field? -
Failing test of image upload using the Django Rest Framework
The following test should return 201 created. It is failing due to image1 and image2 being empty/null I believe which shouldn't be the case! As you can see I generate an image for the payload but this doesn't seem to work, why? class PhotoTests(APITestCase): def setUp(self): """ Setup runs before every test respectively. """ self.api_factory = APIClient() self.test_session = ApplicationFactory.create() self.test_access = ApplicationTokenFactory.create(user=self.test_session.user, application=self.test_session) self.tmp_file = tempfile.NamedTemporaryFile(suffix='.jpg') image = Image.new('RGB', (100, 100)) image.save(self.tmp_file.name) def test_post_photo(self): url = reverse('photo_url') payload = { "image1": self.tmp_file, "image2": self.tmp_file, } print(self.tmp_file) self.api_factory.credentials(Authorization='Bearer ' + self.test_access.token) response = self.api_factory.post(url, payload, format='multipart') print(response.data) self.assertEqual(response.status_code, status.HTTP_201_CREATED) Error: self.assertEqual(response.status_code, status.HTTP_201_CREATED) AssertionError: 400 != 201 -------------------- >> begin captured stdout << --------------------- <tempfile._TemporaryFileWrapper object at 0x10a4a8748> {'image1': ['The submitted file is empty.'], 'image1': ['The submitted file is empty.']}