Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
can't properly use django scoket io
Am trying to use django socket io. I included djangoscoketio in my installed apps and icnluded django_socketio.urls in my urls.py. I keep on getting this error KeyError: 'socketio' when executing socket = SocketIOChannelProxy(request.environ["socketio"]) in django_socketio/views.py. Can you please help me. am using socket io for the first so i really dont know what info should i post in order to well desfcribe my problem but i ready to interact with u and provide more info thank u in advance -
How can I use the "bootstrap datetimepicker" in a django (wizard) form
I spent hours looking after the good way to use "bootstrap datetimepicker" in my django form. What I would like to do is incorporate a timepicker (HH:MM) in a (wizard) form. I found some app (https://github.com/nkunihiko/django-bootstrap3-datetimepicker) but I actually don't know how to use them just to pick the time (without the date). If someone could explain me the cleanest and easiest way to incorporate a nice time picker in a django form it would me amazing because i'm getting crazy... Thanks -
Re-evaluate new objects every time a view/context processor is used in Django?
I need to make queries every time a view or a context processor is used. At the moment I used a queryset. But I realized that I can't use that for my case. I need to make a query like the queryset to retrieve the latest objects in the database. I need to actually re-evaluate it again so that the users see new objects. This is what I use at the moment: class EntryListView(ListView): model = Entry def get_context_data(self, **kwargs): context = super(EntryListView, self).get_context_data(**kwargs) context.update({ 'all_entries': Entry.objects.filter(status=2, publish_date__lte=datetime.date.today())[:40], }) return context How can I make a query so that it will get the latest 40 objects each time the view or context processor is used? The result now is that it using a cached version. So it never updates on the site. -
Django forms and "back" button on multi-forms
My Django app has multi-page forms. Starting with the second form there's a "back" button on the form. Let's assume my form has 2 pages. When I'm done with form 1, and I have my django Forms object with the content that's validated --- is it acceptable practice to save the form object in the session, so that if I'm clicking "back" from form 2, I'd just load up the form 1 "Form Object" from the session and just feed it to the rendered form 1? I realize I can do this field by field, but doesn't it make more sense to retain the entire form? -
Django use Integer Field as ForeignKey field
To support old (legacy) db we have to create a table that using integer field as a foreignkey to User table: This is how our model look like: class UserHistory(): user_id = models.IntegerField(null=True, blank=True) # ..... (other fields) ..... Problem is user id may or may not exist in User table. Is there any way to treat that user_id field as foreign key to user talbe (when it exist)? So I can dis play on django admin or other place instead of just the ID. -
Making existing fields translatable(Django)
I am trying to translate already existing fields on a model class. I got stuck at the very first step, which is subclassing TranslatableModel class in Category, and adding TranslatedFields wrapper to translate selected model fields. I am following a book 'Django by Example' as well as the django-parler instructions on how to do that, however I am getting the following error: File ..../env/lib/python3.5/site-packages/parler/models.py", line 965, in contribute_translations raise TypeError("The model '{0}' already has a field named '{1}'".format(shared_model.__name__, name)) TypeError: The model 'Category' already has a field named 'name' before applying django-parler: # models.py class Category(models.Model): name = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=200, unique=True) class Meta: ordering = ('name',) verbose_name = 'category' verbose_name_plural = 'categories' def __str__(self): return self.name def get_absolute_url(self): return reverse('shop:product_list_by_category', args=[self.slug]) after applying django-parler: # models.py class Category(TranslatableModel): name = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=200, unique=True) translations = TranslatedFields( name = models.CharField(max_length=200, db_index=True), slug = models.SlugField(max_length=200, unique=True), ) class Meta: # ordering = ('name',) verbose_name = 'category' verbose_name_plural = 'categories' def __str__(self): return self.name def get_absolute_url(self): return reverse('shop:product_list_by_category', args=[self.slug]) -
Django form error as
I wish to take an error from my form and return it as a bootstrap warning. Warning example as follows: <div class="alert alert-danger"> <strong>Danger!</strong> Indicates a dangerous or potentially negative action. </div> The form is as follows: class SelectTwoTeams(BootstrapForm): team1 = forms.ModelChoiceField(queryset=StraightredTeam.objects.none(), empty_label=None) team2 = forms.ModelChoiceField(queryset=StraightredTeam.objects.none(), empty_label=None) def __init__(self, *args, **kwargs): user = kwargs.pop('user', None) super(SelectTwoTeams, self).__init__(*args, **kwargs) campaignnoquery = UserSelection.objects.filter(user=user).order_by('-campaignno')[:1] currentCampaignNo = campaignnoquery[0].campaignno cantSelectTeams = UserSelection.objects.filter(campaignno=currentCampaignNo) queryset = StraightredTeam.objects.filter(currentteam = 1).exclude(teamid__in=cantSelectTeams.values_list('teamselectionid', flat=True)) self.fields['team1'].queryset = queryset self.fields['team2'].queryset = queryset def clean(self): cleaned_data = self.cleaned_data # individual field's clean methods have already been called team1 = cleaned_data.get("team1") team2 = cleaned_data.get("team2") if team1 == team2: raise forms.ValidationError("You picked the same two teams!") return cleaned_data View is as follows: def selectteams(request, soccerseason, fixturematchday,*args,**kwargs): if request.method == 'POST': form = SelectTwoTeams(request.POST,user=request.user) if form.is_valid(): return HttpResponse("Two different teams were selected.") else: form = SelectTwoTeams(user=request.user) return render(request, 'meta/selectteams.html', 'form': form}) And the form part of selectteams.html is: <form action="" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Submit" /> </form> As it stands it works perfectly but I get an ugly looking bullet point list type error. Can i use the bootstrap alert message as mentioned above? Many thanks in advance for any help, alan. -
How to apply a djngoFilterBackend in a detail_route() viewset
I want to use django filters in a view which has some other behaviour, without returning viewset retrieve or list methods. My code is the following: class ArticleView(ReadOnlyModelViewSet): serializer_class = get_serializer_class(Article) queryset = Article.objects.all() filter_backends = (filters.DjangoFilterBackend,) filter_fields = ('TYPE',) @detail_route() def articles(self, request, pk=None): some_behaviour() return MY QUERYSET (which can or cannot be modified) FILTERED so by hitting /api/articles and its derivates the queryset gets filtered correctly, also if i return self.retrieve(request) (obviously), but i am not able to modify my queryset. Then my question is, what is needed to apply django filters EXPLICITLY in that situation, or how can i tell him to do that instead of doing request.query_string.pop(bla bla bla). Thanks! -
Django template language and javascript
The html code below produces two links that when hovered will output the corresponding audio file. My question is if I have a table of links stored in a Django database how do I output it in the javascript so that using the Django template language I can loop over the table of links to populate the window.onload function? Or is there a more efficient way? <head> <script type="text/javascript"> window.onload = function() { // collecting elements var welcomeSound = document.getElementById('welcomeSound'); var welcomeTxt = document.getElementById('welcomeTxt'); var sdSound = document.getElementById('shutdownSound'); var sdTxt = document.getElementById('shutdownTxt'); //playing welcome sound on mouse over welcomeTxt.onmouseover = function() { welcomeSound.play(); return false; }; sdTxt.onmouseover = function() { sdSound.play(); return false; }; }; </script> </head> <html> <section> <audio id="welcomeSound" controls="controls" preload="auto"> <source src="welcome.ogg"></source> Your Browser does not support please use (Firefox 3.5+, Chrome 3+, Opera 10.5+, Safari 4+, IE 9+) browsers. </audio> <audio id="shutdownSound" controls="controls" preload="auto"> <source src="shutdown.ogg"></source> Your Browser does not support please use (Firefox 3.5+, Chrome 3+, Opera 10.5+, Safari 4+, IE 9+) browsers. </audio> <p class="info"> Use latest Browser Chrome or FireFox. <br /> If you usig Internet download manager please close it. </p> <a id="welcomeTxt" href="#"> Welcome(Mouse hover here) </a> <br /> <br /> … -
Django: AttributeError - 'unicode' object has no attribute 'status'
I am getting the following AttributeError: Environment: Request Method: POST Request URL: http://192.168.33.10.xip.io:8000/episodeclicktotweet/2/ Django Version: 1.9 Python Version: 2.7.6 Installed Applications: ('producer', 'django.contrib.admin', 'registration', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'storages', 'django_extensions', 'randomslugfield', 'adminsortable2', 'crispy_forms', 'charsleft_widget') Installed Middleware: ('django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware') Traceback: File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response 149. response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response 147. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python2.7/dist-packages/django/views/generic/base.py" in view 68. return self.dispatch(request, *args, **kwargs) File "/home/vagrant/fullcast_project/producer/views/views.py" in dispatch 97. return super(ProductionRequiredMixin, self).dispatch(request, *args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/django/views/generic/base.py" in dispatch 88. return handler(request, *args, **kwargs) File "/home/vagrant/fullcast_project/producer/views/views.py" in post 1141. autogenerate_click_to_tweet_if_needed(tweet) File "/home/vagrant/fullcast_project/producer/helpers/__init__.py" in autogenerate_click_to_tweet_if_needed 63. meets_criteria = production.status() == 'Published' Exception Type: AttributeError at /episodeclicktotweet/2/ Exception Value: 'unicode' object has no attribute 'status' I have this form where I have a field where the user can input his tweet text and submit it. It will go into the DB but thats it. The thing though is that I want to have an additional button where it can generate the click to tweet link and an additional field where it will display the link that just created. This is what I am trying implement to generate the link in my views.py: if … -
How do I move project folders in Pycharm Project View?
I'm using Pycharm to do a few django projects and I have them all open in the Project View to the left. I'd like to move the project I'm currently working on to the bottom of the list to avoid confusion. Pycharm does not let me do this by default. Are there some settings that need tweaking before I can do this? Take a look at this screenshot. What I want to do is to be able to is to click and drag 'Django_pro' to the bottom of the list and then expand the tree. Can this be achieved? Thank you! -
django-haystack custom search form failed filtering indexed field
So I am building a custom search form that comes with a search_type field and a search_content field. I would like the user to select from search_type which field he or she would like search for, and put the key word in search_content to search exactly for that specific field. Currently I have the code below: class Equipment(models.Model): asset_number = models.CharField(max_length = 200, null=True) class EquipmentIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) asset_number = indexes.CharField(model_attr='asset_number') def get_model(self): return Equipment def index_queryset(self, using=None): """Used when the entire index for model is updated.""" return self.get_model().objects.filter(timestamp__lte=datetime.datetime.now()) class MultipleSearchForm(SearchForm): search_type = forms.ChoiceField(required = False, choices = SEARCH_CHOCIES) search_content = forms.CharField(required = False) def search(self): sqs = super(MultipleSearchForm, self).search() if not self.is_valid(): return self.no_query_found() schoice = self.cleaned_data['search_type'] scontent = self.cleaned_data['search_content'] if schoice: if scontent: if schoice == 'Asset #': sqs = sqs.filter(asset_number == scontent) return sqs But when I try to run this, it gives me error NameError at /calbase/search/ name 'asset_number' is not defined at this line: sqs = sqs.filter(asset_number == scontent) complaining that asset_number is not defined. However I thought that in the tutorial, if you already set asset_number in EquipmentIndex, I could just use this in SearchForm. What's wrong here? -
Celery BROKER_URL with vhosts not properly recognized
I have a problem connecting to a RabbitMQ vhost via BROKER_URL. My vhost name is navarro which rabbitmqctl shows: $ rabbitmqctl list_vhosts / navarro $ However, with BROKER_URL = 'amqp://guest:guest@localhost:5672/navarro' I get error: [Errno 104] Connection reset by peer and "access to vhost '/' refused for user 'guest'" in my logfile (guest is only configured for my vhost, note it is not the auth issue but the vhost issue that is the problem). If I use BROKER_URL = 'amqp://guest:guest@localhost:5672//navarro' I get "access to vhost '/navarro' refused for user 'guest'" which makes sense since there is no vhost vhost. Writing this I got the idea to allow the user guest also on '/', will let you know whether it helps. -
select2: not able to include the source in the html file
Getting the error: GET http://127.0.0.1:8000/main/path/to/select2.min.js 404 (NOT FOUND) -
How to unpack the list created by zip()
I have two lists that I zip() together: >> x1 = ['1', '2', '3'] >> y1 = ['a', 'b', 'c'] >> zipped = zip(x1, y1) As expected so far: >> print(list(zipped) [('1', 'a'), ('2', 'b'), ('3', 'c')] From the docs, it seems like I can just do this to get back the two lists from the zip object: >> x2, y2 = zip(*zipped) But instead I get the error: Traceback (most recent call last): File "/usr/lib/python3.5/site-packages/IPython/core/interactiveshell.py", line 2869, in run_code exec(code_obj, self.user_global_ns, self.user_ns) File "<ipython-input-6-58fe68d00d1c>", line 1, in <module> x2, y2 = zip(*zipped) ValueError: not enough values to unpack (expected 2, got 0) Obviously I'm not understanding something simple about the zip object. Edit: As @daragua points out below, the print(list(zipped)) was actually consuming the zipped object, thus making it empty. That's true, for my simple example. I'm still having an issue with my real code. What I'm trying to to is write a unit test for Django view that has a zipped object in it's context. The view works fine, I'm just struggling writing the test for it. In my view context I have this: for season in context['pools']: commissioner.append(season.pool.is_commish(self.request.user)) context['pools'] = zip(context['pools'], commissioner) This works as expected. The … -
'NotImplementedType' object is not iterable django-easy-pdf
I use django-easy-pdf library for my project. When I try to set custom cyrillic font I have TypeError: 'NotImplementedType' object is not iterable I`ve seen where the error appear and here is what I got Looks like I have a problem with src url, but I have no idea how to solve this issue. I`ve tried change src: url() different ways (manual input,{% static 'path' %}, etc) , but it is not working. I really stuck. Django = 1.10, Python = 3.4.3 Here`s my template. {% extends "easy_pdf/base.html" %} {% load staticfiles %} {% block extra_style %} <style type="text/css"> @font-face { font-family: Palatino Linotype; src: url({% static 'automobiles/fonts/bold.ttf' %}); } body{ font-family: "Palatino Linotype", Arial, sans-serif; color: #333333; } </style> {% endblock extra_style %} {% block content %} <div class="container"> <h1>PYTHON3 RULES</h1> <p>Это должно работать</p> <h3>Но библиотеке что-то не нравится</h3> </div> {% endblock content %} Project structure: settings.py -
Google Polymer: google-map-search doesn't work
<paper-dialog id="post" entry-animation="scale-up-animation" exit-animation="fade-out-animation"> <div class="find-area"> <paper-textarea on-input="find" id="find_textarea" class="find-place-text" label="Find your place" maxlength="250"></paper-textarea> </div> <div class="map-area"> <google-map id="[[map]]" api-key="000000000myapi000000" latitude="[[lat]]" longitude="[[lon]]" fit-to-markers> </google-map> <google-map-search id="google_search" globalSearch="true" map="[[map]]" results="[[results]]"> </google-map-search> </div> <paper-button on-tap="[[upload]]">Accept</paper-button> <label>coords:[[ results::lat ]], [[ results::lon ]]</label> <label>query:[[ query ]]</label> <label>map:[[ map ]]</label> <label>results:[[results]]</label> </paper-dialog> <script> function _showPosition(position) { try { x.latitude = position.coords.latitude; x.longitude = position.coords.longitude; }catch (err){ alert(err+'; position:'+position) } } function showError(error) { alert('error:'+ error) }*/ function _submit(event) { Polymer.dom(event).localTarget.parentElement.submit(); } Polymer({ is: 'profile-new-post', properties: { enable : { type: Boolean, value: true }, lat : { value : 37.77493 }, lon : { value : -122.41942 }, query : { type : String, value : "" }, results : { type : Array }, map : { type : Object } }, func : function (e) { this.map = this.$.map; post.open(); }, find : function (e) { this.$.google_search.query = this.$.find_textarea.value; this.query = this.$.google_search.query; this.$.google_search.search(); this.lat = this.$.google_search.results.latitude; this.lon = this.$.google_search.results.longitude; //alert(this.$.google_search.results.latitude + '; ' + this.$.google_search.results.longitude) }, I'm trying to use [[]] brackets because of django use {{}}. Map, results and coords are empty at output lables. It shows map with San Francisco but when i try to print text in input it doesn't … -
Django 1.10: django-storages on S3 error: Not naive datetime (tzinfo is already set)
I've started getting an error since upgrading to Django 1.10. I'm running Django 1.10 on Python 3.5 with django-storages==1.5.0 and boto3==1.4.0. You have requested to collect static files at the destination location as specified in your settings. This will overwrite existing files! Are you sure you want to do this? Type 'yes' to continue, or 'no' to cancel: yes Traceback (most recent call last): File "./manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/home/vagrant/.virtualenvs/wrds-classroom/lib/python3.5/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/home/vagrant/.virtualenvs/wrds-classroom/lib/python3.5/site-packages/django/core/management/__init__.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/vagrant/.virtualenvs/wrds-classroom/lib/python3.5/site-packages/django/core/management/base.py", line 305, in run_from_argv self.execute(*args, **cmd_options) File "/home/vagrant/.virtualenvs/wrds-classroom/lib/python3.5/site-packages/django/core/management/base.py", line 356, in execute output = self.handle(*args, **options) File "/home/vagrant/.virtualenvs/wrds-classroom/lib/python3.5/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 193, in handle collected = self.collect() File "/home/vagrant/.virtualenvs/wrds-classroom/lib/python3.5/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 124, in collect handler(path, prefixed_path, storage) File "/home/vagrant/.virtualenvs/wrds-classroom/lib/python3.5/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 337, in copy_file if not self.delete_file(path, prefixed_path, source_storage): File "/home/vagrant/.virtualenvs/wrds-classroom/lib/python3.5/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 258, in delete_file target_last_modified = self.storage.get_modified_time(prefixed_path) File "/home/vagrant/.virtualenvs/wrds-classroom/lib/python3.5/site-packages/django/core/files/storage.py", line 231, in get_modified_time return _possibly_make_aware(dt) File "/home/vagrant/.virtualenvs/wrds-classroom/lib/python3.5/site-packages/django/core/files/storage.py", line 243, in _possibly_make_aware return timezone.make_aware(dt, tz).astimezone(timezone.utc) File "/home/vagrant/.virtualenvs/wrds-classroom/lib/python3.5/site-packages/django/utils/timezone.py", line 368, in make_aware return timezone.localize(value, is_dst=is_dst) File "/home/vagrant/.virtualenvs/wrds-classroom/lib/python3.5/site-packages/pytz/tzinfo.py", line 304, in localize raise ValueError('Not naive datetime (tzinfo is already set)') ValueError: Not naive datetime (tzinfo is already set) Changeing USE_TZ to False changes the error, but I'm still not … -
What is Meta class for in python\django?
I see in many tutorial a code which looks like this: class books(forms.ModelForm): class Meta: # and alot of code right here Why should I use the Meta Class? And why it doesn't have those () which came after any class definition? -
Adding another select field to django admin interface
So in one app i have four models. From first to last they are name 'brand', 'mark', 'type', 'engine'. Mark has a foreign key to brand, type has a foreign key to mark, and engine has one to type. In the admin interface when I add a mark I get a dropdown list to choose from all the Brands. When I add a type, I get a dropdown list to choose from all the Marks. What I want: when I am adding a Type, I want to also be able to choose the Brand from a dropdown list, and that choice, to filter the next dropdown from Marks. -
Check django permission or operator?
For my view, I am checking the permission through the @permission_required decorator but I really wish to check for "either" permission A or permission B. so if user has at least one of two permissions, the view is execute... Is there a way to do this? -
Django Queryset Help using data aggregation
I am trying to reproduce a mysql query that looks like the following: "select subjects, sum(count) as Count from TOP_Subjects where Date >= DATE_ADD(CURDATE(), INTERVAL - 7 DAY) group by subjects order by Count desc limit 10;" The DB has 4 columns, uid, date, subject, count. The above will sum any duplicate subjects counts and then order them from top count hits to lower hits. I am trying to reproduce this in django query and I am unable to get any duplicate subjects to sum their counts together. Any help would be appreciated. TopSubjects.objects.filter(date__range=(start_7_date, end_date)).values('subjects').annotate(counts=Sum('count')).order_by('-count')[:10] -
Django database models - messages and recipients: many-to-many or many-to-one?
I am using MySQL for my database and have the following Message model in my Django app: class Message(models.Model): sender = models.ForeignKey(User, on_delete=models.CASCADE, null=True, related_name='sender_notification') recipient = models.ForeignKey(User, on_delete=models.CASCADE, related_name='recipient_notification') message = models.TextField() read = models.BooleanField(default=False) recieved_date = models.DateTimeField(auto_now_add=True) If I am not mistaken, this way the relationship between recipient/User and Message is one-to-many, since a single Message record can only have one recipient, but a User might have many records in the Message table. However, there will be situations where I want to send the same Message to multiple Users. With my current schema, I can just add multiple Message records, one for each recipient, with the same message text. However, this seems like a lot of duplication. In this case, would my relationship make more sense as a many-to-many one? Initially I thought the duplication (multiple Messages with the same message field but different recipient fields) was a bad idea, but the more I think about it, it seems like modeling the many-to-many relationship would actually be more difficult, and require more data. Each Message record has a read field to indicate whether the recipient has read the message or not. If I have a single Message record … -
Access localhost on windows
I'm running on a windows 64 bits machine, i cannot access any process running on my localhost, for example. I tried to launch a django project, everything seems to work fine. python manage.py runserver Django server works fine but when i launch a client, i keep waiting but nothing happens. Same goes with Node JS and Wild-fly server . I tried to run the servers using administrative privileges but nothing seems to fix it. -
django rest framework multiple foreign keys serializing
at first it looked simple, now I got confused. I wrote data structure and now struggling to get it. So far what I have: class Area(models.Model): name = models.CharField(max_length=128) ... class Category(models.Model): name = models.CharField(max_length=128) .... class Venue(models.Model): name = models.CharField(max_length=128) category = models.ForeignKey(Category, related_name='venues') area = models.ForeignKey(Area, related_name='venues') And I need based on Area pk get categories with venues in it. Is it possible to do so using django rest framework? The result should look something like: { "pk": 1, "name": "London", "categories": [ { "pk": 1, "name": "Bars", "venues": [ { "pk": 1, "name": "Cool bar" }, { "pk": 2, "name": "Cooler bar" }, { "pk": 3, "name": "Coldest bar" }, ] } ] } Ideally I need something like this: class VenueSerializer(serializers.ModelSerializer): ..... class CategorySerializer(serializers.ModelSerializer): venues = VenueSerializer(read_only=True, many=True) class Meta: model = Category fields = ('pk', 'name', 'venues', ) class AreaSerializer(serializers.ModelSerializer): categories = CategorySerializer(read_only=True, many=True) class Meta: model = Area fields = ('pk', 'name', 'categories', ) But of course this will not work since Area is not directly related to Category. So my question, is it possible to do this without changing data structure?