Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Difference between @cached_property and @lru_cache decorator
I am new to Django. Would be really helpful if someone can tell the difference between @cached_property and @lru_cache decorator in Django. Also when should I use which decorator in Django. Use cases would be really helpful. Thanks. -
Django best practice for a site that submit jobs and polls results to the cloud
I'm trying to figure out an optimal way to do this for a site that acts as a frontend to Azure. Let's say user wants to create a VM: 1) User submits job 2) Job gets submitted to Azure immediately but takes about 3 minutes to get results back. 3) I want user to submit and go on on with their business (i.e. no waiting) and the DOM to update automatically with the result when it's received. Things I've tried: 1) Celery to schedule the task -> saves result to DB -> JavaScript polls DB every so often and update DOM 2) JavaScript runs an AJAX that talks to a view that talks to Azure via API to see if job is done. If done, save result to DB and update DOM Issues with 1) I really don't like this method of relying on another service and adding more complexity. Main problem is that Celery is not reliable, it may run or it may queue. I also have to worry about Celery getting an up to date db data when it finally gets to the task 2) Works but the DB doesn't get updated til user actually queries the data. … -
Can't run dynos
After deploying my django-site to heroku(finally!) i've got "error code H14". Then i tried to scaling dynos but the following error occurred: heroku ps:scale web=1 Scaling dynos... ! ▸ Couldn't find that process type. Procfile: web: gunicorn Django_work.wsgi -
django recaptcha not working on staging (works on production)
For some reasons recaptcha is working local, working on production but on staging pops up alert with text Cannot contact reCAPTCHA. Check your connection and try again Its my translate, because text is in russian. And I press ok and than on recaptcha there are text Invalid domain for site key That just blows my mind, so I thought that this error can cause http on staging and https on prod. But I disabled ssl via RECAPTCHA_USE_SSL = False I use django-recaptcha library, and there was no help. Domains in google captcha are correct: both are written - domain (prod) and subdomain (staging). Guys any help will be super appreciated! -
TypeError: 'class Meta' got invalid attribute(s): fields,model
I am trying to show LDAP-attributes of a user by using the django-ldapdb library. First of all I made a new model: models.py class LdapUser(ldapdb.models.Model): base_dn = u"CN=XXX,CN=Users,DC=domain,DC=com" object_classes = ['posixAccount', 'shadowAccount', 'inetOrgPerson'] # inetOrgPerson phone = CharField(db_column='telephoneNumber', blank=True) mobile_phone = CharField(db_column='mobile', blank=True) I want to display these in my webapp with forms. class LdapUserForm(ldapdb.models.Model): class Meta: model = LdapUser fields = ( 'phone', 'mobile_phone' ) I did all my migrations and but when I run my code it gives me the following error. raise TypeError("'class Meta' got invalid attribute(s): %s" % ','.join(meta_attrs.keys())) TypeError: 'class Meta' got invalid attribute(s): fields,model I looked it up but could not find anything helpful. So I hope someone on stacko has a solution for me. Thanks in advance -
using imagefit in Django
I'm writing an application in Django 2.x I am trying to use django-imagefit plugin in my application to resize images on rendering as I have to generate different size of images in template. According to the instruction in the package documentation, I have added imagefit to INSTALLED_APPS INSTALLED_APPS = [ ... 'imagefit', .... ] and included url pattern in urls.py urlpatterns = [ ... url(r'^imagefit/', include('imagefit.urls')), path('admin/', admin.site.urls), ] now in the template when I try to use resize template tag {% load imagefit %} <img src='{{ course.banner.url|resize:"200x150" }}'> It renders image path as below which is not working /imagefit/resize/200x150//media/course/2018/03/18/image.png whereas without using package, it is rendering /media/course/2018/03/18/image.png which is working perfectly. I tried to setup IMAGEFIT_ROOT like STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static_my_project') ] STATIC_ROOT = os.path.join(BASE_DIR, 'static_cdn', 'static_root') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'static_cdn', 'media_root') IMAGEFIT_ROOT = '/media/' but still it renders same path and image is not working and gives error file not found I think the error could be in IMAGEFIT_ROOT, How to properly use IMAGEFIT_ROOT? -
How to count the number of many to many relationship and display in the Template in django?
I am creating a website where multiple users can UpVote/DownVote an Idea In the HomePage i am displaying the total upvote/downvote an idea has To keep track of upvotes/downvotes an idea received I have created my Idea model as follows: Title = models.CharField(null=False, max_length=20) category = models.CharField(max_length=50, null=True) UpVotes = models.IntegerField(default=0) DownVotes = models.IntegerField(default=0) Submitted_by = models.ForeignKey(Users, on_delete=models.CASCADE, related_name='by') UpVoted_By = models.ManyToManyField(Users, related_name='UpVoted', blank=True, null=True) DownVoted_By = models.ManyToManyField(Users, related_name='DownVoted', blank=True, null=True) Description = models.CharField(max_length=100000) So UpVoted_by and DownVoted_by are having many to many relationships with User Django Creates a separate table to keep track of the many to many fields. Coming to the question as I said to my homepage displays each idea in a card with the corresponding number of upvotes and downvotes, something like this: <div class="row"> {% for x in page_obj %} <div class="col-sm-4"> <div class="card" style="width: 20vw;margin-bottom:20px;"> <img class="card-img-top" src="https://preview.ibb.co/jc8BLH/4928661_borderlands_2_wallpaper.png" alt="Card image cap"> <div class="card-body"> <h5 class="card-title">{{ x.Title}}</h5> <div class="card-text div1"> <p>Submitted By: {{ x.Submitted_by }}</p> <p>UpVotes: {{ x.UpVotes }}</p> <p>DownVotes: {{ x.DownVotes }}</p> </div> <a href="view/{{ x.id }}" class="btn btn-primary">Go somewhere</a> </div> </div> </div> {% endfor %} I am sending all the objects of Ideas as page_obj and displaying them Now, my problem is I … -
Listing celery tasks as foreignkeys
Is it possible to let the user select a task from the available shared tasks in a django model? So each app might have tasks.py in it, but they are all @shared_tasks and I would like the user to be able to select a task from a list. For example: @shared_task def create_event(incoming): print "create an event" class Module(models.Model): name = models.CharField(max_length=256) task = models.ForeignKey(ShareTasks) -
REST API deployment error on heroku - "this field is required"
I'm working on a project using DRF to create a REST API, deploying it on heroku. The rest api works properly on localhost but when I try it on heroku, it always return "this field is required" though I've inserted the value for username and password Send post on heroku -
Deleting image and removing its value from JSON dynamically
I am using Gridster widget for webpage.I have widgets which have images on them.There is a JSON which gives data about what image should be there on each grid(I get text from JSON and then get corresponding image from database).I want a button on each image which will delete the image from the widget and also remove the corresponding value from JSON. My JS loop which generates widgets: for(var index=0;index<json.length;index++) { {% load static %} gridster.add_widget('<li class="new" ><button class="delete-widget-button" style="float: right;">-</button><img src="{% get_static_prefix %}images/'+json[index].html+'"></li>',json[index].size_x,json[index].size_y,json[index].col,json[index].row); }; My JSON var json = [{ "html": 'abc.png', "col": 1, "row": 1, "size_y": 2, "size_x": 2 }, { "html": "xyz.png", "col": 4, "row": 1, "size_y": 2, "size_x": 2 }, { "html": "def.png", "col": 6, "row": 1, "size_y": 2, "size_x": 2 }, { "html": "abc.png", "col": 1, "row": 3, "size_y": 1, "size_x": 1 }, { "html": "def.png", "col": 4, "row": 3, "size_y": 1, "size_x": 1 }, { "html": "abc.png ", "col": 6, "row": 3, "size_y": 1, "size_x": 1 } ]; My HTML: <div class="gridster"> <ul> </ul> </div> The Fiddle is what I am trying to do Any help will be really appreciated because this seems to be an advanced level topic of JS/Jquery -
Dialog system which will allow to upload all types of files and which will have online chat with server
I am going to create dialog system which will allow to upload all types of files and which will have online chat with server. It seems to me that the most optimal solution would be to use Django Channels and Websockets for chat and for all other things Django Rest Framework (registration, sending files etc.). I wonder what do you think about it? In addition, I am looking for an example project that could serve as a basis for me. For example, I do not know how to reconcile authorization using DRF and Django Channels. Can you recommend something? -
Trying to customize the Django SetPasswordForm
I was trying to overwrite SetPasswordForm to add a placeholder and a class but it seems that it is not working. I managed to do it for login page and password reset page but here I got stuck. class MySetPasswordForm(SetPasswordForm): new_password1 = forms.CharField( label=_("New password"), widget=forms.PasswordInput(attrs={'placeholder': 'New Password', 'class': 'password1'}), strip=False, help_text=password_validation.password_validators_help_text_html(), ) new_password2 = forms.CharField( label=_("New password confirmation"), strip=False, widget=forms.PasswordInput(attrs={'placeholder': 'Repeat Password', 'class': 'password2'}), ) urlpatterns = [ path('accounts/password_reset/', auth_views.PasswordResetView.as_view( form_class=MyPasswordResetForm)), path('accounts/password_reset_confirm/', auth_views.PasswordResetConfirmView.as_view( form_class=MySetPasswordForm)), path('accounts/', include('django.contrib.auth.urls')),] Is this accurate ? -
Django form has no errors, but is not valid?
In the following unit test (which uses factory_boy test fixtures), class PackageDefaultTest(TestCase): def test_1(self): company = CompanyFactory() package = PackageFactory(company=company) form = PackageForm(instance=package) import ipdb; ipdb.set_trace() after dropping into the debugger, I encounter the following strange situation: > /Users/kurtpeek/Documents/Dev/lucy/lucy-web/dashboard/tests/test_packages.py(601)test_1() 599 package = PackageFactory(company=company) 600 form = PackageForm(instance=package) --> 601 import ipdb; ipdb.set_trace() ipdb> form.is_valid() False ipdb> form.errors {} That is, form.is_valid() is False, but form.errors is an empty dictionary. Can someone explain how this is possible? From what I understand from https://docs.djangoproject.com/en/2.0/ref/forms/api/#using-forms-to-validate-data, no errors implies a valid form. -
How do I upload a file from Axios to Django?
I'm switching from Jquery AJAX to react-dropzone & Axios, I'd like to upload a file to my Django server, I have no issue posting a blob url of the image on the server but I want to get it under request.FILES but I am getting an empty queryset. request.FILES : <MultiValueDict: {}> <!--- empty request.POST : <QueryDict: {}> <!--- able to get a blob url Here's what my axios configuration looks like : const temporaryURL = URL.createObjectURL(step3.drop[0]); var fd = new FormData(); fd.append('image', temporaryURL); axios({ method: 'post', url: SITE_DOMAIN_NAME + '/business-card/collect/', data: fd, headers: { "X-CSRFToken": CSRF_TOKEN, "content-type": "application/x-www-form-urlencoded" } }).then(function (response) { console.log(response) URL.revokeObjectURL(temporaryURL); }).catch(function (error) { console.log(error) }); I am receiving the file on a classBasedView on POST request. How can I upload the file? Where am I wrong? -
It's possible to call the LogEntry from a list of objects?
i'm trying with this queryset, where all_regimes is a list of pk logs = LogEntry.objects.filter(content_type_id= ContentType.objects.get_for_model(regime).pk ,object_id__in = all_regimes) but thorws this exception No operator matches the given name and argument type(s). You might need to add explicit type cast -
Django Query Foreign Key
I have a tag model which have a category for each tag: class Tag(models.Model): name = models.CharField('Name', max_length=35) description = models.CharField('Description', max_length=255) category = models.ForeignKey(Category, on_delete=models.CASCADE) And I also have a user & tag relation model: class UserTag(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name='User', related_name='user_tag') tag = models.ForeignKey(Tag, verbose_name='Tag', related_name='user_tag') preferred = models.BooleanField(verbose_name='Preferred', default=False) created_at = models.DateTimeField('Created at', auto_now_add=True) updated_at = models.DateTimeField('Updated at', auto_now=True) How can I query all distinct categories names for a specific user? -
Can I encapsulate other classes within a Django model for more readable code?
I have a Django model which has a lot of fields to the point where simply listing them all looks pretty ugly. Some of these fields can be grouped together as they have properties in common, and I'd like to put them in a separate class or model and encapsulate that within the bigger model. As an example, is it possible to do something like this: class BigModel(models.Model): field1 = models.IntegerField() field2 = models.BooleanField() ... grouped_data = SmallClass() class SmallClass(): field1 = models.CharField(max_length=10) field2 = models.IntegerField() What I hope to accomplish with this is to achieve essentially the same thing as if I had simply listed all of the fields within BigModel, but with more readable code. Another possible way I thought of accomplishing this was making SmallClass into a SmallModel and having it contain a OneToOneField referencing the BigModel. For example: class BigModel(models.Model): field1 = models.IntegerField() field2 = models.BooleanField() ... grouped_data = SmallClass() class SmallModel(models.Model): big_model = models.OneToOneField(BigModel) field1 = models.CharField(max_length=10) field2 = models.IntegerField() Any help would be greatly appreciated. -
why does django-admin default to creating outer container directory?
following along to official Django tutorial, their instruction for bootstrapping a Django project is: $ django-admin startproject mysite which creates this directory structure: mysite/ manage.py mysite/ __init__.py settings.py urls.py wsgi.py in 'Hello Web App' book, . is added to end: $ django-admin startproject hellowebapp . the resulting directory structure avoids the matching outer and inner directories: manage.py mysite/ __init__.py settings.py urls.py wsgi.py Is there a best practice in the Django community for directory structure re: startproject? The official tutorial is, well, official; whereas 'Hello Web App' seems to offer a cleaner approach. -
Dropdown/Radio Inputs for Django
I currently have an Input model which contains two attributes. Path - of type CharField File - of type FileField When creating an Input object via CreateView, the user may only choose one or the other. How will I write my code to allow them to choose either and show the input form for either attribute. e.g choosing File will show a FileFile input and vice versa. I was thinking of using either a dropdown or a radio button. -
Minimizing DB queries in cases where the resource is browser cached (Django project)
In a Django web application I'm developing, there's a page where I need to display multiple user avatars in a list. In the relevant view, I employ the Django ORM to fetch these urls like so: Avatar.objects.filter(id__in=user_list).values('id','url) Next, I've set up my nginx webserver to cache static resources, simply via: map $sent_http_content_type $expires { default off; text/html epoch; text/css max; application/javascript max; ~image/ max; } My understanding is, whenever the view servicing the avatars list page is processed, the earlier Django ORM query would always be run. Thus, the webserver caching allows me to save GET requests, but not the actual database look up. Is this understanding correct? If so, what's the pattern for calling ORM queries only if the images are not cached in the browser? Is that possible (or advisable) at all? And if not, why not? I'm interested in understanding the best practices of web development in cases such as these. Illustrative examples would be great! -
Django 1.11 use storage backend or API depending on setting
tl;dr What is the proper way to implement a flag-dependent API and regular file-system storage side by side? I have a Django 1.11 project, and the project will have two modes - an API-dependent mode, and an "independent" mode, depending on a setting settings.py I've been successful in building a single app that supports both versions, and I'd prefer to keep it that way so I don't have to maintain two separate projects (95% of the code is identical, only a small part of it is API dependent). I got stuck on the files however. Effectively, if the setting is X, I want to use the normal Django file storage system, with nothing changed. If setting is Y, I want to instead use an API for the file storage - this is a custom API that we wrote to interact with a legacy system. I have methods for things like saving, loading, getting a link, etc in the API, and it just needs to reference an ID that is returned on saving (I could store the ID in an integer field.) I have code all over my site that currently works with the regular file system, and if possible, I'd … -
Timezone in django request.META
I'm trying to get the users timezone in a django app. I notice that a timezone appears in request.META, is that the user's one? -
django proxy user model access username
I am writing a self Service Application for our Employees based on django 2.0 . Now I want to extend the django user model with an proxy model. But how can i access the username of the user object from the proxy model? -
Django: Accessing kwargs using HttpResponseRedirect(reverse()) in passed view
I am trying to access the kwargs passed through HttpResponseRedirect() in a success view. The key is present in the kwarg dict, but the value is not. Why is this? Views: class UploadView(View): paneluploadform = PanelUploadForm def get(self, request, *args, **kwargs): paneluploadform = self.paneluploadform() context = {'paneluploadform': paneluploadform} return render(request, 'results/upload.html', context) def post(self, request, *args, **kwargs): paneluploadform = self.paneluploadform(request.POST, request.FILES) if paneluploadform.is_valid(): panel_name = paneluploadform.upload() return HttpResponseRedirect( reverse('results:success', kwargs={'panel_name': panel_name}) ) context = {'paneluploadform': paneluploadform} return render(request, 'results/upload.html', context) def success(request, *args, **kwargs): return render(request, 'results/success.html') urls.py: urlpatterns = [ url(r'^upload/$', UploadView.as_view(), name='upload'), url(r'^upload/successful-(?P<panel_name>)', success, name='success') ] In my success.py view when i print(kwargs) the output is {'panel_name': ''} But my url is /localhost/upload/successful-panelnameientered Why doesn't kwargs ={'panel_name': 'panelnameientered'} ? -
Django model filtering(query)
I'm struggling with a model filtering, what I doing wrong? Here is my code: models.py class Images(models.Model): TAK_NIE = ( ('y', 'Tak'), ('n', 'Nie') ) nazwa_polska = models.ForeignKey(Roslina, related_name='images', on_delete=models.CASCADE) image = models.ImageField(max_length=255, upload_to=generate_filename) zdjecie_glowne = models.CharField(max_length=1,choices=TAK_NIE,default='n') def czyGlowne(self): return self.filter(zdjecie_glowne='y') def __str__(self): return self.nazwa_polska.nazwa_polska html not working: {% for zdjecie in ros.images.czyGlowne %} {{ zdjecie.image }} <img src="{% static '' %}{{ zdjecie.image|cut:"static/"}}" alt="brak zdjecia" class="img-thumbnail zdjecia"> {% endfor %} on the same page working html code: {% for zdjecie in ros.images.all %} <div class="col-lg-4"> <img src="{% static '' %}{{ zdjecie.image|cut:"static/"}}" alt="brak zdjecia" class="img-thumbnail zdjecia"> </div> {% endfor %}