Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ModelForm mantomany fields display only assigned values
So I'm using Django ModelForm, to display informations about hardware articles. Everything goes fine, but when it comes to many2many fields, default behavior is to display every instance of the related model. I need to display only the assigned one, for exemple if my article A is related to server S, I'd like to display only S, not a list with Server A, server B etc ... I went through the official doc and various forum but I have no clue on the way to do this. Thanks in advance for any help. -
How to add extra files to a Django project
I want to host a folder which has separate html, css, javascript and images to a Django project. These ARE NOT the Static files for the Django project itself, but products and resources that will be accessed by users and will have additional folders and files inserted regularly. For example: www..com/Bookstore/MyBook/GiftedHands.epub/ How do I do this? -
Multiupload images but upload only one
I have problem with upload few images in django project. I'm using formsets and below is output from view. I always want to upload few images but uploaded only one. Is the problem with my js or in my view? Thanks for any hint. Here is my self.request.POST: #!/usr/bin/python # -*- coding: utf-8 -*- { u'version': [u'1498826737232128:Wqw-xgmTYqir8Vfa6phBU1NKVqU', u'1498826737232128:Wqw-xgmTYqir8Vfa6phBU1NKVqU'], u'promoted_from_1': [u'00:00'], u'promoted_from_0': [u'01/07/2017'], u'FILES_4982-MAX_NUM_FORMS': [u'1000'], u'locales-0-id': [u'4982'], u'pub_date_1': [u'00:00'], u'pub_date_0': [u'01/07/2017'], u'FILES_4983-0-attachment': [u''], u'FILES_4982-0-id': [u'4544'], u'calendar': [u'33'], u'FILES_4982-1-id': [u''], u'promoted_to_0': [u'01/07/2017'], u'promoted_to_1': [u'00:00'], u'FILES_4982-INITIAL_FORMS': [u'1'], u'FILES_4983-0-id': [u''], u'theme': [u''], u'locales-TOTAL_FORMS': [u'2'], u'FILES_4983-MAX_NUM_FORMS': [u'1000'], u'csrfmiddlewaretoken': [u'xKJujcaMmr9KGrjhgYZus74IacAkzFgm'], u'FILES_4983-0-post_locale': [u'4983'], u'status': [u'0'], u'locales-0-locale': [u'60'], u'locales-INITIAL_FORMS': [u'2'], u'FILES_4982-TOTAL_FORMS': [u'3'], u'locales-0-description': [u''], u'locales-1-description': [u''], u'promoted_budget': [u''], u'locales-MAX_NUM_FORMS': [u'1000'], u'FILES_4983-INITIAL_FORMS': [u'0'], u'locales-1-id': [u'4983'], u'FILES_4982-0-post_locale': [u'4982'], u'FILES_4983-TOTAL_FORMS': [u'1'], u'locales-1-locale': [u'59'], u'FILES_4982-1-post_locale': [u'4982'], u'delete': [u'', u''], u'FILES_4982-0-attachment': [u''], } Here is my self.request.FILES: {u'FILES_4982-1-attachment': [<InMemoryUploadedFile: formset.png (image/png)>, <InMemoryUploadedFile: formset2.png (image/png)>, <InMemoryUploadedFile: formset3.png (image/png)>],} -
Try add ascii literals
Have a csv file with data. do parse that. file_reader = csv.reader(f, delimiter=';') for row in file_reader: data = UserDataCsv() data.user = files.user data.file_hash = request.FILES['file'] data.file = UserFiles.objects.get(id=file_id) print(row[0]) data.material = row[0] But when i try add new row got error. Internal Server Error: /upload_file/ Traceback (most recent call last): File "C:\Python27\lib\site-packages\django\core\handlers\exception.py", line 42, in inner response = get_response(request) File "C:\Python27\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Python27\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\PythoProjecs\csv_files\users\user_functions.py", line 112, in upload_file data.save() File "C:\Python27\lib\site-packages\django\db\models\base.py", line 796, in save force_update=force_update, update_fields=update_fields) File "C:\Python27\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:\Python27\lib\site-packages\django\db\models\base.py", line 908, in _save_table result = self._do_insert(cls._base_manager, using, fields, update_pk, raw) File "C:\Python27\lib\site-packages\django\db\models\base.py", line 947, in _do_insert using=using, raw=raw) File "C:\Python27\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Python27\lib\site-packages\django\db\models\query.py", line 1045, in _insert return query.get_compiler(using=using).execute_sql(return_id) File "C:\Python27\lib\site-packages\django\db\models\sql\compiler.py", line 1054, in execute_sql cursor.execute(sql, params) File "C:\Python27\lib\site-packages\django\db\backends\utils.py", line 79, in execute return super(CursorDebugWrapper, self).execute(sql, params) File "C:\Python27\lib\site-packages\django\db\backends\utils.py", line 64, in execute return self.cursor.execute(sql, params) File "C:\Python27\lib\site-packages\django\db\utils.py", line 94, in exit six.reraise(dj_exc_type, dj_exc_value, traceback) File "C:\Python27\lib\site-packages\django\db\backends\utils.py", line 64, in execute return self.cursor.execute(sql, params) File "C:\Python27\lib\site-packages\django\db\backends\mysql\base.py", line 110, in execute … -
Django template - Iterating throug data with conditional effect related to category
I have data source with structure that looks like this: [{ category: 'A', name: 'item 1', count: 11 }, { category: 'A', name: 'item 2', count: 22 }, { category: 'A', name: 'item 3', count: 33 }, { category: 'B', name: 'item 5', count: 44 }, etc... ] Lets call this data source a 'response' So, for now in django template I am able to do <table><tbody> {% for item in response %} <tr><td>{{item.name}}</td><td> {{result.count}}</td><tr> {% endfor %} </tbody></table> The effect of this is Item 1 11 Item 2 22 Item 3 33 Item 5 44 ... But I am willing to achieve this: Category A Item 1 11 Item 2 22 Item 3 33 Category B Item 5 44 Item 6 55 Category C Item 4 66 So it could have effect like this: <tr><th>Category A</th></tr> <tr><td>Item 1</td><td>11</td></tr> <tr><td>Item 2</td><td>22</td></tr> <tr><td>Item 3</td><td>33</td></tr> <tr><th>Category B</th></tr> <tr><td>Item 5</td><td>44</td></tr> ... In PHP I have always done it using temporary variable where I was holding previous category name and compared it each time when new element of data source was used. Is it possible to do similar thing in Django Template? If no is there any other, simple way to achieve this? -
Django Post model views example
I want to create a simple post model. How is the easiest and useful post creation, deletion, detail and listing for django? Best regards -
Where are stored the migration files djangoseo.xxxx?
I have some troubles with django-seo2. Running migrations: Applying djangoseo.0001_initial... Applying djangoseo.0002_auto_20170630_1000... OK Applying djangoseo.0003_auto_20170630_1038... OK Applying djangoseo.0004_auto_20170630_1041...Traceback (most recent call last): File "manage.py", line 34, in <module> Where are stored the migration files djangoseo.xxxx ? I do not see them under project nor under project/app. -
Send image to api rest with httpie or other
I have the following model: class Picture(models.Model): image = models.ImageField(upload_to="originals", blank=True) entity = models.CharField(max_length=20, choices=ENTITIES, default=ENTITY_CLASIFICADO) The following serializer: class PictureSerializer(serializers.ModelSerializer): image = serializers.ImageField(max_length=None, use_url=True) class Meta: model = Picture fields = ("pk", "image", "entity") And this viewset: class PictureViewSet(viewsets.ModelViewSet): queryset = Picture.objects.all() serializer_class = PictureSerializer I want through httpie and the python requests package to do a POST of an image and an entity. The image I want to send to the API is on my computer. The url to make the post is /v1/pictures/ Thank you! -
Why do I have an error "column "content_type_id" does not exist" in Django?
I'm trying to create a Comment class so that I can comment any type of object with it. I have found a solution here : https://docs.djangoproject.com/en/1.11/ref/contrib/contenttypes/ However, it didn't work. (I must admit that i didn't understand everything about the content_type and object_id they used, I just copied the code from their page) Here is my model : class Comment(models.Model): content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') author = models.CharField(max_length=200, default="userPasDef") text = models.TextField() created_date = models.DateTimeField(default=timezone.now) def publish(self): self.created_date = timezone.now() self.author = "userPasDef" self.save() def __str__(self): return self.text Here is the error : Traceback (most recent call last): File "/home/computer/Documents/virtualenv/lib/python3.5/site-packages/django/db/backends/utils.py", line 65, in execute return self.cursor.execute(sql, params) psycopg2.ProgrammingError: column "content_type_id" of relation "Application_comment" does not exist LINE 1: INSERT INTO "Application_comment" ("content_type_id", "objec... But I don't have any "content_type_id" in my model... I can run makemigrations, migrate and runserver, but each time I try to post a comment on my site this error appears. What could have caused this problem ? Thanks ! -
How to enter keyboard shortcuts in bash script
Is it possible to enter keyboard shortcuts into a bash script? For example, I have tried typing in ^d to substitute for control + d (logout) without success. ubuntu@vfleet:~$ ^d -bash: :s^d: substitution failed ubuntu@vfleet:~$ ^D -bash: :s^D: substitution failed I am using screen to run a django development server in the background. One of the commands to run a particular screen as a daemon is control + a + d. The goal is to be able to enter in control + a + d into a bash script. Is this possible? -
Finding best match in mongoengine database with Django
Suppose we have a a Django model similar to this: from mongoengine import (Document, StringField, DateTimeField) class MyModel(Document): car = StringField() plane = StringField() name = StringField() some_field = SecretField() date = DateTimeField() # some more fields ... Then, we want to take best matching object from our database for a given set of parameters, for example @classmethod def desired_method(cls, **kwargs): # for a given kwargs, choose the one that have fields in db # and return object for that parameter (ordered by date, say last one) For example, calling MyModel.desired_method(car='Ford', name='Bettsy') would return last object created in db, with Ford car having name Bettsy. On the other hand, calling MyModel.desired_method(plane='Airbus', some_field='hashed_msg', pilot='Ron', age='7') would return last object with specified plane and some_field fields, but others are ignored, as they do not exists in our model. The purpose for all that is to be able to flexible extend functionality - let's say we are using model to add new objects to db, with specified car, name and some_field fields. With some populated db, we got request from client to start distinguish objects by another field version. We can't do it backwards, but we may add field version to our model, … -
Django GCBV CreateView, set "localize=False" like form.Forms
So i have this class.CreateView, i use it to add a new location to the model location.model. It describes a certain location with coordinates and a small description. Since I set the I18N settings to True, the decimalField will use comma seperated inputs. Since they're coordinates, I would like the use the "." as seperator. forms.DecimalField(max_digits=16, decimal_places=14, localize=False) Would there be such an option with CreateView, i'd like to use the current view instead of rewriting to a formview. My settings #settings.py LANGUAGE_CODE = 'nl' TIME_ZONE = 'Europe/Amsterdam' USE_I18N = True USE_L10N = True Any other solution would be great, other than I'd like to use the generic class based views. Best regards, -
How to use the class based view to render 2 different forms on one template in Django?
In the django basic polls app. I have added the functionality to add polls and I want the "add choice" form to come below the "poll detail" form on the template, how do i do it? -
difference between start and end date is 14 days Django
I would like to check whether the start and end date entered is valid : end date > start date end date - start date = 14 days. If these 2 conditions do not meet, then the user has to enter the correct date until a valid date has been entered only they can submit the form. views.py def clean(self): cleaned_data = super(TimesheetForm, self).clean() startDate = cleaned_data.get("startDate") endDate = cleaned_data.get("endDate") if startDate and endDate: if endDate < startDate: raise forms.ValidationError("End date cannot be earlier than start date!") if endDate < startDate + delta.(days=14) raise forms.ValidationError("Duration must be 2 weeks!") return cleaned_data I am having error saying invalid syntax on the "if endDate < startDate + delta.(days=14)" line. Could anyone please give me an advice on how should i solve this error. -
How to change language in django-modeltranslation in function
I am using django-modeltranslation for translation some fields in my models. The package works great, everything is translated. But there is no easy method to switch language manually. From reading Accessing Translated and Translation Fields: Because the whole point of using the modeltranslation app is translating dynamic content, the fields marked for translation are somehow special when it comes to accessing them. The value returned by a translated field is depending on the current language setting. “Language setting” is referring to the Django set_language view and the corresponding get_lang function. Using set_language() as it described in documentation doesn't work. Got: AttributeError: 'str' object has no attribute 'POST' This is probably happening because i run set_language() not in view. The question: How i can switch language for django-modeltranslation in basic function? -
Can't find a way to install gettext from PIP virtualenv
Overall I'm trying to use a module in Django that helps with translating pages, but I don't have installed and can't do it through pip install package. I've tried the fllowing: pip install gettext That returns that could not find a version that requires the... I also downloaded the tar.gz file from the official website, yet when I try to install it localy the error: python setup.py egg_info failed with error code 1 windows Comes up. Been reading, trying to fix the second error or possible solutions, installed ez_update, updatade all packages, made a rollback and I don't know what to do anymore, any help? -
OPTIONS requests from iOS
I've got a Web app on Django that makes a bunch of asynchronous calls to the server. It works perfectly well from all browsers except Safari, specifically on iOS where users are reporting at least an intermittent problem. It seems the problem might stem from Safari sending an OPTIONS request (over HTTP, oddly, as the app is universally HTTPS). This is a snippet from the Apache log (edited for anonymity): 172.31.34.143 - - [20/Jun/2017:14:12:46 +0100] "OPTIONS /asyncservice/ HTTP/1.1" 500 245 "http://www.example.com/app/" "Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_2 like Mac OS X) AppleWebKit/603.2.4 (KHTML, like Gecko) Version/10.0 Mobile/14F89 Safari/602.1" Has anyone experienced this, and is there a solution? -
Get search result exported to CSV - django
I have a search functionality where I also provide the user to export the search result as csv. My search function works fine. but, the export function is unable to collect the search result done by the user. I can understand the reason behind this problem but unable to find a way to deal with it. (Usage of Global variable might be helpful, but I don't want to use it) My search query function: def search_query(request): result = publication.objects.all() query = request.GET.get("query") if query: result = result.filter( Q(title__icontains=query) Q(timeStamp__icontains=query) ).distinct() user_filter = UserFilter(request.GET, queryset=result) return user_filter My Search function: def search(request): title = "Advanced Search" user_filter = search_query(request) context = { 'title': title, 'filter': user_filter, } return render(request, "search.html", context) My export function: def export_search_csv(user_filter): data = search_query(request) response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment;filename=publications.csv' writer = csv.writer(response) writer.writerow(['Title', 'Published On']) for item in data.qs: writer.writerow([item.title, item.timeStamp.strftime("%b-%Y")]) return response Please help. -
How to use Django Admin website with No-sql
This is a fairly advanced question, but looking for help here. My goal is how to get a generic object manager site (like django-admin) working for ArangoDB and I'm looking for a good answer on how to achieve that. I absolutely love the Django-Admin website. But I am using a NoSQL database and this currently doesn't seem supported. I am using ArangoDB, but I guess this question would be applicable to other NoSQL databases as well such as Mongo or CouchDB although I'm not using them. This could happen one of two ways: 1) Is there a way to write some data adapter that sits inbetween django-admin and the arrangodb nosql database that allows this to work? I have some knowledge of QuerySets and Managers. Maybe one could re-write one to support ArrangoDB? But these do seem very specific and tied heavily to SQL. 2) Is there a another generic object admin django app that works well with nosql databases? It would need to be similar to django-admin and it would have to be able to add/update/delete objects. For what it's worth, I'm aware of 'django-nonrel' but they don't support ArrangoDB, and the site seems to have almost no recent … -
Aysnc calls from Safari to Web App not working
I've got a Web app on Django that makes a bunch of asynchronous calls to the server. It works perfectly well from all browsers except Safari, specifically on iOS where users are reporting at least an intermittent problem. It seems the problem might stem from Safari sending an OPTIONS request (over HTTP, oddly, as the app is universally HTTPS). This from the Apache log (edited for anonymity): 172.31.34.143 - - [20/Jun/2017:14:12:46 +0100] "OPTIONS /asyncservice/ HTTP/1.1" 500 245 "http://www.example.com/app/" "Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_2 like Mac OS X) AppleWebKit/603.2.4 (KHTML, like Gecko) Version/10.0 Mobile/14F89 Safari/602.1" Has anyone experienced this, and is there a solution? -
Django filter error log
I am trying to create an error log from my Django project. Though I only need it to display 404 & 500 errors. All others can be ignored. (Ignore the .html I need to show it on a page, and it doesn't need to be formatted) Currently all errors at least WARNING are displayed. So How could I filter all errors except 404 and 500? LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'file': { 'level': 'WARNING', 'class': 'logging.FileHandler', 'filename': os.path.join(BASE_DIR, 'logs/debug.html'), }, }, 'loggers': { 'django': { 'handlers': ['file'], 'level': 'INFO', 'propagate': True, }, }, } -
getting a url to download a file generated by the execution of a script in django
i'm new in django and i need help. I have a script which takes in input a video and gives as output another video. What i want to do is once the script is executed in my view, user will have a link to download the video generated by the script. What i tried to do: In my views: class testView(TemplateView): template_name = 'test.html' def getlink(request): var = Video.objects.order_by('id').last() subprocess.call("./myscript.sh %s" % (str(var)); shell=True) filename = "/home/service/videoresult.mp4" wrapper = FileWrraper(file(filename)) response = HttpResponse(wrapper, content_type='text/plain') response['Content-Disposition'] = 'attachment; filename=%s' % os.path.basename(filename) response['Content-Length'] = os.path.getsize(filename) return response -
fixing the form view to hide the field of authenticated user in django
my model.py is from django.db import models from django.contrib.auth.models import User class Question(models.Model): asker = models.ForeignKey(User, related_name='questions') question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) forms.py from django.forms import ModelForm from .models import Question,Choice from betterforms.multiform import MultiModelForm class ChoiceForm(ModelForm): class Meta: model = Choice exclude = ('question','votes) class QuestionForm(ModelForm): class Meta: model = Question exclude = ('asker','pub_date',) class PollForm(MultiModelForm): form_classes = { 'question':QuestionForm, 'choice':ChoiceForm, } views.py class CreateImagePost(CreateView): form_class = PollForm template_name = "blog/post.html" def form_valid(self, form): question = form['question'].save(commit=False) question.asker = User.objects.get(username=request.user.username) question.save() choice = form['choice'].save(commit=False) choice.question = question choice.save() return HttpResponse("congrat") now the view is not working as i want it gives the asker field and make user choose from users list and and don't hide it and after submitting the form nothing changes in the database and the page doesn't redirected also. how should i edit the view to make the maximum amount of choices to be three and make the authenticated user is asker of the question thanks in advance -
Can't upload multiple images with formset
I have django app and problem with multiple images upload. Everything was OK till add to Familymember model field image. Now I can not create any item for FamilyMember. Please for help. Here is my model: class Profile(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) created_date = models.DateTimeField(default=timezone.now) def get_absolute_url(self): return reverse('profile-update', kwargs={'pk': self.pk}) def __unicode__(self): return "%s %s" % (self.first_name, self.last_name) class FamilyMember(models.Model): profile = models.ForeignKey(Profile) name = models.CharField(max_length=100) file = models.FileField(upload_to="localefile/") relationship = models.CharField(max_length=100) Here are forms: class ProfileForm(ModelForm): class Meta: model = Profile exclude = () class FamilyMemberForm(ModelForm): file = forms.FileField(widget=forms.FileInput(attrs={'multiple': True})) class Meta: model = FamilyMember exclude = () FamilyMemberFormSet = inlineformset_factory(Profile, FamilyMember, form=FamilyMemberForm, extra=1) Here are my views, to create. class ProfileCreate(CreateView): model = Profile fields = ['first_name', 'last_name'] class ProfileFamilyMemberCreate(CreateView): model = Profile fields = ['first_name', 'last_name'] success_url = reverse_lazy('profile-list') def get_context_data(self, **kwargs): data = super(ProfileFamilyMemberCreate, self).get_context_data(**kwargs) if self.request.POST: data['familymembers'] = FamilyMemberFormSet(self.request.POST) else: data['familymembers'] = FamilyMemberFormSet() return data def form_valid(self, form): context = self.get_context_data() familymembers = context['familymembers'] with transaction.atomic(): self.object = form.save() if familymembers.is_valid(): familymembers.instance = self.object familymembers.save() return super(ProfileFamilyMemberCreate, self).form_valid(form) I also use a JavaScript code, from here: <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> <script src="{% static 'formset/jquery.formset.js' %}"></script> <script type="text/javascript"> $('.formset_row').formset({ addText: 'add family member', deleteText: 'remove', … -
Invalidating cache
I have to cache my message board. But the issue is that whenever any new message is there on the message board the cache should be invalidated and a new cache should be formed. How can I do that?