Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to test file upload in Django rest framework using PUT?
I would like to write a unit test for a view on a Django REST Framework application. The test should upload a file using PUT, in essence equivalent to http -a malkarouri PUT http://localhost:8000/data-packages/upload/ka @tmp/hello.py The code I have written so far is factory = APIRequestFactory() request = factory.put( '/data-packages/upload/ka', data, content_type='application/octet-stream', content_disposition="attachment; filename=data.dump") force_authenticate(request, user) view = PackageView.as_view() response = view(request, "k.py") which, obviously, does not upload a file. The specific error when running the test is 400: {u'detail': u'Missing filename. Request should include a Content-Disposition header with a filename parameter.'} Notably, I am using a request factory to test the view rather than a full client. That is what makes solutions such as the one in this question not work for me. What is the correct way to set the content disposition header? -
jfu upload file.error is always true in mozilla firefox?
views.py if upload_msg == "KeyError": file_dict['error'] = "Invalid File format" else: file_dict['error'] = False jfu_template.html `{{ JQ_OPEN }} if (file.error) { {{ JQ_CLOSE }} <div class="col-md-12" style="width: 130%;"> <div id="error" class="alert alert-danger"> <!--<span class="label label-danger" id="error">Error</span>--> {{ JQ_OPEN }}=file.error{{ JQ_CLOSE }} </div> </div> {{ JQ_OPEN }} } {{ JQ_CLOSE }}` In the above html file (file.error) is always True in Mozilla Firefox and it works well in chrome and chromium browser. What is the issue with jfu ? -
Render the first few items of a queryset, and then load more items via ajax
I want to render the first 5 comments of a Comment queryset. But then I want to be able to load the next 20 comments when a user clicks a button. views def article(request): new_comments_list = Comment.objects.all()[:5] context = { 'comment_list': new_comments_list, } return render(request, 'article.html', context) comments.html {% for i in comment_list %} {{ i }} {% endfor %} <p class="more_comments">more comments</p> #click this to load 20 more comments So as you can see in my views I only get the first 5 comments. So by doing this, is there any viable way to load the next 20 items of the queryset (via AJAX)? Or alternatively, should I initially load the whole queryset, but only show the first 5 (hide the rest through jquery)? And then load the next 20 comments through jquery? Or is that not viable? Appreciate recommendations. -
Django framework: Saving a ManyToMany Field in a form using save_m2m() method throws error
I'm trying to build a cookbook web-app with django. The recipies you can create can be in several cookbooks you can create. That's why 'cookbooks' is a ManyToMany field in recipies. By creating a recipe it shows multiple checkboxes where you can check several cookbooks. Saving this throws an error saying: ValueError: invalid literal for int() with base 10: 'a' in my views.py: def create_recipe(request): if not request.user.is_authenticated(): return render(request, 'cookbook/login.html') else: form = RecipeForm(request.POST or None, request.FILES or None) if form.is_valid(): recipe = form.save(commit=False) recipe.user = request.user recipe.picture = request.FILES['picture'] file_type = recipe.picture.url.split('.')[-1] file_type = file_type.lower() if file_type not in IMAGE_FILE_TYPES: context = { 'recipe': recipe, 'form': form, 'error_message': 'Image file must be PNG, JPG, or JPEG', } return render(request, 'cookbook/create_recipe.html', context) recipe.save() form.save_m2m() cookbook = Cookbook.objects.filter(user=request.user) return render(request, 'cookbook/index.html', {'cookbook': cookbook}) context = { "form": form, } return render(request, 'cookbook/create_recipe.html', context) in my forms.py: class RecipeForm(forms.ModelForm): directions = forms.CharField(widget=forms.Textarea) ingredients = forms.CharField(widget=forms.Textarea) class Meta: model = Recipe fields = ['title', 'ingredients', 'directions', 'picture', 'cookbooks'] def __init__ (self, *args, **kwargs): super(RecipeForm, self).__init__(*args, **kwargs) self.fields["cookbooks"].widget = forms.widgets.CheckboxSelectMultiple() self.fields["cookbooks"].help_text = "" self.fields["cookbooks"].queryset = Cookbook.objects.all() -
I want to create a basic HTML5 Website with RSVP form
I want to create a basic wedding website for a close friend of mine who is getting married soon. Something responsive with an RSVP form. I intended to do it with Django as I have some experience with that, but I feel it's an overkill. Can anyone recommend something very basic/responsive and allows me to store RSVP data easily? Thanks! -
Does the 'through' argumnt in ManyToManyField in Django includes all fields?
Does the 'through' argument in ManyToManyField in Django includes all fields in the related tables? For example will Group contain all Person and Membership fileds? And also how many levels deep can 'through' relationships can be? from django.db import models class Person(models.Model): name = models.CharField(max_length=128) def __str__(self): # __unicode__ on Python 2 return self.name class Group(models.Model): name = models.CharField(max_length=128) members = models.ManyToManyField(Person, through='Membership') def __str__(self): # __unicode__ on Python 2 return self.name class Membership(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE) group = models.ForeignKey(Group, on_delete=models.CASCADE) date_joined = models.DateField() invite_reason = models.CharField(max_length=64) -
Display data in table based on time value?
I have to display data in table based on the time value. so for that i have a datatime filed which consist of date and time for that task. i would like to display data if datetime value is greater than and equal to the current time. im trying to do this in angularjs and Django rest Framework. Once the data is displayed it should be there till the user deletes it from the GUI. Hope some one can help me out . -
Django Angular saving document in Binary Field
I am trying to save some documents in database in django in BinaryField. Then get those document back from the front end. The way i store the document is given below def post(self, request, *args, **kwargs): data = request.data trade_id = data.get(u'tradeId')[0] extension = data.get(u'extension') filename = data.get(u'name') document = request.FILES.get('file') doc_read = document.read() # doc_64_encode = base64.encodestring(doc_read) # print doc_64_encode transaction = Transaction.objects.get(tr_id=trade_id) tr_file = TrFiles() tr_file.file = doc_read tr_file.file_name = filename tr_file.extension = extension tr_file.transaction = transaction tr_file.created_by = request.user tr_file.save() return Response({ 'success':True }) Now the get method to download the uploaded document def get(self, request, *args, **kwargs): doc_id = kwargs.get('document_id') doc = TrFiles.objects.get(file_id=doc_id) binary_doc = doc.file content_disposition = 'attachment; filename=%s'%doc.file_name response = HttpResponse(binascii.a2b_qp(binary_doc), content_type='application/octet-stream') response['Content-Disposition'] = content_disposition return response At Front-end I use angular ng-filesaver module to download the document function downloadTradeDocument(docId, fileName, fileType){ return transactionAPI.customGET(apiEndPoints.transaction.document+'/'+docId).then(function(res){ var data = new Blob([res], { type: fileType }); FileSaver.saveAs(data, fileName); }) } However I get a corrupted document on download! -
Django - form to create class based on type
I've got an abstract model and a load of subclasses that inherit from it. I can get a list of these subclasses but how would I go about putting them in a form so that the user can choose to create one of them? So, for instance:- class Abstract(models.Model): class Meta: abstract = True class ImplA(Abstract): pass class ImplB(Abstract): pass I need a form which enables the user to choose to create either an instance of ImplA or an instance of ImplB. -
passing a variable to all templates from views.py in django
is that possible in django to pass a variable from views.py to all html templates. for example: i have a variable "baseURL" it will be used in all templates. the reason is "baseURL" keeps on changing and if i change this in one place it should be reflected in all the places -
Can not post form data in a specific xml format using Django
I need one help. I need to save all data into a specific xml format using Django. I am explaining my code below. bmr.html: <form method="post" action=" "> {% csrf_token %} <label>location name: </label> <input name="lname"> <br> <label>Room name: </label> <input name="rname"> <br> <label>No of Seats: </label> <input type="number" name="seat"> <br> <label>Projector Screen</label> <select name="projector"> <option value="Yes">Yes</option> <option value="No">No</option> </select> <br> <label>Video conference</label> <select name="video"> <option value="Yes">Yes</option> <option value="No">No</option> </select> <br> <input type="submit" value="Submit"> </form> views.py: from __future__ import unicode_literals from django.shortcuts import render, redirect from django.contrib.auth import get_user_model, login, logout from django.contrib.auth.decorators import login_required from django.views import View from django.contrib.auth.forms import (UserCreationForm, AuthenticationForm) import xml.etree.cElementTree as ET def bmr(request): root = ET.Element("roomlist") ET.SubElement(roomlist, "location name", name="blah").text = "some value1" doc = ET.SubElement(root, "location") return render(request,'booking/bmr.html',{}) Here I need when user will click on submit button the post data will save into following xml format. I am explaining my format below. <roomlist> <location name="Bangalore"> <room id="1uy92j908u092"> <roomname> Aquarius </roomname> <noseats> 10 </noseats> <projectorscreen>yes</projectorscreen> <videoconf>yes</videoconf> </room> </location> <location name="Sydney"> <room id="324det56yuygttrgr"> <roomname> Capricorn </roomname> <noseats> 5 </noseats> <projectorscreen>no</projectorscreen> <videoconf>yes</videoconf> </room> </location> </roomlist> After save into xml file it should also display in that below part of the form in table structure. … -
Django settings: raise KeyError, raise ImproperlyConfigured or use defaults?
Django expects you to use environment variables in settings.py to adapt to multiple environments (e.g. local, heroku, AWS). I guess I should define -for instance- the username of the DB in an environment variable DB_USERNAME. How should I read it? import os DB_USERNAME = os.environ['DB_USERNAME'] DB_USERNAME = os.environ.get('DB_USERNAME') DB_USERNAME = os.environ.get('DB_USERNAME', 'john') Should I capture the KeyError and raise a ImproperlyConfigured myself? I prefer to make the app stop rather than run it using incorrect settings (defaults, people forgetting to set a variable,etc). In the case of the defaults, it might even happen that john exists both loaclly and remotely, but with different permissions. It doesn't look very robust. -
app name is appended to the table name in django
When I try to fetch data from the table, the app name is appended to the table name and displays an error. Following is my code. from models import open_cart class test(APIView): def(self,request,format=None): values = open_cart.objects.get() My app name that I have defined in installed_apps is 'MyApp'.My table name is 'open_cart'. table name in the query goes as MyApp_open_cart instead of open_cart. the error message that i get is relation "untitled_open_cart" does not exist -
View Django User table from MySQL console
I want to view Django default User table from MySQL console. I know to access from django shell or python by simply importing it. from django.contrib.auth.models import User is there a way to view it from MySQL console itself? and where it will be located? i mean in which database django user table belongs? -
How to improve django-haystack + whoosh search speed
In order to reduce the pressure on the database, I want to add a search module for a module of the site. So I integrated Django-haystack in the project. The search function has been achieved, but when the data more than 100 thousand the search speed seems a bit slow. So, I removed the index in the irrelevant field, but the performance is still not very good. Because in the production environment, there is a more than 1 million records of the table to be retrieved. So, How to improve the search speed of django-haystack? Here's main code: search_index.py class YibaoIndex(indexes.ModelSearchIndex, indexes.Indexable): area = indexes.CharField() class Meta: model = YibaoNew fields = ('name', 'area', 'dosage_form', 'related_skus_num') def index_queryset(self, using=None): return YibaoNew.objects.all().order_by('area').select_related('area') def prepare_area(self, obj): return obj.area.name api.py class YibaoSearchApi(APIView): """医保全文检索 :param :param kw 查询关键字,匹配name和factory字段 :param area 查询关键字(可选) 省份名,默认全国 :param order 查询关键字(可选) 按价格排序 1升序,2降序 """ permission_classes = (IsAuthenticated,) def get(self, request): # 权限校验 check_search_permissions(request) kw = request.GET.get('kw') area = request.GET.get('area') order = request.GET.get('order') page = int(request.GET.get('page', 1)) next_page = None queryset = None data = [] if kw: queryset = SearchQuerySet().models(YibaoNew).filter(SQ(name__contains=kw)|SQ(dosage_form__contains=kw)) else: queryset = SearchQuerySet().models(YibaoNew).filter(~SQ(area=u'全国')) if area and not area==u'全国': queryset = queryset.filter(area__contains=area) if order == '1': queryset = queryset.order_by("-price") elif … -
Store traces of http requests in Python
I want to store traces of the python code which gets executed to handle http requests. We use Python and Django. What is a trace in this context? I want to have this for all traced http requests: request.META, request.POST request.GET For every trace there are N times the stacktraces of the code execution. In the first step it would be enough to store well known python traceback as string. In the first step the value of variables does not need to be stored. The stacktraces can be created by a supervisor thread or by explicit by a method call in the source code. In the first step explicit is enough, the supervisor thread can be done later. The traces are optional and only for debugging and analyzing. They are not needed to process the http requests. How could this be solved? Is something missing to understand this question? If, yes, please leave a comment. -
Django resets connection on some requests
I stub with problem that when sending some requests to Django sever, it closes connection before time. Here is simple project on Github Here is how it works on simple POST request with no body: But when I send some binary data, ~15MB in size, Postmen displays connection error: But curl works fine curl -X POST -d "@bin/ngrok" localhost:3000/test/ I thought this is some bug in Postman, but on mobile devices it does not work too; I tried to compare request headers. I tried to toss middeware. I tryed to debug Djnago code. But I can find solution. Can you help me with this? -
How can I change home screen in the Apache HUE?
After installing and configuring the Apache HUE, I try to change home screen in the Apache HUE. Is it right way to change home screen in the Apache HUE manually? Thank you for your help in advance. /usr/local/hue/ -
Django forms.Form for add and edit
I have used forms.Form instead of ModelForm in my project as the form is little complex(means it has to deal with multiple models). Add part is completed, Now I am workin on the edit part. Is there any way which I can resuse the same form. I mean add and edit on same form? -
Downloading a file as attachment from a Django template is not working in firefox
I have a Django view (download-attachment) which returns a django.http.response.HttpResponse object. The dictionary representation of the object is: { 'reason_phrase': u'OK', '_handler_class': None, '_headers': {'content-length': ('Content-Length', '21'), 'content-type': ('Content-Type', 'text/plain'), 'content-disposition': ('Content-Disposition', 'attachment; filename="upload_file.txt"') }, '_charset': None, '_closable_objects': [], 'cookies': , 'closed': False, '_container': ['Upload to file\n'] } In template the view is rendered on click of a hyperlink: <a href="{% url "download-attachment" certificationID=certificationID fileID=attachment.id %}" download> {{attachment.name}}</a> Here certificationID and fileID are parameters of the url for the download-attachment view. In chrome, on clicking the hyperlink the file gets downloaded as an attachment with the filename given in Content-Disposition header of response. In firefox, the file download fails. Need help in making the file download work in firefox. -
How to restructure json object django rest framework?
This is my json response from Django { id:"123" latitude: "37.5111", longitude: "126.9743" }, Want output like this "123":{ latitude: "37.5111", longitude: "126.9743" } in my serializers.py class SearchSerializer(ModelSerializer): class Meta: model = IpGeo fields = [ # 'id', # 'metadata', 'latitude', 'longitude' ] in my views.py class Search(ListAPIView): queryset = IpGeo.objects.all() serializer_class = SearchSerializer -
Django + SQLite how to increase SQLite timeout when "database is locked" error occurs
I am getting the: django.db.utils.OperationalError: database table is locked error (an oh boy are there many copies of that question) all of the answers refer to this page: https://docs.djangoproject.com/en/dev/ref/databases/#database-is-locked-errorsoption and although I understand what is going on I clearly don't know Python and Django well enough to understand the instruction. The instruction is to increase the timeout like: 'OPTIONS': { # ... 'timeout': 20, # ... } but it's not so easy for a-bear-of-very-little-brain to understand exactly where that code goes. Can someone give me a bit more context? Where in my Django project do I specify these sort of options? It can't be a general Django setting can it? Timeout sounds lika a bit too general a name for that... -
how can I show the name of the user for something he created in my website?
I'm designing a website using djagno with a Q&A section. in this section there is a part that users can see all of questions and also can see who asked any question. I did something but it just shows the username who is logged in for all questions!!! any suggestions? Thank you in advance. This is my view: def getUserInfo(userID): row = msignup.objects.get(id=userID) fname = row.fname lname = row.lname mobile = row.mobile email = row.email userInfo = { 'userID': userID, 'fname': fname, 'lname': lname, 'degree': degree, 'field': field, 'mobile': mobile, 'email': email, } return userInfo def my_question(request): userID = request.session.get('mainSession', 0) userInfo = getUserInfo(userID) user = msignup.objects.get(id=userID) q = Question.objects.all() context = {'myquestions' : q, 'userInfo':userInfo} return render (request,'questions/myquestions.html',context) -
Django form submission success message after form submission
I developed a form which on submission is stored into database. I am using python django framework. Now I would like to show a "Successfully Updated" message in the fronend form for the user. Can someone suggest me the best way to do this. I would like to show the message only after the form is successfully stored in the db. -
How to reload a page on ajax call with clearing form fields?
Whenever ajax is called the page should be reloaded but all fields of forms should not get cleared on page-load my form <form method='post'> <input type='text' placeholder='product'/> <input type='number' placeholder='cost'/> <input type='number' placeholder='tax'/> <button type='button' id="cust_tax" data-toggle="collapse" data-target="#cust_tax">Custom tax</button> <input type='number' placeholder='new tax' id="cust_tax" class="collapse"/> <input type='button' class='apply_tax'>New tax add</button> <input type='submit'/> </form> when user click on custom tax there is a ajax call which save new_tax in database and it gets automatically added in list. my ajax $(".tax_apply").click(function() { var tax_name = document.getElementById("tax_name").value; var tax_value = document.getElementById("tax_value").value; ajaxPost('/myurl',{'user':user,'tax_name':tax_name,'tax_value':tax_value},function(result){ alert('new tax added'); //reload page }); }); now whenever ajax is called and user add new tax it should reload the page but form fields which he have entered should not get cleared