Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Add a field value outside form in Django
Whenever I have to add a value to the instance of a form obtained from the context or from the URL I do it in the following way, using form.instance. class PreguntaForm(forms.ModelForm): class Meta: model = Pregunta fields = ('etiqueta', 'grupo', 'tipo_pregunta', 'opciones', 'mostrar_tabla', 'activo') def __init__(self, *args, **kwargs): cuestionario = kwargs.pop('cuestionario', False) super(PreguntaForm, self).__init__(*args, **kwargs) self.fields['grupo'].queryset = Grupo.objects.filter(cuestionario=cuestionario) class PreguntaNueva(InfoPregunta, CreateView): form_class = PreguntaForm encabezado = 'Nueva Pregunta' model = Pregunta def get_form_kwargs(self): kwargs = super(PreguntaNueva, self).get_form_kwargs() kwargs['cuestionario'] = self.dame_cuestionario() return kwargs def form_valid(self, form): form.instance.cuestionario = self.dame_cuestionario() return super(PreguntaNueva, self).form_valid(form) The problem that arises now is that I want to perform a check CreateView and EditView. To DRY, I want to do it in the clean method of the model, but the value that I assign to form.instance.cuestionario, is not available within the clean method. How could I do it? This value must not be edited by the user in any case. -
Django queryset: check for foreignkey values and substract them from queryset
Let's imagine we have 2 models: class Blog(models.Model): title = models.CharField(...) status = models.Charfield(choices=choices.STATUS, default='pending') class Entry(models.Model): blog = models.ForeignKey(Blog, on_delete=models.CASCADE, related_name="entries") text = models.TextField() ready = models.BooleanField(default=False) Every entry can be added in many blogs. I want to filter all entries with ready = True whose blog has the status = published. -
get request on empty lists return 200 status code
I have this view: def get(self,request): cities = City.objects.filter(State__in=request.GET.getlist('state_id')) serializer = citySerializers(cities,many=True) return Response({"message": "data loaded!", "data": serializer.data}) If I enter a state_id that does not exist on the database it returns me status code 200,I expect it returns 404 for an empty list. What I did wrong? -
View function is not being called after submitting form in django
I have made a simple form inside a html file whose path is www.site.com/posts/5. Whenever the form is submitted, it redirects back to the same page i.e www.site.com/posts/5 displaying a message given by user in the form. However, whenever the form is submitted it doesn't call the foobar view. The urls.py, views.py and html files are as follows:- urls.py urlpatterns = [ path('posts/<int:foo>',user_views.display, name="display", path('posts/<int:foo>',user_views.foobar, name="makefoo"), ] views.py def foobar(request, foo): #do something html file <form name="fooform" action= "{% url 'makefoo' 5 %}" method = "post"> {% csrf_token %} <input type="text" name="FOO_BODY" maxlength="300" required> <input type="submit" value="comment"> <input type="reset" value="clear"> </form> -
Is it bad practice to store a Pandas DataFrame as a PickledObjectField in a Django Model?
I am storing a Pandas DataFrame in a Django model as a PickledObjectField. I need to access and modify this DataFrame based on certain logic. Pandas makes this job a lot easier, where I have an engine class that uses Pandas selects and filters. Should I have a separate model where I store each row in the DataFrame, then read this using django-pandas, perform the manipulation and update the model? The key here is that the DataFrame will be modified by adding/removing some rows, so if it is to be stored in a model, it would be easier to drop all records and re-populate the model. The DataFrame is less than 100 rows, so I'm not worried about scalability. -
How to access my ChoiceField in views.py?
How do I access the ChoiceField options in views.py so I can print different outputs based on it? (I tried the code below but it doesn't seem to work, I don't know where went wrong) forms.py class BeamForm(forms.Form): CHOICES = (('Add on', 'Add on'),('Reset', 'Reset'),) field = forms.ChoiceField(choices=CHOICES) views.py from . import forms if forms.BeamForm.field == 'Add on': print("Option is add on") elif forms.BeamForm.field == 'Reset' print("Option is Reset") else: print("nothing") -
Using session.set_expiry() in custom AuthenticationForm in Django.
I am trying to set remember me in login and use LoginView as view. Is it possible to set session.set_expiry(0) in the custom AuthenticationForm? class CustomAuthenticationForm(AuthenticationForm): username = forms.CharField(); password = forms.CharField(), remember_me = forms.BooleanField(widget=forms.CheckboxInput(), label='Remember me') def clean_remember_me(self): if not self.cleaned_data['remember_me']: set expiry immediately <-- here SESSION_EXPIRE_AT_BROWSER_CLOSE might be usable but can I use session.get_expiry(0) in this case? How can I do without writing a custom view? -
Django converting tiff to jpeg with pillow
I'm working with Django in Python 3, and I have a model with an ImageField and I'm trying to override the .save() to do tiff to jpeg conversion: from PIL import Image from io import BytesIO from django.core.files.base import ContentFile class MyModel(models.Model): image = models.ImageField(upload_to=upload_image_to, editable=True, null=True, blank=True) def save(self, *args, **kwargs): pil_image_obj = Image.open(self.image) new_image_io = BytesIO() rgb_pil_image_obj = pil_image_obj.convert("RGB") rgb_pil_image_obj.save(new_image_io, quality=90, format='JPEG') # temp_name = self.image.name # self.image.delete(save=False) # self.image.save( # temp_name, # content=ContentFile(new_image_io.getvalue()), # save=False # ) super().save(*args, **kwargs) However, this leads to: tempfile.tif: Cannot read TIFF header. *** OSError: -2 If I try the save experiment but only opening the TIFF file from disk instead of feeding PIL.Image with the Django InMemoryUploadedFile, then everything works absolutely fine and the tiff is converted to a jpeg. Also pil_image_obj.verify() doesn't throw any exceptions. I'm using Pillow==5.3.0 -
Django Wagtail 'expected string or bytes-like object' error
I've been having some trouble figuring out what exactly is causing this error in my code. My main pages render but when I try to open a child page I get the expected string error. Any help debugging this greatly appreciated. Traceback Below: Internal Server Error: /resonate/page-2/ Traceback (most recent call last): File "/Users/saeahmad/.pyenv/versions/auxe_cms/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/Users/saeahmad/.pyenv/versions/auxe_cms/lib/python3.6/site-packages/django/core/handlers/base.py", line 156, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/saeahmad/.pyenv/versions/auxe_cms/lib/python3.6/site-packages/django/core/handlers/base.py", line 154, in _get_response response = response.render() File "/Users/saeahmad/.pyenv/versions/auxe_cms/lib/python3.6/site-packages/django/template/response.py", line 106, in render self.content = self.rendered_content File "/Users/saeahmad/.pyenv/versions/auxe_cms/lib/python3.6/site-packages/django/template/response.py", line 83, in rendered_content content = template.render(context, self._request) File "/Users/saeahmad/.pyenv/versions/auxe_cms/lib/python3.6/site-packages/django/template/backends/django.py", line 61, in render return self.template.render(context) File "/Users/saeahmad/.pyenv/versions/auxe_cms/lib/python3.6/site-packages/django/template/base.py", line 171, in render return self._render(context) File "/Users/saeahmad/.pyenv/versions/auxe_cms/lib/python3.6/site-packages/django/template/base.py", line 163, in _render return self.nodelist.render(context) File "/Users/saeahmad/.pyenv/versions/auxe_cms/lib/python3.6/site-packages/django/template/base.py", line 937, in render bit = node.render_annotated(context) File "/Users/saeahmad/.pyenv/versions/auxe_cms/lib/python3.6/site-packages/django/template/base.py", line 904, in render_annotated return self.render(context) File "/Users/saeahmad/.pyenv/versions/auxe_cms/lib/python3.6/site-packages/django/template/loader_tags.py", line 150, in render return compiled_parent._render(context) File "/Users/saeahmad/.pyenv/versions/auxe_cms/lib/python3.6/site-packages/django/template/base.py", line 163, in _render return self.nodelist.render(context) File "/Users/saeahmad/.pyenv/versions/auxe_cms/lib/python3.6/site-packages/django/template/base.py", line 937, in render bit = node.render_annotated(context) File "/Users/saeahmad/.pyenv/versions/auxe_cms/lib/python3.6/site-packages/django/template/base.py", line 904, in render_annotated return self.render(context) File "/Users/saeahmad/.pyenv/versions/auxe_cms/lib/python3.6/site-packages/django/template/loader_tags.py", line 62, in render result = block.nodelist.render(context) File "/Users/saeahmad/.pyenv/versions/auxe_cms/lib/python3.6/site-packages/django/template/base.py", line 937, in render bit = node.render_annotated(context) File "/Users/saeahmad/.pyenv/versions/auxe_cms/lib/python3.6/site-packages/django/template/base.py", line 904, in render_annotated return self.render(context) File … -
Why language is not changing with set_language url in Django?
I added django-user-language-middleware package but it only change language when I manually change it at admin or DB. When I use set_language link, it doesn't update language. Before adding that middleware, it was working without any problem but I need to save language for user. The middleware order: MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'user_language_middleware.UserLanguageMiddleware', ... } -
How do I save the video recorded on web browser to smartphone (Android) internal storage?
I managed to stream the video from camera in a smartphone to the web app in the code below. However, I do not know how to save the video to the internal storage of the smartphone from the web app. How can I achieve this? The following is my working code so far. Thank you for any kind assistance. base.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content="{% block metadescription %}{% endblock %}"> <link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet"> <title>{% block title %}{% endblock %}</title> </head> <body> <div class="container-fullwidth"> <div class="container-fluid bg-light navbar-fixed-top"> </div> {% block content %} {% endblock %} </div> <script async src="https://www.googletagmanager.com/gtag/js?id=UA-33848682-1"></script> <script> window.dataLayer = window.dataLayer || []; function gtag() { window.dataLayer.push(arguments); } gtag('js', new Date()); gtag('config', 'UA-33848682-1'); </script> <script> 'use strict'; var videoElement = document.querySelector('video'); var audioSelect = document.querySelector('select#audioSource'); var videoSelect = document.querySelector('select#videoSource'); navigator.mediaDevices.enumerateDevices() .then(gotDevices).then(getStream).catch(handleError); audioSelect.onchange = getStream; videoSelect.onchange = getStream; function gotDevices(deviceInfos) { for (var i = 0; i !== deviceInfos.length; ++i) { var deviceInfo = deviceInfos[i]; var option = document.createElement('option'); option.value = deviceInfo.deviceId; if (deviceInfo.kind === 'audioinput') { option.text = deviceInfo.label || 'microphone ' + (audioSelect.length + 1); audioSelect.appendChild(option); } else if (deviceInfo.kind === 'videoinput') { … -
not able to upload image in app static folder
i have a app named website and in this i have a static folder and inside it i have website folder and then i have uploaded_image folder and i want to upload my images in this folder through admin panel. this is my model class About(models.Model): displayname=models.CharField(max_length=50) email=models.EmailField(max_length=70) website=models.CharField(max_length=200) photo=models.FileField(upload_to='website/static/uploaded_image') des=models.TextField() def __str__(self): return self.displayname -
Html for loop add another condition
I want to fetch the data in html template by for loop. Here's what my code is. {% for entry in topic.entries.all %} <li> <a style="line-height:170%", href="{% url 'xx' entry.id %}">{{ entry.text }}</a> </li> {% endfor %} And I need to add one additional condition to identify if the Entry Model field 'delete' = '1'. I try {% for entry in topic.entries.all().value_list(delete = '1') %}, but id did not work. How could I achieve that? Here's the Model.py. class Topic(models.Model): text = models.CharField(max_length=200) date_added = models.DateTimeField(auto_now_add=True) owner = models.ForeignKey(User, on_delete=models.CASCADE) delete = models.IntegerField(default=1) def _str_(self): return self.text class Entry(models.Model): topic = models.ForeignKey(Topic, on_delete=models.CASCADE, related_name="entries") text = models.TextField() date_added = models.DateTimeField(auto_now_add=True) delete = models.IntegerField(default=1) class Meta: verbose_name_plural = 'entries' def _str_(self): return self.text[:50] + "..." #on_delete=models.CASCADE, -
Django Web/Dev On same Unix Server
I'm looking at a couple of MVC/MVT frameworks for a new server I'm getting at work (Unix, not sure of the flavor yet). I'm heavily leaning towards Django as well as Laravel. What I'm having trouble figuring out right now, is how Django would be setup, or would work, if I need a separation between web and dev environments. I'm only getting one server for this. The other problem I'm trying to figure out is the difficulty in only having 1 database (going with PostgreSQL). I mean when you're using migrations, how difficult is it to control the db names being different (db names like "test_prod_v1" and "test_dev_v1"). How to only have two sub-folders in the htdocs: web and dev, and how hard is it to deal with a setup like that? With migrations (etc) how to deal with needing a Web and Dev version of each database? I need to make a decision next week so I'm just looking for some advice or keyword/concepts to read up on over the weekend (weekend reading pointers). Thanks for any help or advice. In setting up a new web server, this is my biggest problem by far in making a framework decision. -
Need to quickly update Django model with difference between two other models
I'm populating my database from an API that provides year-to-date stats, and I'll be pulling from this API multiple times a day. Using the year-to-date stats, I need to generate monthly and weekly stats. I'm currently trying to do this by subtracting the stats at the start of the month from the stats at the end of the month and saving it in a separate model, but the process is taking far too long and I need it to go faster. My models look something like this : class Stats(models.Model): date = models.DateField(default=timezone.now) # Date pulled from API customer_id = models.IntegerField(default=0) # Simplified for this example a = models.IntegerField(default=0) b = models.IntegerField(default=0) c = models.IntegerField(default=0) d = models.IntegerField(default=0) class Leaderboard(models.Model): duration = models.CharField(max_length=7, default="YEARLY") # "MONTHLY", "WEEKLY" customer_id = models.IntegerField(default=0) start_stats = models.ForeignKey(Stats, related_name="start_stats") # Stats from the start of the Year/Month/Week end_stats = models.ForeignKey(Stats, related_name="end_stats") # Stats from the end of the Year/Month/Week needs_update = models.BooleanField(default=False) # set to True only if the end_stats changed (likely when a new pull happened) a = models.IntegerField(default=0) b = models.IntegerField(default=0) c = models.IntegerField(default=0) d = models.IntegerField(default=0) e = models.IntegerField(default=0) # A value computed based on a-d, used to sort Leaderboards I thought … -
Error: Django-Social-Auth LinkedIn Client Error
After authentication I got this error message HTTPError at /oauth/complete/linkedin-oauth2/ 410 Client Error: Gone for url: https://api.linkedin.com/v1/people/~:(email-address,first-name,headline,id,industry,last-name)?format=json Django settings conf SOCIAL_AUTH_LINKEDIN_OAUTH2_SCOPE = [ 'r_emailaddress', 'r_liteprofile' ] SOCIAL_AUTH_LINKEDIN_OAUTH2_FIELD_SELECTORS = [ 'email-address', 'headline', 'industry',] ====================================== Django package versions: social-auth-app-django==3.1.0 social-auth-core==2.0.0 Django==2.1 -
Django - adding contact form to footer
I am trying to create a contact form that can be used on all pages of my app. My function contact_form(request) in context_processors.py successfully shows the contact form in all templates that my base template extends to, but the problem is that I can't submit the information and run POST requests with it. After extensive research, it seems like the only clean way to do this would be to have context_processors.py perform the GET request and have a custom template tag handle the POST request. Taking this approach, I can't find a way to process this in the template tag. I have tried several different ways and have gotten several different errors. I have also looked at many of the posts out there to get to this point, including Contactform in footer of page, and there doesn't seem to be any answers that show how this is formatted in the template. settings.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ ... 'services.context_processors.contact_form', ], }, }, ] context_processors.py from .forms import ContactForm def contact_form(request): if request.method == 'GET': contact_form = ContactForm() return {'contact_form': contact_form} return tags.py @register.inclusion_tag('services/headerfooter.html', takes_context=True) def post_request(context): request = context['request'] if request.method … -
Rest_Pandas and Rest_Framework usage [rest_pandas.html does not exist]
I am working on a webapp with data tracking/visualization in Django. I have a Rest_Framework API configured so far and I'm trying to couple it with Rest_Pandas to create data visualization that visualizes hours submitted by users on one part of the website for managers on another. I have set up my views correct to the Rest_Pandas usage guide: # Organization Hours View class HoursOverviewView(PandasView): queryset = HoursEntry.objects.all() serializer_class = HoursEntrySerializer Along with my url: urlpatterns = [ path('overview/', views.HoursOverviewView.as_view()), ] And my serializer: class HoursEntrySerializer(serializers.ModelSerializer): class Meta: model = HoursEntry fields = ('id', 'user', 'hours_date', 'hours_category', 'hours_amt', 'notes') But, I seem to be getting an error stating: TemplateDoesNotExist at /staff/overview/: rest_pandas.html I'm still new to Django development, API's and third-party packages, so I'm not sure if I'm misunderstanding the purpose of API's, Rest_Pandas, how they interact, or all three. My goal is to create data visualization for the HoursEntry model and this seemed like the most simple approach, but I can't seem to figure it out. -
Oddly unable to reach the media folder in django
I'm tinkering with an image gallery, but I can't seem to make contact with my media folder when upload time comes, and I was hoping someone might point me in the right direction. In settings.py I have: MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' In my main urls.py I have: urlpatterns = [ ... ] urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) and finally in models.py I have: class Gallery(models.Model): class Meta: verbose_name = 'gallery' verbose_name_plural = 'galleries' owner = models.ForeignKey(Profile, on_delete=models.CASCADE) extra_img = models.ImageField(default='default.jpg', upload_to='images') def __str__(self): return self.owner.user.username def save(self, force_insert=False, force_update=False, using=None): super().save() #print(settings.MEDIA_URL + 'images/thumbs_color') #print(settings.MEDIA_ROOT) img = Image.open(self.extra_img.path) xpad = int(img.width/2)-45 ypad = int(img.height/2)-45 coords = (xpad, ypad, xpad+90, ypad+90) color_url = settings.MEDIA_URL + 'images/thumbs_color/' bw_url = settings.MEDIA_URL + 'images/thumbs_bw/' crop_img_color = img.crop(coords) crop_img_color.save(color_url) crop_img_bw = ImageOps.grayscale(crop_img_color) crop_img_bw.save(bw_url) With the idea of creating two thumbnails from the original image, one in color (hover state) and one in b/w (normal state), I find myself struggling with something that I think ought to be a straight shot. Rather confusing indeed; knowing me and my beginner ways, it's most likely something simple I've overlooked. As I had expected the two print statements give me: /media/images/thumbs_color/ C:/Users/vulpes/Desktop/velox/media However, … -
Django admin ImageField: Upload a valid image. The file you uploaded was either not an image or a corrupted image
ERROR: "Upload a valid image. The file you uploaded was either not an image or a corrupted image." I have been looking around and I haven't been able to find a solution to my problem. I use the same images locally in a venv and they work. I use the same images in a docker container that has the same Pillow library and dependancies and it works. I have a Django ImageField that I have a simple admin form. I can get the images to upload to S3 for storage. I have pulled the docker container we use on the servers and I have ran this locally, but is cannot get the error. I have not run into this error before with image uploading, so I am unsure why this is happening. # models.py @deconstructible class RandomFileName(object): def __init__(self, path): self.path = path def __call__(self, instance, filename): ext = filename.split('.')[-1] filename = '{}.{}'.format(uuid.uuid4().hex, ext) return os.path.join(self.path, filename) class MyModel(models.Model): name = models.CharField(max_length=50) avatar = ImageField( upload_to=RandomFileName('avatars') ) ... # admin.py @admin.register(MyModel) class MyModelAdmin(admin.ModelAdmin): list_display = ( 'name', ... ) fieldsets = ( (None, {'fields': ( 'name', 'avatar', )}), ) ... Dependancies: Django==2.0.3 Pillow==5.3.0 -
Run the most basic of tests in python/django
I have created a selenium client to create unit tests against the actual staging website (and its database) without doing everything locally. In other words, I don't think I necessarily need all of django's testing framework and such. Here is the "test function" I want to run: def run_time() s = SeleniumClient() s.login() assert "my-data" in self.user1.current_url It works, and I can run it from the command line. How would I run this test, and how would I properly call it so that it runs as a unit test? -
Django select random value of one column with distinct value on another
I have a table tab(id, pid) where id is the primary keys. Example of values id pid 1 23 2 23 3 5 4 7 5 7 I want to select a random id for each distinct pid. Here is the working mysql query: SELECT a.pid, (SELECT b.id FROM tab AS b WHERE a.pid=b.pid ORDER BY rand() LIMIT 1) AS id FROM tab AS r GROUP BY r.pid order by r.pid; How do I write this query in django syntax? -
How to make a redirect view jump to a section in django
so I have a section in my templates: <div id='comments'>Comments go here</div> now I want my django redirect function to redirect to this page and jump to this div id. return redirect('post_detail', post.slug) Where do I put in '/#comments' to make it jump there on redirecting -
How to install Django on Python 3?
My OS is Ubuntu 18.04 if that helps. I tried installing using pip. It keeps saying it's successful but this is the result: Requirement already satisfied: django in /usr/local/lib/python2.7/dist-packages (1.11.17) Requirement already satisfied: pytz in /usr/local/lib/python2.7/dist-packages (from django) (2014.10) Now, I tried upgrading it and it still shows the same error. I tried using pip3. It's successful but when I try to import it on python 3.0, it shows this error: ModuleNotFoundError: No module named 'django' I also tried installing using virtualenv. It still doesn't work. If it helps, this is the error which shows when I try installing using pip3: Requirement already satisfied: django in ./pgadmin4/lib/python3.6/site-packages (2.1.4) Requirement already satisfied: pytz in ./pgadmin4/lib/python3.6/site-packages (from django) (2018.3) -
How to serve subdirectory as root in nginx using django?
When a user visits www.website.com I would like to server content as if the user went to www.website.com/frontend/. However, I want to mask the /frontend/ part of the url so the user doesn't see it. Can this be done? What would my rewrite rule look like?