Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to render pyqt4 gui in django?
Is there any method to render pyqt4 gui in django template? I'm using django v1.8 and python 2.7 Currently I have a a pyqt4 code creating a GUI that browses an image from my computer and perform some processing and next it shows the images and a histogram in several figures. How do I incorporate the gui to django and create a web app? -
validate the size and format if uploaded image and resize it in django
I am uploading an image in django, i want to validate it's format and size in forms.py class CreateEventStepFirstForm(forms.Form): user_image = forms.ImageField(required = True, widget=forms.FileInput(attrs={ 'class' : 'upload-img', 'data-empty-message':'Please upload artist image, this field is required' })) While uploading this image i want to first validate it's format, form allows user only to upload png and jpeg image and also user will have to upload an image upto 700*500 dimensions, if image is lower than this dimensions, then this form should not be validated, and if image is greater than 1200*1000 pixels, in this case it should resize image to 700*500 without affecting the image quality. View i am using for uploading file is :- def create_new_event(request, steps): if request.method == 'POST': stepFirstForm = CreateEventStepFirstForm(request.POST, request.FILES) if stepFirstForm.is_valid(): myfile = request.FILES['user_image'] fs = FileSystemStorage() filename = fs.save('event_artists_images/'+myfile.name, myfile) uploaded_file_url = fs.url(filename) return render(request, 'home/create-new-event.html', {'stepFirstForm':stepFirstForm}) -
how to resize an image while uploading and saving it automaticly django
I am not able to save the image that is either being resized or uploading directly through my admin panel. I want to resize it through PLP or any other way! def get_product_image_folder(instance, filename): return "static/images/product/%s/base/%s" %(instance.product_id, filename) product_image = StringIO.StringIO(i.read()) imageImage = Image.open(product_image) thumbImage = imageImage.resize((100,100)) thumbfile = StringIO() thumbImage.save(thumbfile, "JPEG") thumbcontent = ContentFile(thumbfile.getvalue()) newphoto.thumb.save(filename, thumbcontent) new_photo.save() -
django rest framework - nested serializers
I have those models and serializers: # MODELS class CompanyUserProfile(AbstractUserProfile): guid = models.UUIDField(verbose_name=_('GUID'), unique=True) organization = models.ForeignKey( verbose_name=_('organization'), to='my_company.Organization', related_name='user_profiles', null=True, blank=True, ) position = models.ForeignKey( verbose_name=_('position'), to='my_company.Position', related_name='user_profiles', null=True, blank=True, ) store_pcs = models.ManyToManyField( verbose_name=_('Store PCs'), to='my_company.StorePC', related_name='user_profiles', ) # location = models.ForeignKey( verbose_name=_('WorkLocation'), to='my_company.WorkLocation', related_name='user_profiles', null=True, blank=True, ) class StorePC(AbstractOrganizationalUnit): store_number = models.CharField( max_length=50, editable=False, help_text=_("..."), null=True, unique=True ) anchor = models.BooleanField( default=False, editable=False, help_text=_('...'), ) @python_2_unicode_compatible class Transcript(TimeStampedModel): csod_profile = models.ForeignKey( CompanyUserProfile, null=True, blank=True, related_name='transcripts', verbose_name="Company Profile" ) learning_objective = models.ForeignKey( LearningObjective, verbose_name="Learning objective", related_name="transcripts" ) transcript_status = models.ForeignKey( TranscriptStatus, verbose_name="" ) transcript_status_last_modified = models.DateTimeField( verbose_name="Transcript Status last modified", null=True, blank=True ) brand = models.ForeignKey( Score, null=True, blank=True, verbose_name="Score", related_name="transcripts" ) passed = models.NullBooleanField( verbose_name="Has passed" ) requested_on = models.DateTimeField( verbose_name="Requested on", null=True, blank=True ) registered_on = models.DateTimeField( verbose_name="Registered on", null=True, blank=True ) assigned_on = models.DateTimeField( verbose_name="Assigned on", null=True, blank=True ) due_date = models.DateTimeField( verbose_name="Due date", null=True, blank=True ) completed_on = models.DateTimeField( verbose_name="Completed on", null=True, blank=True ) custom_dashboard = models.BooleanField( verbose_name="", default=True ) completion_percentage = models.PositiveSmallIntegerField( verbose_name="", null=True, blank=True ) timestamp = models.DateTimeField( verbose_name="Timestamp" ) # SERIALIZERS class TranscriptSerializer(serializers.ModelSerializer): id = serializers.CharField(source='get_id', read_only=True) value = serializers.IntegerField(source='get_title', read_only=True) # segment_id = serializers.CharField(default="N/A", read_only=True) class Meta: model = Transcript … -
Upload html in Django
Code in template: <form action="/html/" method="post" enctype="multipart/form-data"> {% csrf_token %} <input type="file" id="html_file" name="html_file" /> <input type="submit" value="Upload" /> </form> and in view def add_html(request): if request.POST: #do something with html return redirect('/') else: return render_to_response('add_html.html') I need to html-file is loaded and read its contents, not upload to the server. But I get an error: csrf token missing or incorrect How fix? -
How to remove distinct values from a QuerySet and keep the pk at the same time?
I am using the package django_autocomplete_light. I have a simple model called Tag: class Tag(models.Model): title = models.CharField(max_length=255) django_autocomplete_light uses the following code when selecting all tags: qs = Tag.objects.all() The problem with this is the software I am building needs to allow duplicate tags (not my decision). That means if there are two tags "Male" and "Male", obviously there will be duplicates in the QuerySet. I've tried to remove these duplicates by changing the query as follows: qs = Tag.objects.all().distinct() However I am not using PostgreSQL, so it causes an error. Therefore I tried this workaround: qs = Tag.objects.all().values_list('title', flat=True).distinct() But that just causes the following error: AttributeError: 'str' object has no attribute 'pk' I tried changing the query to the following but it causes another error: qs = Tag.objects.all().values_list('pk', 'title').distinct() AttributeError: 'tuple' object has no attribute 'pk' So basically it seems like I need to keep the id value, but somehow remove the duplicate tags. Unfortunately I can't use a raw SQL query as the QuerySet gets processed multiple times in later code. Is there a way I can change my database query, or perhaps a way to manually remove duplicates from a QuerySet? Any help appreciated. Thank … -
Get the conditions that returned true in Django filter
I am creating a queryset using a list of OR conditions. objects = mModel.objects.filter(reduce(operator.or_, listargs)) Is there a way to retrieve the OR conditions that returned true, after the execution of the query? Thank you. -
'QuerySet' object doesn't support item deletion
I am trying to delete an Item in the QuerySet by Index. I am able to display the items of the QuerySet using print q_set[code_id - 1] but can't delete it. I want to permanently delete the item and not filter excluding that item. views.py ... def customcode_view(request): global q_set try: u = User.objects.get(username=request.user) except: return render(request,"login_required.html",{}) q_set = customcode.objects.filter(user=u) if request.method == "POST": form = CustomcodeForm(request.POST) if form.is_valid(): cc = form.save(commit=False) cc.user = u cc.save() return HttpResponseRedirect('#BOTTOM') else: form = CustomcodeForm() return render(request, "customcode.html" , {'q_set':q_set,'form':form,}) def deletecode(request,code_id): code_id = int(code_id) del q_set[code_id - 1] #this is the problem return redirect('customcode_view') ... models.py ... class customcode(models.Model): user = models.ForeignKey(User) name = models.CharField(blank=False,max_length=250) sourcecode = models.TextField(blank=False) def __unicode__(self): return self.name ... -
How to add field into generic detail via HyperlinkedIdentityField in Django REST
I would like to add my own field 'create_user' into API using Django Rest Framework. There's a problem with auto generated detail view. Is there an easy way to customize detail view and add field into it without redefined whole view by hand? serializers.py class AccountSerializer(serializers.HyperlinkedModelSerializer): detail = serializers.HyperlinkedIdentityField(lookup_field='id', view_name='account-detail', read_only=True) This automatically generate view, serializer and url for detail of Model Account. I don't need to do something more. And now, how to add extra field, which is not in Account Model? -
Django Rest : Model field default value only while creating
I have a model with 3 char-fields. I want to give them default values when a row is getting created. This default values are sort of IDs which depends on time. This ID should never change. i.e. the default value should not be applied when subsequent updates happen on the row. I'm trying to use update_or_create but, the defaults while creating & updating are not same. How can I put these Ids only while creating and ignore while updating? I'm referring to this answer but no luck. -
How to display the text value of an enum field?
I am using django_enumfield My model looks like this: class GenderValues(enum.Enum): NONE = 0 MALE = 1 FEMALE = 2 BOTH = 3 class Gender(models.Model): gender = enum.EnumField(GenderValues, default=GenderValues.NONE) def __str__(self): return self.gender I have exposed this model in the admin area as follows: admin.site.register(Gender) I can then go to the admin area and add a gender. Problem: The gender appears as the number (e.g. 1 if I choose 'Male') instead of "MALE". Note I have tried adding a label to GenderValues like this but it makes no difference: labels = { MALE: 'Male', } Do you know how I can display "MALE" or "Male" in the admin area instead of 1? Thank you. -
Django REST Framework : filtering with another table
I'm using Django REST Framework to implement an associative schedule system, where a user can subscribe to an association and receive its events. Each association can have many groups (you choose yours when you subscribe to the association), so that the events are often the same for each group but with different places and dates. The model looks like this : class Association(models.Model): name = models.CharField(max_length=40, blank=False, unique=True) description = models.CharField(max_length=500, blank=False) class AssocMember(models.Model): class Meta: unique_together = (("user", "assoc"),) user = models.ForeignKey('user.User') assoc = models.ForeignKey('associations.Association') is_admin = models.BooleanField(default=False) group = models.SmallIntegerField(default=-1) class Event(models.Model): name = models.CharField(max_length=40, blank=False) date = models.DateTimeField(blank=False) assoc = models.ForeignKey('associations.Association') group = models.IntegerField(blank=True, default=-1) I would need to implement a get_queryset() in my API that returns all the events of the connected user corresponding to its group. But for that, I have to access AssocMember for each event during the filtering, and create a custom condition (like normal .filter() in Python) What is the best way to do so with Django REST filters ? Thanks in advance. -
How to create a DB view using Django
Is it possible to create and use a database view using Django models. I have read of a meta option managed=False But am unsure if this can cater my requirement -
Python Django Template cannot get name from model function
While I understood that I can call a function definition from our models, I can't seem to extract the file name of my uploaded document. Below I tried the following template format but either results from my desired output: .html Version 1 <form action="." method="GET"> {% if documents %} <ul> {% for document in documents %} <li> {{ document.docfile.filename }} <input type = "submit" name="load-data" value="Add to Layer"/> </li> {% endfor %} </ul> Result: It just shows the button. .html Version 2 <form action="." method="GET"> {% if documents %} <ul> {% for document in documents %} <li> {{ document.filename }} <input type = "submit" name="load-data" value="Add to Layer"/> </li> {% endfor %} </ul> Result: It just shows the button. .html Version 3 <form action="." method="GET"> {% if documents %} <ul> {% for document in documents %} <li> {{ document.docfile.name }} <input type = "submit" name="load-data" value="Add to Layer"/> </li> {% endfor %} </ul> Result: Prints the complete pathname (eg: /documents/2016/10/08/filename.csv) together with the button Here's the rest of my code: models.py class Document(models.Model): docfile = models.FileField(upload_to='document/%Y/%m/%d') def filename(self): return os.path.basename(self.file.name) views.py documents = Document.objects.all() return render(request, 'gridlock/upload-data.html', { 'documents' : documents, 'form': form }) I hope someone can explain why … -
Not Fount :/media/app/images/my_image.png
image not found but the image exist at exact location . print(profile.image.url) #/media/app/images/my_image.png prints the image location but when i used in my template , other column are current but image is not found profile = same_table.object.get(pk = 1) setting: MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(MY_BASE_DIR , 'media') my media location has no problem because when i upload image to server it is working fine Template: <img src = "{{profile.image.url}}"> any idea what i messed ? Using Django 1.10 with Python 3.4 in window 10 -
django required file field validation
Working with django form in which i have two file uploads fields one for artist image and another for event poster, both of these fields are required. class CreateEventStepFirstForm(forms.Form): event_title = forms.CharField(required = True, max_length=20, widget=forms.TextInput(attrs={ 'class' : 'custome-input promote-input', 'autocomplete' : 'off', 'data-empty-message':'This field is required' })) ticket_title = forms.CharField(required = True, max_length=225, widget=forms.TextInput(attrs={ 'class' : 'custome-input promote-input', 'autocomplete' : 'off', 'data-empty-message':'This field is required' })) artist_image = forms.FileField(required = True, widget=forms.FileInput(attrs={ 'class' : 'upload-img', 'data-empty-message':'Please upload artist image, this field is required' })) event_poster = forms.FileField(required = True, widget=forms.FileInput(attrs={ 'class' : 'upload-img', 'data-empty-message':'Please upload artist image, this field is required' })) Problem is that all fields are validated properly except these two file fields, when i select images for both artist_image and event_poster it don't validate the fields and give "This field is required" error even i select both images. -
Django admin foreign key values custom form
So, I have a model Puzzle and a model Piece. Piece has as foreignKey to Puzzle. And on the admin, on puzzle form to add a new element, i have a stackedInLine for pieces. But i can only add more if I enter all the data from the piece. Is there a way to add new Pieces to the puzzle by choosing from a dropdown with the Piece values already stored on the DB ?? I google'd forever and found nothing....thanks. -
Serializing a JSON object for a Django URL
I have a JSON object that looks like this: var obj = { "selection":[ { "author":"John Doe", "articles":[ "Article One", "Article Two" ] } ] } I want to pass this object to Django to render a view that displays 'Article One' and 'Article Two' upon render. I first serialize the JSON object so that it can be appended to a URL; I use $.param(obj) for serialization. Now the JSON object looks something like this: "selection%5B0%5D%5Bauthor%5D=John+Doe&selection%5B0%5D%5Barticles%5D%5B%5D=Article+One&selection%5B0%5D%5Barticles%5D%5B%5D=Article+Two" Now I can append this to a path and use window.open(url) the view will handle everything else. On the Django end, I was surprised to see that the structure of the JSON object has changed to this: "selection[0][author]=John+Doe&selection[0][articles][]=Article+One&selection[0][articles][]=Article+Two" I want to be able to use the JSON object as a dict e.g.: obj = request.GET.get('selection') obj = json.loads(obj) print(obj[0].author) ... How should I handle this JSON structure on the Django side of things? -
python post request not working with import
I have a problem with POST request with Python/Django and Minio server, this is the code from django.http import HttpResponse import json from minio import Minio minioClient = Minio('mypath:9000', access_key='mykey', secret_key='mysecret', secure=False) def getMessage(request): if request.method == 'POST': data = json.loads(request.body.decode('utf-8')) for obj in data['files']: ...do some stuff.... minioClient.fget_object(myvar, myvar2, '/tmp/processing') return HttpResponse(file) The problem is that the request won't work if I don't remove the import at the begging and I can't understand why. This is the error generated: HTTPConnectionPool(host='myhost', port=8001): Max retries exceeded with url: /myurl/ (Caused NewConnectionError ('<requests.packages.urllib3.connection.HTTPConnection object at 0x7fcbeab21160>: Failed to establish a new connection: [Errno 111] Connection refused',)) and this is the script that make the request is this one: .... some code.... try: r = requests.post("http://myurl:8001/mypath/", data=my_data, timeout=1) except Exception as e: print(e) I've already tried to increase the timeout but it's not working and of course I've tested the Minio part in another script, the import it's generating this error only in this request script. Thanks for the help -
Does not upload file django 1.9
http://www.easydevmixin.com/2015/07/17/easily-dealing-with-multiple-files-in-django/ In this example file does not upload. Why? No error. Thank you -
django cms filer uploads fail - diagnostics?
I've logged into a new Django CMS system as superuser but cannot Add filer image or Add filer file to a page as the file upload silently fails; very briefly flashing its upload graphics but not actually uploading anything. I believe all the settings.py are correct as static artifacts are rendered correctly and nginx has credible similar locations for both media and static directories. I believe all file and directory permissions and ownerships are correct; i.e. that nginx has user and / or group ownership to the Django CMS app directories and that permissions are correct. The postgres table filer_folder has a row for a new filer folder I created when editing a page but no corresponding directory has been created in the file system. I can add text and new text block plugins that get saved correctly. Django CMS is running in a Docker container web which I have confirmed has rw access to a Docker volume. I see nothing abnormal in webs logs. How can I find out what's (not) happening? -
Prevent initializing model form when crreating
In a Django form I encountered a strange python behavior. I have a model form which I want to populate with some existing data. Because one field is meant to be a comma separated list of an m2m field I have to initialize it separately. class SomeModel(models.Model): confirming_stuff = models.ManyToManyField(OtherModel,related_name='confirming') def get_confirming(self): return ','.join([l.pmid for l in self.confirming_stuff.all()]) class SomeForm(ModelForm): def __init__(self, *args, **kwargs): super(SomeForm, self).__init__(*args, **kwargs) self.initial['confirming_field'] = self.instance.get_confirming() Everything works fine with an update. The field is populated with comma separated entries as expected. The problem arises with creation. As the instance does not yet exists the field cannot be filled with data, so I tried to skip this step. But it doesn't work. Instead I encountered a strange behavior of the python code. class SomeForm(ModelForm): def __init__(self, *args, **kwargs): super(SomeForm, self).__init__(*args, **kwargs) if self.instance: print "Self instance: ",self.instance self.initial['some_field'] = self.instance.get_some_field() produces the same error. Additionally the printout on the debug screen shows: Self instance: None I tried several other logical expressions, if self.instance != None: if not self.instance == None: if self.instance > 0: but the result remains the same. It remains a mystery to me why the instance is printed as 'None' but cannot be … -
Is there any way to post list of dictionary in django test client?
As Django Test Client accepts only data={} as an input I am not able to pass a list of dict i.e data=[{},{},{}] to it. Any solution for this? -
Serving excel file via django
Hello I have seen many similar posts like this but I am not able to solve my problem. So from client side i am uploading a excel file (.xls) and then in django view i am performing some task and then want to return the same excel file with some errors written at the end of the same file as response. I have two problem firstly how to write on the same file and returning into the response without saving it. secondly the file i am recieving at the client side is encoded i am not able to decode. My client side for uploading file is: <form id="upload_excel" method="post" enctype="multipart/form-data"> <p>File Upload</p><br> <p>Select File</p><br> <input id="csv" name="csv" type="file" /> <input type="submit" value="submit"/> </form> Handling it in django class Upload(APIView): """Handle upload files.""" def post(self, request, *args, **kwargs): """POST call.""" error_list = [] filehandle = request.FILES.get('csv') data = filehandle.read() book = xlrd.open_workbook(file_contents=data, encoding_override='utf8') wb_sheet = book.sheet_by_index(0) for rownum in range(1, wb_sheet.nrows): try: row = wb_sheet.row_values(rownum) // some task wb = copy(book) wb_sheet = wb.get_sheet(0) for errors in error_list: wb_sheet.write(last_row, 0, errors) last_row += 1 wb.save("output.xls") // this i don't want to do res = HttpResponse(data, content_type='application/vnd.ms-excel') res['Content-Disposition'] = 'attachment; filename="Output_Report.xls"' return … -
how to use csv file data after upload using javascript and html5 or django
I have the code to upload the csv file. http://www.aspsnippets.com/Articles/Read-Parse-and-display-CSV-Text-file-using-JavaScript-jQuery-and-HTML5.aspx <script type="text/javascript"> function Upload() { var fileUpload = document.getElementById("fileUpload"); var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.csv|.txt)$/; if (regex.test(fileUpload.value.toLowerCase())) { if (typeof (FileReader) != "undefined") { var reader = new FileReader(); reader.onload = function (e) { var table = document.createElement("table"); var rows = e.target.result.split("\n"); for (var i = 0; i < rows.length; i++) { var row = table.insertRow(-1); var cells = rows[i].split(","); for (var j = 0; j < cells.length; j++) { var cell = row.insertCell(-1); cell.innerHTML = cells[j]; } } var dvCSV = document.getElementById("dvCSV"); dvCSV.innerHTML = ""; dvCSV.appendChild(table); } reader.readAsText(fileUpload.files[0]); } else { alert("This browser does not support HTML5."); } } else { alert("Please upload a valid CSV file."); } } </script> <input type="file" id="fileUpload" /> <input type="button" id="upload" value="Show" onclick = "Upload()" /> <hr /> <div id="dvCSV"> Using this i can upload and view the csv data.But now i want to parse it and for each column header a separate drop down menu is to be shown and the data selected from the drop down list has to be stored in the database. What would be the best approach for this? I've tried creating the form using django also but didnt understand …