Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Which PIP Returns Global Instead of VirtualEnv
I am setting up a Django app to run on Apache using WSGI. I created a virtualenv inside the project's directory on my Mac, installed Django in there and made sure it worked. I get the following results on the Mac after I run source ./virt_name/bin/activate: which python -> /Users/user/www/sites/Playground/Django-tut/app_name/app-env/bin/python which python3 -> /Users/user/www/sites/Playground/Django-tut/app_name/app-env/bin/python3 which pip -> /Users/user/www/sites/Playground/Django-tut/app_name/app-env/bin/pip I then take the same app directory and transfer it (using Git) to an EC2 instance. After I activate the virtual environment (seemingly successfully), I get the following: which python -> /usr/bin/python which python3 -> /usr/bin/python3 which pip -> /usr/bin/pip Is this an expected behavior? How can I fix this? It is my understanding that when one activates a virtualenv, the binaries should be "picked up" from there instead of the system directories? P.S. This is preventing the mod_wsgi from finding the Django included in the virtualenv and thus the app from running successfully. -
Could not parse the remainder: '(song)' from 'playlist.songs.add(song)'
Here are my Playlist & Song model : models.py class Song(models.Model): song_title = models.CharField(max_length=200, null=False, blank=False) def __str__(self): return self.song_title class Playlist(models.Model): name = models.CharField(max_length=200, null=False, blank=False,default='') songs = models.ManyToManyField('Song') def __str__(self): return self.name @property def playlist_id(self): return self.id Here is my template : <div class="dropdown"> <button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">Add to playlist<span class="caret"></span></button> <ul class="dropdown-menu"> {% for playlist in all_playlists %} <li><button onclick="{{playlist.songs.add(song)}}">{{playlist.name}}</button></li> {% endfor %} </ul> </div> When the user clicks the drop down button 'Add to playlist', it shows a drop down list of playlists. But what I want is when the user clicks on the playlists, the song should get added to the songs field of the playlist. For that purpose, I created a button with action = playlists.songs.add(song).When I render it, it returned this error: Could not parse the remainder: '(song)' from 'playlist.songs.add(song)' So I fired up django shell and then typed the same thing, it worked in the shell but not in the template. Here is my shell log. In [1]: from music.models import Song, Playlist In [2]: s = Song.objects.get(pk=2) In [3]: p1 = Playlist.objects.get(pk=2) In [4]: p1.songs.add(s) In [5]: p1.songs.all() Out[5]: [<Song: Shape of you>] Your help would be very much … -
Place to find and market open source developers tools?
Is there any website where i can find open source developers resources + i can market my own open source development works ? -
Run celery with Django start
I am using Django 1.11 and Celery 4.0.2. We are using a PaaS (OpenShift 3) which runs over kubernetes - Dockers. I am using a Python image, it knows only how to run one command on start (and follow for exit code - restart if fails), How can I run celery worker in the same time I am running Django to make sure that failure of one of them will kill the both process (worker and Django) Thank you! -
Django about get_context_data()
I was looking in django source-code to understand super(ExampleView, self).get_context_data(**kwargs) and why I used it in my view: class ExampleView(TemplateView): # ... atributes def get_context_data(self, **kwargs): context = super(ExampleView, self).get_context_data(**kwargs) context['key'] = 'value' return context I've found: class ContextMixin(object): """ A default context mixin that passes the keyword arguments received by get_context_data as the template context. """ def get_context_data(self, **kwargs): if 'view' not in kwargs: kwargs['view'] = self return kwargs I can't figure it out what that condition or kwargs['view'] = self does. I've tried in my view to overwrite get_context_data() without that default condition: class ExampleView(TemplateView): # .. atributes def get_context_data(self, **kwargs): kwargs['key'] = 'value' return kwargs and it worked the same as the first code I've written. -
File writing in Django keeps having IOError
I'm running my app locally and I'm currently having an IOError during my file creation from the database. I am using Django 1.10, MongoDB as my database, and Celery 4.0.2 for my background tasks. The problem occurs in the tasks.py since that is where I access the db then store it in my django subfolder 'analysis_samples'. Here is the traceback: [2017-04-15 15:31:08,798: ERROR/PoolWorker-2] Task tasks.process_sample_input[0619194e-4300-4a1d-91b0-20766e048c4a] raised unexpected: IOError(2, 'No such file or directory') Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/celery/app/trace.py", line 367, in trace_task R = retval = fun(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/celery/app/trace.py", line 622, in __protected_call__ return self.run(*args, **kwargs) File "/home/user/django_apps/myapp/analysis/tasks.py", line 218, in process_sample_input with open(sample_file_path, "w+") as f: IOError: [Errno 2] No such file or directory: u'/home/user/django_apps/myapp/myapp/analysis_samples/58f1cc3c45015d127c3d68c1' And here is the snippet of tasks.py: from django.core.files import File sys.path.append(settings.ANALYSIS_SAMPLES) import base64 import os, sys @shared_task(name='tasks.process_sample_input') def process_sample_input(instance_id): instance = Sample.objects.get(pk=instance_id) #many code here.. try: conn=pymongo.MongoClient(settings.MONGO_HOST, settings.MONGO_PORT) db = conn.thugfs #connect to GridFS db of thug thugfs_db = GridFS(db) except pymongo.errors.ConnectionFailure, e: logger.error("Could not connect to ThugFS MongoDB: %s" % e) sample_file_folder = settings.ANALYSIS_SAMPLES for sample_fs_id in sample_fs_ids: sample_file = thugfs_db.get(ObjectId(sample_fs_id)).read() sample_file = base64.b64decode(sample_file) #decode file from database sample_file_path = os.path.join(sample_file_folder, sample_fs_id) with open(sample_file_path, "w+") as f: fileOut = … -
Where is a django validator function's return value stored?
In my django app, this is my validator.py from django.core.exceptions import ValidationError from django.core.validators import URLValidator def validate_url(value): url_validator = URLValidator() url_invalid = False try: url_validator(value) except: url_invalid = True try: value = "http://"+value url_validator(value) url_invalid = False except: url_invalid = True if url_invalid: raise ValidationError("Invalid Data for this field") return value which is used to validate this : from django import forms from .validators import validate_url class SubmitUrlForm(forms.Form): url = forms.CharField(label="Submit URL",validators=[validate_url]) When I enter URL like google.co.in, and print the value right before returning it from validate_url, it prints http://google.co.in but when I try to get the cleaned_data['url'] in my views, it still shows google.co.in. So where does the value returned by my validator go and do I need to explicitly edit the clean() functions to change the url field value?? The doc says the following: The clean() method on a Field subclass is responsible for running to_python(), validate(), and run_validators() in the correct order and propagating their errors. If, at any time, any of the methods raise ValidationError, the validation stops and that error is raised. This method returns the clean data, which is then inserted into the cleaned_data dictionary of the form. I am still not … -
select multiple checkboxes and get the values in Python Django
I have a html table and in that, the last column is for checkbox. so when I check to this multiple checkboxes from that column,it should get the selected values.and then I want to send this list of values to a python function. Can anyone please help me on it? <table id="test-datatable" class="table table-bordered"> <thead> <tr> <th>Id</th> <th>First Name</th> <th>Last Name</th> <th>Address</th> <th>Occupation</th> <th><input name="select_many" id ="select_many" value="1" `type="checkbox"></th> </tr> </thead> </table> -
Save model with @transaction.atomic in class based view
I am trying to handle both add new and edit object. My views.py file is like- personal_data=Personal.objects.create(emp_fname=first_name, emp_mname=middle_name, emp_lname=last_name) # rest of object is created here try: print "pk", pk with transaction.atomic(): if pk != None: print "hey" #save model goes here messages.add_message(request, messages.INFO, 'Data updated successfully') else: print "hello" personal_data.save() family_data.save() address_data.save() education_data.save() pre_company_data.save() messages.add_message(request, messages.INFO, 'Data saved successfully') except IntegrityError: handle_exception() if-else condition works properly but data is saved in both cases. even if I commented the code shown above still data goes to database. -
File uploads in Heroku deployment with Django
So I was finally able to set up local + prod test project I'm working on. # wsgi.py from dj_static import Cling, MediaCling application = Cling(MediaCling(get_wsgi_application())) application = DjangoWhiteNoise(application) I set up static files using whitenoise (without any problems) and media (file uploads) using dj_static and Postgres for local + prod. Everything works fine at first... static files, file uploads. But after the Heroku dynos restart I lose all the file uploads. My question is, --- Since I'm serving the media files from the Django app instead of something like S3, does the dyno restart wipe all that out too? PS: I'm aware I can do this with AWS, etc, but I just want to know if thats the reason I'm losing all the uploads. -
Django Form Validation Error?
I'm trying to run and validate a form but having some problem. Instead of displaying the form it renders the template which I put to display when the form is not valid. Here is my Model: class Preference(models.Model): CLASS_CHOICES = [('1', '1'), ('2', '2'), ('3', '3')] BOARD_CHOICES = [('C', 'CBSE'), ('I', 'ICSE'), ('S', 'State Board')] SLOT_CHOICES = [('M', 'Morning'), ('A', 'AfterNoon'), ('E', 'Evening')] SUBJECT_CHOICES = [('H', 'HINDI'), ('M', 'MATH'), ('E', 'ENGLISH')] LOCATION_CHOICES = [('M', 'My Home'), ('T', 'I am willing to travel')] GENDER_CHOICES = [('M', 'Male'), ('F', 'Female'), ('B', 'Both are Fine')] Class = models.CharField(max_length=2, choices=CLASS_CHOICES, default='1', blank=False) Board = models.CharField(max_length=2, choices=BOARD_CHOICES, default='C', blank=False) Subject = models.CharField(max_length=2, choices=SUBJECT_CHOICES, default='M', blank=False) Frequency = models.IntegerField(default=7) Slot = models.CharField(max_length=2, choices=SLOT_CHOICES, default='E', blank=False) Location = models.CharField(max_length=2, choices=LOCATION_CHOICES, default='M', blank=False) Gender = models.CharField(max_length=2, choices=GENDER_CHOICES, default='M', blank=False) Address = models.CharField(max_length=250, blank=True) Travel = models.IntegerField(default=5) Name = models.CharField(max_length=50, blank=True) Contact = models.IntegerField(default=100) Here is my form: class PreferenceForm(forms.ModelForm): class Meta: model = Preference fields = ['Class', 'Board', 'Subject', 'Frequency', 'Slot', 'Location', 'Gender', 'Address', 'Travel', 'Name', 'Contact'] widgets = { 'Board': forms.RadioSelect(), 'Subject': forms.CheckboxSelectMultiple(), 'Slot': forms.CheckboxSelectMultiple(), 'Location': forms.CheckboxSelectMultiple(), 'Gender': forms.RadioSelect()} And here is my view: def pref2(request): form = PreferenceForm(request.POST or None) if form.is_valid(): prefer = form.save(commit=False) prefer.save() … -
Django search functionality
I added a search functionality to my website, such that if you goto www.mywebsite.com/search/texthere , it displays all the songs with title=texthere. I would like to add this functionality to my index page. In my page, there is an input box where users could type the input and the press submit to submit the input but it goes to some another page. How can I solve this? urls.py url(r'^search/(?P<query>[\w\-]+)/$', views.search, name='search'), index.html <form action="/search/"> <input type="text" name="query" value="me"><br> <input type = "submit"> </form> What I want is when the user clicks submit button, the text from the input box should be used as the query in urls.py -
How to link a comment to a single post in django?
I have a problem which I want to help me solve. I have a "Post" with comments included but, when I comment a "Post" the comment I made in "Post 1" appears in "Post 2" and in all "Posts" and I want to link the comment to a single post, I've been looking for solutions but I have not been able to make it work. models.py class Comment(models.Model): book = models.ForeignKey(Book, related_name='cooments') user = models.ForeignKey(User, unique=False) text = models.CharField(max_length=250) created_date = models.DateTimeField(default=timezone.now) approved_comment = models.BooleanField(default=False) views.py @login_required def add_comment_to_book(request, pk): book = get_object_or_404(Book, pk=pk) if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.book = book comment.user = request.user comment.save() return redirect('book_detail', slug=book.slug) else: form = CommentForm() return render(request, 'comments/add_comment_to_book.html', {'form':form}) my add_comment.html, this code fragment is included on my book_detail.html <form action="{% url 'add_comment_to_book' pk=book.pk %}" method="post"> {% csrf_token %} {{form.as_p}} <input type="submit" class="btn btn-primary" value="Comentar"> </form> my book_detail.html <div class="container"> <div class="row"> <div class="col-md-6 comment" style="text-align: center;"> <!-- HERE IS WHERE I INCLUDE THE add_comment.html --> {% include 'comments/add_comment_to_book.html' %} </div> {% for comment in comments %} {% if user.is_authenticated or comment.approved_comment %} <div class="col-sm-6 col-sm-offset-1"> <div class="media-body"> <div class="well well-lg"> <div class="avatar"> <img src="{{comment.user.profile.pic.thumbnail.url}}" … -
Implementing The Twitter API in Django
Earlier today I created a Twitter application and received API credentials. Then I did the command for a successful installation: sudo -H pip3 install twitter After this I found these instructions for Django implementation for Twitter API based on Django models. I am stuck within the Installation: I added the list of INSTALLED_APPS and provided my API credentials to the settings.py file. Then I thought I should run the command: python3 manage.py collectstatic && python3 manage.py compress I am receiving the Traceback Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.5/dist-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.5/dist-packages/django/core/management/__init__.py", line 341, in execute django.setup() File "/usr/local/lib/python3.5/dist-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python3.5/dist-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/usr/local/lib/python3.5/dist-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/usr/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 956, in _find_and_load_unlocked ImportError: No module named 'oauth_tokens' I tried to resolve the error with: sudo -H pip3 install oauth_tokens But I received the error message: Collecting oauth_tokens Could not find a version that satisfies the requirement oauth_tokens (from … -
retrieve data from serializer and render it in template
I have a REST api containing mutliple entries like this : [ { "title": "test3dxblock.0", "html": "<div><iframe src=/scenario/test3dxblock.0/ width=\"400\" height=\"500\"></iframe></div>", "description": "desc", "status": "417" }, { "title": "test3dxblock.0", "html": "<div><iframe src=/scenario/test3dxblock.0/ width=\"400\" height=\"500\"></iframe></div>", "description": "error", "status": "417" }, { "title": "allscopes_demo.0", "html": "<div><iframe src=/scenario/allscopes_demo.0/ width=\"400\" height=\"500\"></iframe></div>", "description": "desc", "status": "417", "error": "Requested page error: Error: Invalid URI \"http:///scenario/allscopes_demo.0/\"", "url": "/scenario/allscopes_demo.0/" }, { "title": "thumbs.0", "html": "<div><iframe src=/scenario/thumbs.0/ width=\"400\" height=\"500\"></iframe></div>", "description": "thumbs.0", "status": "417", "error": "Requested page error: Error: Invalid URI \"http:///scenario/thumbs.0/\"", "url": "/scenario/thumbs.0/" } ] I'm looking to extract one of those items and render its values in my template, I've created a function to get one item @api_view(['GET']) def get_sc(request, scname): try: scenario = SavedEmbeds.objects.filter(title=scname) except SavedEmbeds.DoesNotExist: raise HttpResponse(status=404) if request.method == 'GET': serializer = EmbedSerializer(scenario, many=True) return Response(serializer.data) However in my view i'm strugguling in retrieving the item in the proper format, so far i've made this scenario = SavedEmbeds.objects.filter(title=scname) serializer = EmbedSerializer(scenario, many=True) serializer_json = JSONRenderer().render(serializer.data) embedserializer = EmbedSerializer(data=serializer_json) if embedserializer.is_valid(raise_exception=True): embed = embedserializer.save() return render(request, 'workbench/dir/xblock.html', {'embed': embed}) else: return render(request, 'workbench/dir/xblock.html', {'status':embedserializer}) each time i try to get the items i get an error instead {u'non_field_errors': [u'Invalid data. Expected a dictionary, but got str.']} -
DisallowedHost error not going away when adding IP address to ALLOWED_HOSTS
If I set ALLOWED_HOSTS = ['*'] I am able to make a succesfull call, however this seems dangerous and counterintuitive. When I set ALLOWED_HOSTS to the recommended string, it fails. How to fix this? -
how do I create and link to a category section in my templates?
I am new to django and I have tried a few suggestions but can't seem to get it to work. I am trying to create a blog post model with a category section and link to the categories in my template. My codes are as follows. from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.core.urlresolvers import reverse from taggit.managers import TaggableManager # Create your models here. class PublishedManager(models.Manager): def get_queryset(self): return super(PublishedManager, self).get_queryset().filter(status='published') class MoneyManager(models.Manager): def get_queryset(self): return super(MoneyManager, self).get_queryset().filter(category='money') class LoveManager(models.Manager): def get_queryset(self): return super(LoveManager, self).get_queryset().filter(category='love') class WeightlossManager(models.Manager): def get_queryset(self): return super(WeightlossManager, self).get_queryset().filter(category='weightloss') def get_image_filename(instance, filename): title = instance.post.title slug = slugify(title) return "post_images/%s-%s" % (slug, filename) class Post(models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) CATEGORY_CHOICES = ( ('money', 'Money'), ('love', 'Love'), ('weightloss', 'Weightloss') ) title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique_for_date='publish') author = models.ForeignKey(User, related_name='blog_posts') image = models.ImageField(upload_to='get_image_filename', verbose_name='Image', blank=True) body = models.TextField() image2 = models.ImageField(upload_to='get_image_filename', verbose_name='Image', blank=True) body2 = models.TextField(blank=True) image3 = models.ImageField(upload_to='get_image_filename', verbose_name='Image', blank=True) body3 = models.TextField(blank=True) publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft') objects = models.Manager() published = PublishedManager() category = models.CharField(max_length=10, choices=CATEGORY_CHOICES) money = MoneyManager() love = LoveManager() weightloss = … -
Django - display form errors as message
I don't have idea how to display error messages in proper way. This is my clean method in my forms.py: def clean(self): cleaned_data = super().clean() subcategory = cleaned_data['subcategory'] subcategory1 = cleaned_data['subcategory1'] keywords = cleaned_data['keywords'] if subcategory1 and (subcategory == subcategory1): raise forms.ValidationError("Subkategorie nie mogą być takie same.") if len(keywords) < 20: raise forms.ValidationError("Za mało") This is a part of my views.py: if form_extended.is_valid(): group = request.POST["group"] if group == '2': sprawdzenie_kodu = CodeCheck(form_extended.cleaned_data['kod']) if sprawdzenie_kodu.check_code_validation(): new_form = form_extended.save(commit=False) new_form.date_end = datetime.now() + timedelta(days=config.PREMIUM_TIME) new_form.save() SendEmail(form_extended).send_confirmation_email() messages.add_message(request, messages.SUCCESS, 'Dodano!!') else: messages.add_message(request, messages.ERROR, 'Podany kod jest nieprawidłowy') return render(request, 'mainapp/add_site.html', context) else: form_extended.save() SendEmail(form_extended).send_confirmation_email() messages.add_message(request, messages.SUCCESS, 'Dodano!!') return render(request, 'mainapp/add_site.html', context) else: messages.add_message(request, messages.ERROR, form_extended.errors) print(form_extended.errors) I validate "keywords" field: keywords = MyTextField(max_length=config.KEYWORDS_LENGTH_MAX, validators=[MinLengthValidator(20)], verbose_name="Słowa kluczowe") This is my error message (it is doubled - I don't now why): How can I display correct error message? -
how to i can change wagtail cms page tag before save
sorry for my bad English how to i can change wagtail page tag before save ? I can change a title with overrides save() like this def save(self, *args, **kwargs): self.title = "my title" super(ProductPage, self).save() but i dont know how to change tag list Again, sorry for my bad English tnx -
Django render not working when redirected from another view
I have two views as follows def home(request): levels = levelData.objects.all() context ={ "levels" : levels } print "abcde" return render(request, 'home.html', context) and the other one def create(request): if request.method == "POST": # doing something with data with saveData as variable of model type saveData.save() return redirect('home') return render(request, 'create.html') Now, inside the create view, I wish to redirect to home view after saving data. Redirect is working fine and it's being redirected to home as the print statement in home view is executed and "abcde" is printed in terminal. But, home.html does not get rendered and it remains on create.html. Also, the url doesn't change. This is home view in my urls.py url(r'^$', home, name='home'), What am I doing wrong? -
Using TimeZones in Django Rest Framework
I know in a Postgres database, all date/times are stored in GMT timezone. I know that if I want to use date/time in a filter for django rest framework, that the formula is YYYY-MM-DDTHH:MM:SSZ. I also know if I want to enter a datetime other than Z-time, then I use the +/- as such for PST: YYYY-MM-DDTHH:MM:ZZ-07:00. My problem is that all of my responses return in Z-time. How do I make the DRF API call return in the same timezone that I asked for it in? Here's my serializer and api view. Thanks: SERIALIZER.PY class LatestSerializer(serializers.ModelSerializer): class Meta: model = Currency_Latest fields = '__all__' API.PY class CurrencyLatestViewSet(viewsets.ReadOnlyModelViewSet): queryset = Currency_Latest.objects.all() serializer_class = LatestSerializer MODELS.PY class Currency_Latest(models.Model): skey = models.CharField(max_length=100, blank=True, unique=True) name = models.CharField(max_length=100, blank=True, null=True) symbol = models.CharField(max_length=100, blank=True, null=True) rank = models.IntegerField(blank=True, null=True) price_usd = models.FloatField(blank=True, null=True) price_btc = models.FloatField(blank=True, null=True) volume_24h_usd = models.FloatField(blank=True, null=True) market_cap_usd = models.FloatField(blank=True, null=True) available_supply = models.FloatField(blank=True, null=True) total_supply = models.FloatField(blank=True, null=True) percent_change_1h = models.FloatField(blank=True, null=True) percent_change_24h = models.FloatField(blank=True, null=True) percent_change_7d = models.FloatField(blank=True, null=True) last_updated = models.DateTimeField(blank=True) def __str__(self): return self.skey The field in question is the last_updated field. of note, in settings.py I have the field set: USE_TZ = True Thanks. -
django-import-export not showing in admin
I have a problem with django import-export tool. Simmilat to the one described in This topic. Problem is there is no solution for the problem posted there and I need it badly. Buttons for import/export in my admin panel do not show up. Did change the order of declaration, run collectstatic, restarted server ... I could use your help django masters. from django.contrib import admin #from actions import export_to_csv from import_export import resources from import_export.admin import ImportExportModelAdmin, ImportExportMixin, ImportMixin, ExportActionModelAdmin, ImportExportActionModelAdmin from .models import Library from datetime import datetime from django import forms from redactor.widgets import RedactorEditor # registered models class LibraryResource(resources.ModelResource): class Meta: model = Library class LibraryAdmin(ImportExportModelAdmin, admin.ModelAdmin): resource_class = LibraryResource list_display = ... list_display_links = ... search_fields =... list_filter = ... def name(self, obj): return obj.library.name name.admin_order_field = 'name' #Allows column order sorting name.short_description = 'Biblioteka' -
Django smth_set functionality
I created basic application following guildlines from official django documentation and after i modified it with some functionality of Django Rest Framework I see in my error log this statement AttributeError: 'Question' object has no attribute 'choice_set' question.choice_set.get(pk=request.POST['choice']) I can't find any solution to this problem. it used to work but it is strange that native function of model stopped to work. -
Celery beat sometimes stops working
I'm using latest stable Celery (4) with RabbitMQ within my Django project. RabbitMQ is running on separate server within local network. And beat periodically just stops to send tasks to worker without any errors, and only restarting it resolves the issue. There are no exceptions in worker (checked in logs & also I'm using Sentry to catch exceptions). It just stops sending tasks. Service config: [Unit] Description=*** Celery Beat After=network.target [Service] User=*** Group=*** WorkingDirectory=/opt/***/web/ Environment="PATH=/opt/***/bin" ExecStart=/opt/***/bin/celery -A *** beat --max-interval 30 [Install] WantedBy=multi-user.target Is it possible to fix this? Or are there any good alternatives? (Cron seems to be not a best solution). -
Django ModelMultipleChoiceField Widget not Rendering
I'm trying to use the built-in django admin widget ModelMultipleChoiceField to render something like this in a form: I have followed others' recommendations here, and have reviewed the documentation. but I am getting a half-complete widget; only one box is showing, and all of the associated buttons don't appear: In addition, when the page loads, the following error is given: Uncaught ReferenceError: addEvent is not defined at (index):1665 Here is the line within index that is causing the error: <script type="text/javascript"> addEvent(window, "load", function(e) {SelectFilter.init("id_employee_selection", "__unicode__", 0, "/static/admin/"); }); </script> I cannot find addEvent.js anywhere within the django library, even though it is referenced on some django tickets. For reference, below are my form and HTML FORM: from django import forms class EventAttendeesForm(forms.Form): from employees.models import Employee from django.contrib.admin.widgets import FilteredSelectMultiple employee_selection = forms.ModelMultipleChoiceField( queryset=Employee.objects.all(), widget=FilteredSelectMultiple("__unicode__", is_stacked=False, attrs={'rows':20}) ) def __init__(self, *args, **kwargs): super(EventAttendeesForm, self).__init__(*args, **kwargs) self.fields['employee_selection'].label = "Employees" HTML SNIPPET: <link href="/static/admin/css/widgets.css" type="text/css" media="all" rel="stylesheet" /> <script type="text/javascript" src="/jsi18n/"></script> <script type="text/javascript" src="/static/admin/js/jquery.init.js"></script> <form method='POST' action='' enctype='multipart/form-data'>{% csrf_token %} {{ form }} <input type='submit' value='Add Item(s)' /> </form> {{ media }} How can I correctly render the ModelMultipleChoiceField widget? I have tried this hack but it doesn't work. Many thanks …