Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django ModelMultipleChoiceField and CheckboxSelectMultiple delete values
I have a Form with: somemodels = forms.ModelMultipleChoiceField(queryset=SomeModel.objects.none, widget=forms.CheckboxSelectMultiple, required=False) I set my queryset with my __init__ function and and can even provide existing connections to my list on page load (existing objects are marked as checked). def __init__(self, *args, **kwargs): qs = kwargs.pop('SomeModel') inital_object = kwargs.pop('someothermodel') super(SelectDatesForm, self).__init__(*args, **kwargs) self.fields['timeframes'].queryset = qs selected_items = qs.filter(someothermodels=inital_object) #manytomany relationship self.fields['somemodels'].initial = selected_timframes The issue I get is a combination of the fact that a) HTML only submits data for checked inputs and b) django forms remove all the already existing objects from "cleaned_data". When I submit the form, I get the cleaned_data list of my form only contains the newly selected values, not the ones that were already selected when the page was constructed. To delete the existing ones (i.e. if the user unselects a checkbox that was initially checked) I need to know either a) a total list of all selected values, or b) a list of values that have been unselected. Is there a smooth way of doing this without actually going through the original POST data? -
Django filter choices in forms
I'm a bit of a django newbie and was looking for a bit of advice. I want to make an 'Add Favourites' form to allow users to select their 'favourite' tests from a list, with the idea being that they will only see test data relevant to them. There are a lot of tests so I want to be able to filter the tests by category with the user being able to add multiple tests from different categories. These are my models: class TestCategory(models.Model): name = models.CharField() ... class Test(models.Model): name = models.CharField() category = models.ForeignKey(TestCategory) ... class UserTests(models.Model): user = models.ForeignKey(User) test = models.ForeignKey(Test) ... I've played around with Django Forms, ModelForms and django-filters but can't seem to combine it all together. Ideally, I'd like it to look something like this: http://jsfiddle.net/WX4Nw/ The problem I'm having as well is that it needs to be client-side so nice solutions involving server requests like Ajax don't work. Is there a way to do this using Django Forms? -
Access Celery's subprocess stdout and stderr in my Django app
I put Celery in my Django app so that the two other python programs can process the input from my Django app via doing subprocess method. My question is how do I access the output from the subprocess? Back then when I made just a python program, I access the log files (output from the two apps) via stdout and stderr. Is this the same when I use Celery in Django? Is the value of CELERY_RESULT_BACKEND (if I should assign my Django app's db here) affected by the log files? So far what I've done is: Access the two apps via subprocess in my tasks.py I assigned my broker's db, Redis, as my db for now for CELERY_RESULT_BACKEND. My plan is to get the log files and then save them to my Django app's db so that I can just access that db. Can you offer some help? -
How to pass an url tag in a custom template tag?
I'm learning Django building a small site, and I found that I have many templates where I list objects, each of them with a link to it. I thought I could make a custom template tag, something like {% object_list some %} some is a dictionary {'list': obj_list, 'link': link} where obj_list is the list of objects I want to print out and link should some url structure that points to the item. The template (called object_list.html) should look like {% for object in object_list %} <li><a href="{% url myapp:object object.id %}">{{object.name}}</a></ {% endfor %} Now, my problem is that I don't know what to do in the url. I want it to be flexible, such that 'myapp:object' is replaced by the argument 'link', for example, if the object type is User, then I use {%url myapp:user user.id%}. It is possible to do this? How? I tried this solution, in the form {% for object in object_list %} {% url 'link' as my_url %} <li><a href="{% url myview object.id %}">{{object.name}}</a></li> {% endfor %} giving 'myapp:myobject' as argument but it does not work. To be precise, in the template {% load property_extras %} {% object_list property_dict %} where property_dict is my … -
Wagtail sitemap produces error in console
We've noticed this error (below ) cropping up when running the Wagtail sitemap.xml, we haven't modified it, and it does work. These errors are just in the console/logs locally. Our server person wants to know if we should worry about these or not? Thanks Joss Exception while resolving variable 'priority' in template 'wagtailsitemaps/sitemap.xml'. VariableDoesNotExist: Failed lookup for key [priority] in u"{u'lastmod': datetime.datetime(2015, 7, 22, 10, 57, 43, 759421, tzinfo=), u'location': u'http://localhost/streamfield-page/news-index/news-1/'}" -
How to copy a Django Model Instance and all related data
Using Django 1.9 and Python 3.4 I want to copy an existing model instance and all its related data. Below is an example of how I have currently achieved this. My question is, is there a better way? I have read over posts e.g. Duplicating model instances and their related objects in Django / Algorithm for recusrively duplicating an object this one but, they are over 8 years old and no longer work with Django 1.9+. Below is how I try to achieve this already, ok or a better way in Django 1.9? Models class Book(models.Model): name = models.CharField(max_length=80) class Contributor(models.Model): name = models.CharField(max_length=80) books = models.ForeignKey("Book", related_name="contributors") Copy Function def copy_book(self, id): view = self.context['view'] book_id = id book = Book.objects.get(pk=book_id) copy_book_contributors = book.contributors.all() book.id = None # make a copy of the contributors items. book.save() for item in copy_book_contributors: # We need to copy/save the item as it will reassign the existing one. item.id = None item.save() book.contributors.add(item) -
PyCharm: debug Django Rest Viewsets
I have got the following viewset (same in the Rest Framework docs): class UserViewSet(viewsets.ViewSet): def list(self, request): queryset = User.objects.all() serializer = UserSerializer(queryset, many=True) return Response(serializer.data) Let's say this viewset is called by: GET 127.0.0.1:8000/api/user I want to toggle breakpoints and watch, how the code is executing when I request to that viewset from my web-interface. I know that it is possible to debug django commands (that are inherited from BaseCommand and called by python manage.py <command_name>). I simply define in Run/Debug configurations Script - manage.py and script parameters - <command_name> and everything works like a charm. Is it possible to Debug my viewsets somehow? -
How to package a Django app to be test-friendly?
I've been working on this side project that's effectively a replacement for Django's default FileField and ImageField classes. More of a thin wrapper really, it lets you change this: attachment = models.FileField(upload_to="attachments") image = models.ImageField( upload_to="images", width_field="image_width", height_field="image_height" ) into this: attachment = EncryptedFileField(upload_to="attachments") image = EncryptedImageField( upload_to="images", width_field="image_width", height_field="image_height" ) and magically Encrypt All The Things. The thing is, while it works well so far, and I have tests for it, packaging is still troublesome. Specifically: I don't know how to run the tests outside of the demo. You need to cd into demo and run ./manage.py test and there has to be a symlink from that directory to ../django_encrypted_filefield. This can't be the "right" way to do this... right? I think I've got setup.py working as I can do pip install -e git+... and things work just fine, but I don't think the demo should be included, right? But if I exclude it, what about the tests? Ideally, I'd like to setup tox to do the usual pep8 & unit test run, but I don't know how to do that for a project that's Django-dependent. TL;DR: Can someone point me to a simple django module that does tests … -
Django - Pass related object as variable in user_passes_test mixin
I am trying to restrict instances of an object to be viewable only to users referenced by that object via a OneToOneField. I’m using the “user_passes_test” mixin on a DetailView to compare request.user to the user in the OnetoOne relationship. I got some help on django irc which led me to unsuccessfully try and implement get_object, but I’m still stuck (I'm new to Django & Python). the Model: class Event(models.Model): client = models.OneToOneField(settings.AUTH_USER_MODEL) the View: class EventDetail(UserPassesTestMixin, DetailView): model = Event def test_func(self): if self.request.user == self.model.client: return True else: return False User is being referenced in its own app, as User(AbstractUser) -
Django project- adding a new user
I need to add a new user profile to my Django project for a new employee who is starting next week- I tried doing this via www.mysite.co.uk/admin and going to Authentication & Authorisation -> Add User, I set up the username & password, and gave the user profile admin privileges. It said that the user had been created successfully, but when I tried to get hold of the user profile that I had just added in the command line, by running the following commands: from employees import models from employees.models import Employee allEmps = Employee.objects.all() newUser = allEmps.filter(first_name = "name") newUser just became an empty array, so clearly the user has not been added to the database... If I run the same commands, but using my name, rather than the name of the user I've just tried adding, newUser holds an array of one element (my user account), which I can then assign to a variable in order to check its properties, etc. I then tried creating a new user directly in the command line, so ran: newEmployee = Employee(first_name = "name", surname = "surname") and this seemed to create an Employee object locally How do I actually add a … -
How to check errors for gunicorn using sock
I have a Django project running using gunicorn sock(not port). I am using supervisor to run it. The problem is - supervisor is saying that the process is running. Logs doesnt show anything. But site says "Bad gateway". Nginx generally shows bad gateway when the gunicorn is not running. But here, gunicorn is running without errors but nginx shows bad gateway. If it uses port, I would have tested locally using "wget http://localhost:8000" but since we use sock here, how to test if its really running and why its not showing any error. -
The value of the input disappears
I'm new using the ** typeahead.js ** with ** Django **. I'm also using ** handlebars_min.js **. When I type three characters I show the items in my list that match the search, when doing Click, the element is placed in the input. The problem is that when I choose the element and I click outside the input, the value of the input disappears. Here is my code Views.py def json_destino(request): destino = request.GET.get('q', None) if not destino: return HttpResponse(json.dumps({})) destinos = Clientes.objects.filter(nombre__icontains=destino) vl = [{'name': c.nombre,'destino': c.nombre} for c in destinos] vl = vl[:10] ret = json.dumps(vl[:10]) return HttpResponse(ret) Archivo autocomplete.js $(function() { var engine1 = new Bloodhound({ remote: '/destino/name/json/?standard=true&q=%QUERY', datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'), queryTokenizer: Bloodhound.tokenizers.whitespace, }); engine1.initialize(); $('#id_destino').typeahead({minLength: 3,highlight: true}, { name: 'destino', displayKey: 'id', source: engine1.ttAdapter(), templates: { empty: [ '<div class="empty-message">', 'No se ha encontrado ningun elemento', '</div>' ].join('\n'), suggestion: Handlebars.compile('<p style="border: 1px solid red; padding: 5px;">'+'<span class="text-primary" style="font-size:20px;">{{name}}</span><br>' +'</p>') } }).bind('typeahead:selected', function(obj, datum) { taselected(obj, datum); }).bind('typeahead:autocompleted', function(obj, datum) { taselected(obj, datum); }); function taselected(obj, datum) { $("#div_id_destino").click(); $("#id_destino").val(datum.destino); } }); HTML <div id=div_id_destino> <input type="text" name="destino" id="id_destino" /> </div> <script src="{% static 'js/autocomplete.js' %}"></script> -
How to get round "Must be a "image" instance" when uplaoding with a csv
I have just managed to install the django-import-export package on my project and i am testing how i can export and import data so that i can populate my tables fast. When i try to upload data i get an error telling me Line number: 1 - Cannot assign "''": "Component.image" must be a "Image" instance. i have tried numerious types of data to get round this, and i cant find anything on google, if anyone has any information on this problem i would love to hear it! -
Django's form textarea doesn't appear in template
I'm beginner in Django and I'm trying to create a form. The problem is that when I render the form, the textarea field doesn't appear, but the button does. The project is a twitter-like app, the form is where the user puts the text to and then posts it. forms.py: from django import forms class TweetForm(forms.Form): text = forms.CharField(widget=forms.Textarea(attrs={'rows': 1, 'cols': 85}), max_length=160) Country = forms.CharField(widget=forms.HiddenInput()) views.py: class PostTweet(View): """Tweet Post form available on page /user/<username> URL""" def post(self, request, username): form = TweetForm(self.request.POST) if form.is_valid(): user = User.objects.get(username=username) tweet = Tweet(text=form.cleaned_data['text'], user=user, country=form.cleaned_data['country']) tweet.save() words = form.cleaned_data['text'].split(" ") for word in words: if word[0] == "#": hashtag, created = HashTag.objects.get_or_create(name=word[1:]) hashtag.tweet.add(tweet) return HttpResponseRedirect('/user/'+username) template: {% extends "base.html" %} {% block content %} <div class="row clearfix"> <div class="col-md-12 column"> <form method="post" action="post/">{% csrf_token %} <div class="col-md-8 col-md-offset-2 fieldWrapper"> {{ form.text.errors }} {{ form.text }} </div> {{ form.Country.as_hidden }} <div> <input type="submit" value="post"> </div> </form> </div> <h3>&nbsp;</h3> <div class="col-md-12 column"> {% for tweet in tweets %} <div class="well"> <span>{{tweet.text}}</span> </div> {% endfor %} </div> </div> {% endblock %} Output: -
Django filer image related to another model, i.e. is it being used?
I am creating a cleanup script for Django Filer, so that if an image is not in use, e.g. it's not related to any other model, then I'd like to delete the image. I can't figure out how to detect if the image is related to any other objects though. Does anybody know how to achieve this? You can view this information when you press the delete button and are on the delete confirmation page, but I'm not sure how Django has done this. Any help would be much appreciated. -
Asynchronous task queue for serverless AWS Lambda / Django / Zappa
I have been experimenting with deploying Django apps to AWS Lambda with Zappa. In some of my other (EC2/EBS hosted) Django projects, if there is a need to perform some heavier calculation that can take some time (such as sending a lot of emails, or just some processing that takes over a minute), Celery is used. It is a task queue system where the tasks are sent to a queue, a response can be returned immediately and workers can process the tasks later. What would be the best way to implement a Celery-like task queuing system for a Zappa-Django app running in Lambda? Zappa/Lambda supports scheduled tasks, and the models of the app could be designed in such a way that the processing could be done by scheduled functions later and the results could be saved to DB. But I do not think polling for tasks once a minute is robust enough, there is a oftena need to start the delayed task immediately. Is there an easy way to return a response from a Django view immediately and have a function (from inside the Django app) with arbitrary parameters queued to be executed later? -
HTML+JSON ModeViewSet Renderers: dictionary update sequence element #0 has length ??; 2 is required
I'm using Django==1.10.5 and djangorestframework==3.5.3. I have a few ModelViewSets that handle JSON API requests properly. Now, I'd like to use TemplateRenderer to add HTML rendering to those same ModelViewSets. I started with the list endpoint, and created a simple template that lists the available objects. I implemented the get_template_names to return the template I created. Accessing that endpoint through the browser works fine when there are no objects to list, so everything related to setting up HTML renderers alongside APIs seems to work.However, when tere are objects to return the same endpoint fails with the following error: ValueError: dictionary update sequence element #0 has length XX; 2 is required Where XX is the number of attributes the object has. This documentation section suggests the view function should act slightly differently when returning an HTML Response object, but I assume this is done by DRF's builtin views when necessary, so I don't think that's the issue. This stackoverflow Q/A also looks relevant but I'm not quite sure it's the right solution to my problem. How can I make my ModelViewSets work with both HTML and JSON renderers? Thanks! -
In Django 1.9 how do I use the currently logged in user as the foreign key value when saving a model
I have a model class matter (models.Model): name = models.CharField(max_length=200) client = models.ForeignKey(client, null=False) created = models.DateTimeField('Date created', auto_now_add=True) user = models.ForeignKey(User, editable=False) last_updated = models.DateTimeField('Last updated', auto_now=True) And a view class MatterCreate(LoginRequiredMixin,CreateView): model = matter fields = ['name','client','matterType'] I need to save user as the id of the currently logged in user when I post to this view. I know I can get the currently logged in user from the request object (request.user.id). My problem is because I am using a generic view I don't have the request object being passed in. I tried to override the post method of the view but this led to other issues regarding me having to return an HTTPResponse object. What is the best way to get the currently logged in user and then update the new record with this user's id? Im using django version 1.9 -
python-social-auth with Django: ImportError: No module named 'social_django'
ALL packages installed!! Hi, I'm using python 3.5 Django==1.10 I installed Python-social-auth executed the command Python manage.py transfer error received! Traceback (most recent call last): File "manage.py", line 22, in execute_from_command_line(sys.argv) File "/home/berluskuni/web_project/exprender/.exprender/lib64/python3.5/site-packages/django /core/management/init.py", line 367, in execute_from_command_line utility.execute() File "/home/berluskuni/web_project/exprender/.exprender/lib64/python3.5/site-packages/django/core/management/init.py", line 341, in execute django.setup() File "/home/berluskuni/web_project/exprender/.exprender/lib64/python3.5/site-packages/django/init.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/home/berluskuni/web_project/exprender/.exprender/lib64/python3.5/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models(all_models) File "/home/berluskuni/web_project/exprender/.exprender/lib64/python3.5/site-packages/django/apps/config.py", line 199, in import_models self.models_module = import_module(models_module_name) File "/usr/lib64/python3.5/importlib/init.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 986, in _gcd_import File "", line 969, in _find_and_load File "", line 958, in _find_and_load_unlocked File "", line 673, in _load_unlocked File "", line 665, in exec_module File "", line 222, in _call_with_frames_removed File "/home/berluskuni/web_project/exprender/.exprender/lib64/python3.5/site-packages/social/apps/django_app/default/models.py", line 1, in from social_django.models import AbstractUserSocialAuth, UserSocialAuth, Nonce, Association, Code, DjangoStorage ImportError: No module named 'social_django' -
Wagtail, how to test PageChooserBlock returns correctly typed page?
so at my company we've recently ran into a problem. We have a custom StructBlock, containing as it's first attribute a PageChooserBlock. page = blocks.PageChooserBlock(required=False) In the StructBlock we then call render(): def render(self, value, context=None): target_page = value['page'].basepage or context.get('page') if target_page is not None: context = context or {} context['new_value'] = target_page.CUSTOM_METHOD_DEFINED_IN_BASEPAGE() return super(CustomStructBlock, self).render(value, context) Now the problem was, that the type of value['page'] was not the actual page chosen, but a related object from the wagtailcore page model. This one didn't have our custom method, and after figuring out that we can add ".basepage" to get our original page back, we now want to test that this will keep working. Any help on how to test this would be much appreciated :) -
Django formset does not save if required field in extra form is empty
I have a model: class ProjectPage(models.Model): page_project = models.ForeignKey(Project, on_delete=models.CASCADE) page_url = models.URLField(verbose_name = "Адрес страницы") page_title = models.CharField(max_length=300, blank=True, verbose_name = "meta-title",default="") page_description = models.CharField(max_length=300, blank=True, verbose_name = "meta-description",default="") page_h1 = models.CharField(max_length=300, blank=True, verbose_name = "Заголовок h1",default="") def __unicode__(self): return self.page_url def __str__(self): return self.page_url Form: class ProjectPageForm(forms.ModelForm): class Meta: model = ProjectPage fields = [ 'page_project', 'page_url', 'page_title', 'page_description', 'page_h1', ] widgets = { 'page_project': forms.HiddenInput() } View: def projects_update(request, proj=None): instance = get_object_or_404(Project, id=proj) form = ProjectFormUpdate(request.POST or None, instance=instance) queryset=ProjectPage.objects.filter(page_project__id=proj) formset_f = modelformset_factory(ProjectPage, form=ProjectPageForm, extra=3) formset = formset_f(queryset=queryset, initial =[{'page_project': proj} for x in range(len(queryset)+3)]) if request.method == 'POST': formset = formset_f(request.POST) if formset.is_valid(): formset.save() if form.is_valid(): form.save() context = { 'title': "Редактируем проект - "+instance.name, 'form': form, 'formset': formset, 'instance': instance, } return render(request, "projects_update.html", context) And, finaly, html <form method="POST" action="" class="create-form"> {{ formset.management_form }} {% csrf_token %} <div class="row"> <div class="col-lg-6 offset-lg-3 col-md-10 offset-md-1 col-xs-10 offset-xs-1 form-bg"> <h2>Общие данные</h2> {{ form|crispy}} <input type="submit" class="btn btn-success" value="Обновить проект" /> </div> </div> {% for formset_form in formset %} <div class="row form-container"> <div class="col-lg-6 offset-lg-3 col-md-10 offset-md-1 col-xs-10 offset-xs-1 form-bg"> <h3>Страница {{forloop.counter}}</h3> {{ formset_form|crispy}} </div> </div> {% endfor %} </form> My problem is: when I try … -
How to group querysets by attributes in Django
I have this data structure: class Currency(Model): name = CharField() ... class Invoice(Model): currency = ForeignKey(Currency) ... I would like to filter all Invoices grouping them by Currencies. I would like the result to be something like this: { 'USD': '<INVOICES_QUERYSET_FOR_USD>', 'EUR': '<INVOICES_QUERYSET_FOR_EUR>', ... } Is there an easy way to achieve this or do I have to mount the dictionary myself? I know Annotate gives a similar result, but I just want to group the Queryset by a common attribute value. -
How tosave django output in json file?
I want to save django output in .json file. How should I do this? I have a geojson data in my django output . I want to save that output in .json file. My output is already in json format but only problem is that in django, the output is in arrary format( i.e output is enclosed in close brackets). So, I can't use that output directly so, I think first saved it in json file then used that. Any idea how to do that? -
How to access Models.py from external py script?
I want to integrate my existing code into django. How can I access models.py from external code.I tried putting it in the same application directory but it did not work. Case Scenario: Having a web parsing code that takes data from the web and prints it. Here I am integrating it with django so as to save that data in the db and print it out in the web page. I'm trying the input to get from the webpage and when I hit submit it triggers the parsing code and gives output on the page. I have the Django server up and running, created the apps (startapp), have the table created via models.py, have the urls.py setup. Here my question is how or where do I put my external code to make it trigger to access models .py, will it execute by itself when I start the server and hit the submit button ( i know i have to configure this one). -
How to output model data into a csv document?
Hello i am trying to make a simple script to output the items in the componant table that have "Show on sight" selected. This sounds simple. But iv had so many probelms i have had to go right back to beggining to see where im going wrong and i found what is giving me such a pain. import csv with open('test.csv', 'w', newline='') as fp: a = csv.writer(fp,delimiter=',') data=[['stock','sales'], ['100','24'], ['200','50'], ['23','5']] a.writerows(data) This works fine, but i need to get data from the models and the model is here from twm.component.models import Components once this is in the script i get an error telling me that setting are not configured, I must either define the eviroment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. What i dont understnad is, i have set this variable in setting.py, and im useing this line of code to access data in other parts or the project(in same directory) do it should be no different. Full Traceback C:\Users\Staff\Documents\tsl\twm>python monthly_repairs.py Traceback (most recent call last): File "monthly_repairs.py", line 2, in <module> from twm.component.models import Components File "C:\Users\Staff\Documents\tsl\twm\twm\component\models.py", line 11, in <module> from filer.fields.image import FilerImageField File "C:\Python34\lib\site-packages\django_filer-1.2.4-py3.4.egg\filer\fields\image.py", line 4, in <module> from ..models import Image …