Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ValidationError: is not a valid UUID in Django
I'm using Django 2.0 I have a Note table and StarredNotes table. Initially, there was no id field as it was added by default by Django as integer data type. Now I have changed the data type of id to UUID in model model.py class Starred(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) user = models.ForeignKey(User, on_delete=models.CASCADE) note = models.ForeignKey(Note, on_delete=models.CASCADE) objects = StarredManager() and views.py class StarredNotes(ListView): template_name = 'notes/starred.html' model = Starred context_object_name = 'starred_notes' def get_queryset(self): starred_notes = Starred.objects.filter(user=self.request.user).order_by('-updated') return starred_notes @method_decorator(login_required) def dispatch(self, request, *args, **kwargs): return super(self.__class__, self).dispatch(request, *args, **kwargs) and urls.py app_name = 'notes' urlpatterns = [ path('starred-notes/$', StarredNotes.as_view(), name='starred'), ] but when I access the view using http://127.0.0.1:1234/notes/shared-notes/ It gives error as ValidationError at /notes/shared-notes/ ["'shared-notes' is not a valid UUID."] -
How to handle video files uploads with django
I'm working on a django project that requires video files of any kind to be uploaded and then transcoded. Everything work fine its just that I sporadically get a "Timeout when reading response headers from daemon process" when uploading a video (well under 2GB in size). This occurs before any processing of the file. I've looked online for a solution and have tried several things to fix, including WSGIApplicationGroup %{GLOBAL} in the httpd.conf and increasing the TimeOut values, but the problem persists. Is there anything I can do in python/django to fix this issue? -
DDT in the Django-admin
Here is what I have in my settings.py file """ Django development settings for v6 project. """ from .common import * # noqa DEV = True DEBUG = True STAGE = 'dev' EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' USERENA_USE_HTTPS = False ALLOWED_HOSTS = ['127.0.0.1', 'localhost'] INSTALLED_APPS = INSTALLED_APPS + [ 'django.contrib.staticfiles', 'debug_toolbar', 'django_extensions', ] MIDDLEWARE = MIDDLEWARE + [ 'debug_toolbar.middleware.DebugToolbarMiddleware', ] DEBUG_TOOLBAR_PANELS = [ 'debug_toolbar.panels.versions.VersionsPanel', 'debug_toolbar.panels.timer.TimerPanel', 'debug_toolbar.panels.settings.SettingsPanel', 'debug_toolbar.panels.headers.HeadersPanel', 'debug_toolbar.panels.request.RequestPanel', 'debug_toolbar.panels.sql.SQLPanel', 'debug_toolbar.panels.staticfiles.StaticFilesPanel', 'debug_toolbar.panels.templates.TemplatesPanel', 'debug_toolbar.panels.cache.CachePanel', 'debug_toolbar.panels.signals.SignalsPanel', 'debug_toolbar.panels.logging.LoggingPanel', 'debug_toolbar.panels.redirects.RedirectsPanel', ] DEBUG_TOOLBAR_CONFIG = { 'INTERCEPT_REDIRECTS': False, } I don't know why, but I can't see the Django debug toolbar in the http://localhost:8000/admin even if I am following the instruction on http://django-debug-toolbar.readthedocs.io/en/stable/installation.html. Django_extensions is working well, but not DDT. What do I need to do to show DDT in the admin? Do I need to add something in settings.py? -
'AttributeError' when overriding 'RelatedField' in Serializing
I'm working with a Django project that implement the Rest framework. I have this model class Portfolio(models.Model): ticker = models.CharField(max_length=10, default='???') name = models.CharField(max_length=25) amount = models.FloatField() owner = models.ForeignKey('auth.User', related_name='portfolio', on_delete=models.CASCADE) def __str__(self): return self.name Note on the 'owner' ForeignKey. And in my serializers.py I have this class MyRelatedField(serializers.RelatedField): def to_representation(self, obj): return 'Test' class UserSerializer(serializers.ModelSerializer): portfolio = serializers.MyRelatedField(many=True) class Meta: model = User fields = ('url', 'id', 'username', 'portfolio') AS I read on the docs, I should override the RelatedField (which I did) if I want a custom representation. However when I try to run I get this error AttributeError: module 'rest_framework.serializers' has no attribute 'MyRelatedField' No matter what I return in MyRelatedField, the same error occurs. My question is how to debug and ideally, fix this error. Thank you. -
Django null value in column "user_id" violates not-null constraint DETAIL: Failing row contains
I have the following problem: I am try to save the user and profile but When I try to post in my database the following error occur: null value in column "user_id" violates not-null constraint DETAIL: Failing row contains (16, 2018-01-01 00:00:00+00, null, colegio monserrat, femenino, null, primero, social, null, null, null, null, null, null, null, null, null, null, Ciencias mundo contemporáneo, Historia de la filosofía, Lengua catalana y literatura I, Lengua catalana y literatura II, Lengua extranjera I, Lengua extranjera II, Lengua castellana y literatura I, Lengua castellana y literatura II, fisica, matematicas, quimica, matematicas, matematicas, matematicas, matematicas, fisica, Educación física, Filosofía, null, Historia). My models is the following: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) birth_date = models.DateTimeField(null=True, blank=True) sex = models.CharField(null=True, max_length=50, choices=SEX_CHOICES) school = models.CharField(null=True, max_length=50, choices=SCHOOL_CHOICES) schoolCode = models.IntegerField(null=True) bachelorCourse = models.CharField(null=True, max_length=50, choices=COURSE_CHOICES) bachelorModality = models.CharField(null=True, max_length=50, choices=COURSE_MODALITY_CHOICES) password = models.CharField(null=True, max_length=50) password2 = models.CharField(null=True, max_length=50) obligatorySubjectOne1 = models.CharField(null=True, max_length=100, default='Lengua catalana y literatura I') obligatorySubjectTwo1 = models.CharField(null=True, max_length=100, default='Lengua castellana y literatura I') obligatorySubjectThree1 = models.CharField(null=True, max_length=100, default='Lengua extranjera I') obligatorySubjectFour1 = models.CharField(null=True, max_length=100, default='Ciencias mundo contemporáneo') obligatorySubjectFive1 = models.CharField(null=True, max_length=100, default='Educación física') obligatorySubjectSix1 = models.CharField(null=True, max_length=100, default='Filosofía') optionalSubjectOne1 = models.CharField(null=True, max_length=100, choices=SUBJECTS_CHOICES_OPTIONALLY) optionalSubjectTwo1 … -
Can't use django variable in include tag
I'm trying to include a .html using {% include "paintings/experiments/points/{{substance.name}}.html" %} This however leads to the error TemplateDoesNotExist. If I hardcode the name of the .html file, it does work. {% include "paintings/experiments/points/fabric.html" %} And, in fact, I can use {{substance.name}} inside the included html, were it does indeed get substituted for fabric. Why can I not use a django variable when using an include tag? -
Django: Hide language prefix conditionally
I'm trying to hide the language prefix in my URL depending on a configuration saved in the database. I already know that setting prefix_default_language=False will hide the default language. My problem: I need the default language to be hidden or showed dynamically depending on a saved object in the database. My idea: create a middleware that reads the object in database and show or hide the prefix. Additional info: I am using the middleware 'django.middleware.locale.LocaleMiddleware'. -
Cutom widget in Django template using inline_formset
I have 2 models Company and CompanyLogo, where CompanyLogo has an FK to Company. For the CompanyLogo I want to have a custom widget. Even if I created a custom widget Django is still using the default Widget, and I don't know why ? The relation between CompanyLogo and Company is 1 to many. It is the same logo, but on different size. If I want to show only a specific size of the logo in widget, how can I replace the for loop and pass that specific size in template ? Models: class Company(Meta): name = models.CharField(max_length=255) class CompanyLogo(models.Model): company = models.ForeignKey(Company, on_delete=models.CASCADE) logo = models.ImageField(upload_to='static/temp') Forms: class CompanyLogoModelForm(forms.ModelForm): class Meta: model = CompanyLogo fields = ['logo'] widgets = { 'logo': forms.CompanyLogoWidget } CompanyLogoFormSet = forms.inlineformset_factory(parent_model=Company, model=CompanyLogo, form=CompanyLogoModelForm, extra=1, can_delete=True) Template: {% for logo_form in form.logos %} {{ logo_form }} {% endfor %} -
Is it possible to pass values from a query to models.py in django?
I'm trying to make an app that some person inserts an id and a birthday date from someone and outputs something. My doubt here is: having a query (from oracle) with the severall id and birthday dates using: connection = cx_Oracle.connect(...) cursor = connection.cursor() cursor.execute("query") My question is: Is it possible to pass some values from the query to my models.py file? For example, in my "models.py" file I have a field called "id" and I would like to pass all the records from the query in the field "doente" to the "models.py" file as "id". My form is something like this: Form where the values from the fields: "GTS do autorizante" and "Data de nascimento do autorizante" are in my models.py and the values from the fields: "GTS do autorizado" and "Data de nascimento do autorizado" come from the query. I would like to copy all the values from the query to my models.py file but I don't know if that is possible. -
Maintain timezone awareness with date and time arithmetic
According to Django : RunTimeWarning : DateTimeField received a naive datetime while time zone support is active, get today's date with timezone information with from django.utils import timezone today = timezone.now() When I do: from datetime import timedelta yesterday = today - timedelta(days=1) But now yesterday is no longer timezone aware. How do I maintain the timezone awareness while doing date and time arithmetic? -
struggling with Django Chosen Form
I'm a new developer and I've come across a javascript library called Chosen.js which would work wonderful for my schools senior project. My problem is I'm having issues getting started and getting the chosen form to show up using django-chosen. I believe it's related to the invalid line break showing up in the linting tool and i'm missing something else. After the pip install django-chosen I've added chosen to my installed files in settings.py as shown below: INSTALLED_APPS = [ 'django_python3_ldap', 'chosen', 'django_extensions', 'django_filters', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'accounts', ] Then I created my chosen form: from django import forms from .models import User, FacilityDimension from django.forms import ModelForm from widgets import ChosenSelectMultiple from chosen import forms as chosenforms class ChosenModelForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(ChosenModelForm, self).__init__(*args, **kwargs) for field in self.fields: if self.fields[field].__class__.__name__ in ['ChoiceField', 'TypedChoiceField', 'MultipleChoiceField']: choices = self.fields[field].choices self.fields[field] = chosenforms.ChosenChoiceField(choices=choices) elif self.fields[field].__class__.__name__ in ['ModelChoiceField', 'ModelMultipleChoiceField']: queryset = self.fields[field].queryset self.fields[field] = chosenforms.ChosenModelChoiceField(queryset=queryset) class FormFacilityDimension(ChosenModelForm): class Meta: model = FacilityDimension After my form is created I use the following in my template, I receive no errors, but i'm not able to get it to show up: {% block extra_js %} {{ block.super }} {{ form.media }} … -
Django generic views DeleteView removes the unexpected object
I have created DeleteView for my 'Album' model, but it's now working as expected. Here is my scripts: urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^albums/create/$', views.AlbumCreateView.as_view(), name='album_create'), url(r'^albums/(?P<slug>[-\w]+)/update/$', views.AlbumUpdateView.as_view(), name='album_update'), url(r'^albums/(?P<slug>[-\w]+)/delete/$', views.AlbumDeleteView.as_view(), name='album_delete'), url(r'^albums/(?P<slug>[-\w]+)/$', views.AlbumDetailView.as_view(), name='album_detail'), url(r'^albums/$', views.AlbumListView.as_view(), name='album_index'), url(r'^songs/create/$', views.SongCreateView.as_view(), name='song_create'), url(r'songs/$', views.SongListView.as_view(), name='song_index'), url(r'^(?P<song_id>[0-9]+)/favorite/$', views.make_song_favorite, name='song_favorite'), url(r'^$', views.AllAlbumListView.as_view(), name='index'), ] views.py from django.views.generic import ListView, DeleteView from django.contrib.auth.mixins import LoginRequiredMixin from .models import Album class AlbumListView(LoginRequiredMixin, ListView): template_name = 'music/album_index.html' context_object_name = 'all_albums' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['album_active'] = True return context def get_queryset(self): queryset = Album.objects.filter(owner=self.request.user).order_by('-release_date') return queryset class AlbumDeleteView(DeleteView): model = Album template_name = 'music/album_index.html' success_url = '/albums/' album_index.html {% extends "base.html" %} {% block content %} <div class="row"> <div class="col-md-9"> <h1>Your Albums</h1> <a class="btn btn-primary" href="{% url 'music:album_create' %}">Add Album <span class="oi oi-plus" title="Add New Album"></span> </a> <div class="card-columns" style="margin-top: 10px;"> {% for album in all_albums %} <div class="card"> <img class="card-img-top img-fluid" src="{{ album.logo.url }}" style="background-size: cover;"> <div class="card-body"> <h4 class="card-title">{{ album.title }}</h4> <h6 class="card-subtitle mb-2 text-muted">{{ album.artist }}</h6> <a class="btn btn-primary" href="{% url 'music:album_detail' album.slug %}">Look Inside</a> <a class="btn btn-primary" href="{% url 'music:album_update' album.slug %}"> <span class="oi oi-pencil" title="Edit Album"></span> </a> <a class="btn btn-primary" href="{% url … -
Django admin error 'WSGIRequest' object has no attribute 'user
I am practicing Django, and when i try to go to http://localhost/admin/ i get the below error, I have checked settings.py and MIDDLEWARE_CLASSES does exist, is there any other reason why i am getting this message. AttributeError at /admin/ 'WSGIRequest' object has no attribute 'user' Request Method: GET Request URL: http://localhost/admin/ Django Version: 2.0 Exception Type: AttributeError Exception Value: 'WSGIRequest' object has no attribute 'user' Exception Location: /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/contrib/admin/sites.py in has_permission, line 186 Python Executable: /usr/local/bin/python3 Python Version: 3.6.1 Python Path: ['/Users/yasserhussain/learning_site', '/Library/Frameworks/Python.framework/Versions/3.6/lib/python36.zip', '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6', '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/lib-dynload', '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages'] Server time: Thu, 4 Jan 2018 00:17:34 +0000 -
module 'models' has no attribute 'ImageField'
I'm trying to add an ImageField to a django model but I'm getting an error telling ImageField does not exist: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/home/trie/Desktop/django/venv/lib/python3.5/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/home/trie/Desktop/django/venv/lib/python3.5/site-packages/django/core/management/__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/trie/Desktop/django/venv/lib/python3.5/site-packages/django/core/management/base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "/home/trie/Desktop/django/venv/lib/python3.5/site-packages/django/core/management/base.py", line 335, in execute output = self.handle(*args, **options) File "/home/trie/Desktop/django/venv/lib/python3.5/site-packages/django/core/management/commands/makemigrations.py", line 78, in handle loader = MigrationLoader(None, ignore_no_migrations=True) File "/home/trie/Desktop/django/venv/lib/python3.5/site-packages/django/db/migrations/loader.py", line 49, in __init__ self.build_graph() File "/home/trie/Desktop/django/venv/lib/python3.5/site-packages/django/db/migrations/loader.py", line 200, in build_graph self.load_disk() File "/home/trie/Desktop/django/venv/lib/python3.5/site-packages/django/db/migrations/loader.py", line 109, in load_disk migration_module = import_module("%s.%s" % (module_name, migration_name)) File "/home/trie/Desktop/django/venv/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 958, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 673, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 673, in exec_module File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed File "/home/trie/Desktop/django/vidmiotest/models/migrations/0013_video_thumbnail.py", line 7, in <module> class Migration(migrations.Migration): File "/home/trie/Desktop/django/vidmiotest/models/migrations/0013_video_thumbnail.py", line 17, in Migration field=models.ImageField(blank=True, null=True, upload_to=models.models.Video.user_directory_path), AttributeError: module 'models' has no attribute 'ImageField' This is my code for adding the ImageField: thumbnail = models.ImageField(upload_to=user_directory_path, default='admin/test.png', max_length=256) i'm using django version: Django-2.0.1 -
django translation logged in user doesn't work
I am struggling with this for days now. My translations work when the user is logged out (django finds all the translations files, also when I use a switch) But once the user is authenticated, django changes the selected language with the default one. django could not find the translation files, only the default language works. Even if I use a switch, the selected language is replace by the default. I work with django allauth. I can't explain this issue. Who could help? Thank you so much for the great help -
Custom context processor doesn't work in base template while works in other templates
I have simple context processor that chechks account type of logged user. Context processor works fine on index page, but it doesn't work in base.html. Here is code to custom context processor: def isdadilja(request): isdadilja = False if hasattr (request.user, 'dadilja'): isdadilja = True return { 'isdadilja' : isdadilja, } settings.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATE_DIR,], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'accounts.context_processors.isdadilja' ], }, },] {{ isdadilja }} tag works fine when used in index.html but it doesn't work in base.html. What am I doing wrong? Should I somehow load it first to base template? -
Django reverse url not matching despite finding the right url [duplicate]
This question is an exact duplicate of: NoReverseMatch with keyword argument uidb64 with Django 2.0 1 answer I have the following in the main url.py file url(r'^authentication/', include(authentication.urls.urlpatterns)), and the following line in the auth url.py url(r'confirm/(?P<uidb64>[0-9A-Za-z]+)-(?P<token>.+)/$', confirm_email_with_token, name="confirm_email"), and when I try to render the reverse url like so {% url 'confirm_email' uidb64=uid token=token %} I get the following django.urls.exceptions.NoReverseMatch: Reverse for 'confirm' with keyword arguments '{'uidb64': b'MTU', 'token': '4sk-9bb9de4589dcfd386fdc'}' not found. 1 pattern(s) tried: ['authentication/confirm/(?P<uidb64>[0-9A-Za-z]+)-(?P<token>.+)/$'] Reverse lookup for the passwordresetview also defined in the authentication urls is working fine. I'm sure it is something trivial that I'm missing but I can't seem to figure out what. I'm using django 2 and python 3.6 -
How to iniciate workers in celery
I want to know if is this the correct way to iniciate workers in celery celery multi start -A app conc carga -c:conc 1 -c:carga 3 if anyone can give more details of what this script does, I'm trying to run async task in django using celery. then i start celery doing this. ./manage.py celeryid -lDEBUG -
Add OneToMany relation model instances from parent model instance Django Form
I have a Person model: class Person(models.Model): name = models.CharField(max_length=100) And then a Car model: class Car(models.Model): plate = models.CharField(max_lenght=100) owner = models.ForeignKey(Person) And then a certain CarAttribute model: class CarAttribute(models.Model): whatever = models.CharField(max_lenght=100) car = models.ForeignKey(Car) Person has a relation 1 to many to Car. Car has a relation 1 to many to Car attributre. Is there a way in Django for adding the Car (and eventually its relative CarAttributes) in the Form to be used when adding a new Person? One person may have more than one car, and one car can multiple attributes. Any hints on how to approach this solution with Django? Or complementary tool? -
How to use blocks for attribute in django
I want to use jinja2 blocks for attribute in django. Basically on every page I want a different url for a header image. This is the base.html: <header id="masthead" style="background-image:url('{% block headerimage %}{% endblock %}'" . . . How do I pass in '{% static 'img/some-bg.jpeg' %} to it from index.html which {% extends "base.html" %}? I tried to use this block syntax I just showed and it does now work. How do I achieve this? I want to pass in a string for the url of an image from a template that inherits from the base template. Thank you :-). -
Django rest ModelViewSet multiple GET requests with different URLs
I have to Models: A Library can have many Books. Right now I have a URL for performing CRUD on Books in a specific Library: router.register(r'books/(?P<library_id>[0-9]+)', BookViewSet, base_name='books') and corresponding view: class BookViewSet(viewsets.ModelViewSet): serializer_class = BookSerializer def get_queryset(self): genre_query = self.request.query_params.get('genre', None) status_query = self.request.query_params.get('status', None) author_query = self.request.query_params.get('author', None) books = Book.objects.filter(which_library=self.kwargs.get('library_id')) if genre_query: books = books.filter(genre=genre_query) if status_query: books = books.filter(status=status_query) if author_query: books = books.filter(author=author_query) return books I originally did not use ModelViewSet instead I had functions with @api_view decorators, one of which was following (returning books added in last two weeks, I had a separate URL for this function as api/books//new_arrivals): @api_view(['GET']) def new_arrivals(request, library_id): """ List all new arrival books in a specific library """ d=timezone.now()-timedelta(days=14) if request.method == 'GET': books = Book.objects.filter(which_library=library_id) books = books.filter(when_added__gte=d) serializer = BookSerializer(books, many=True) return Response(serializer.data) While using ModelViewSets, how can I do it? Must I add another URL and then write another class for new_arrivals or write a function in existing BookViewSet? How to achieve handling those two GET methods in that case? -
Why do we need Signatures in Celery?
I've started using Celery 4.1 in my Django Python project and have come across Signatures. In the documentation it says the following: You just learned how to call a task using the tasks delay method in the calling guide, and this is often all you need, but sometimes you may want to pass the signature of a task invocation to another process or as an argument to another function. A signature() wraps the arguments, keyword arguments, and execution options of a single task invocation in a way such that it can be passed to functions or even serialized and sent across the wire. Although I see them used in some of the examples I don't really know when and why to use them, as well as which problems they solve. Can someone explain this to a layman? -
Display logo in my django-admin
I plugged Django-jet to my project and it works fine. I am trying to install a logo on the top left corner of my Django-admin, but it failed. I think the following answer is relevant here : Custom logo in django jet. (venv) ┌─╼ [~/Projects/Work_Projects/clients.voila6.com/v6] └────╼ ls .. dev_requirements.pip dploy.yml v6_project media requirements.pip dploy v6 manage.py README.md scripts (venv) ┌─╼ [~/Projects/Work_Projects/clients.voila6.com/v6] └────╼ ls admin.py clientspace core fixtures messaging __pycache__ templates urls.py apps.py configurations customers __init__.py orders settings.py tests.py views.py So templates/admin/base_site.html is in ~/Projects/Work_Projects/clients.voila6.com/v6, media/my_logo.png is in ~/Projects/Work_Projects/clients.voila6.com and MEDIA_URL is in ~/Projects/Work_Projects/clients.evoila5.com/ev5_project/conf/settings/common.py Here is my base_site.html file {# Template: your_app/templates/admin/base_site.html #} {% load static i18n %} {# Setup favicon #} {% block extrahead %}<link rel="shortcut icon" type="image/png" href="/media/e5_favicon.png"/>{% endblock %} {# Setup browser tab label #} {% block title %}{{ title }} | {% trans "Your title" %}{% endblock %} {# Setup branding #} {% block branding %} <h1 id="site-name"> <a href="{% url 'admin:index' %}"> {# Your logo here #} <img style="background-color: white" src="{{MEDIA_URL}}{% trans "e5_logo_eng-300x150" %}.png" alt="évoilà5" height="50%" width="50%"> <!--<br><br>--> <!--</span> {# trans "Your Branding" #%}--> </a> </h1> {% endblock %} I have not a lot of experience with Django and I think I forgot a step, but … -
Django Wrong save image in view func, but in admin panel save correct! how to fix?
Why does jango save the image while in the main specified directory, add one more such directory with the same name, and only create the necessary package and store it there? P.S. on local work everythin, if i save image using browser and admin pane, he save where it's need and suppose to be there, but if it makes in view, via for after gen image, save with wrong path this is my media root location theband@TheBand:~/media$ ls fake_qr_code_img media section_about did you see this *** same folder but in models set, some another special folder, without media this is model class QRCode(models.Model): user = models.ForeignKey(UserProfile, blank=True, default=None) qr_code = models.CharField(max_length=120) qr_code_img = models.ImageField(upload_to="qr_code_img/", width_field="width_field", height_field="height_field") upcoming_show = models.ForeignKey(SectionUpcomingShow) width_field = models.IntegerField(default=270) height_field = models.IntegerField(default=270) is_active = models.BooleanField(default=True) timestamp = models.DateTimeField(auto_now=False, auto_now_add=True) updated = models.DateTimeField(auto_now_add=False, auto_now=True) def __str__(self): return "{0} - - {1}".format(self.user.user.username, self.is_active) def save(self, *args, **kwargs): img = Image.open(self.qr_code_img) img_name = self.qr_code_img.name new_image_io = BytesIO() if img.format == 'JPEG' : img.save(new_image_io, format='JPEG', quality=85) elif img.format == 'PNG' : img.save(new_image_io, format='PNG', quality=85) elif img.format == 'jpg' : img.save(new_image_io, format='JPG', quality=85) self.qr_code_img.delete(save=False) self.qr_code_img.save( img_name, content=ContentFile(new_image_io.getvalue()), save=False ) super(QRCode, self).save(*args, **kwargs) class Meta: ordering = ["-timestamp"] verbose_name = 'QRCode' verbose_name_plural = … -
Python Django how can't render my variables from views.py on html file
How can i render my variables from models in a html file, they was rendering a time ago before I made html link slug with class(DetailView) in my views.py HTML FILE (product.html) <h2 class="heading">{{ product.name }}</h2> <div style="clear: both;"><br></div> <div class="block"> <div class="img_preview"> <img src="{{ product.img }}"> <div class="categ"> {% for category in product.category.all %} <a href=""><span>{{ category }}</span></a> {% endfor %} {# <div style="clear: both"><br></div> #} </div> </div> <div id="links"> {% for link in links %} <div class="download_link"> <a href="{{ links.link }}"><span>DOWNLOAD MIRROR NUMBER {{ links.number }}</span></a> </div> {% endfor %} </div> <div style="clear: both"></div> <div id="games"> <div id="video_trailer"> <iframe width="560" height="317" src="{{ product.video_trailer }}" frameborder="0" gesture="media" allow="encrypted-media" allowfullscreen></iframe> <div id="description"> <span class="title">Description</span> <p>{{ product.description }}</p> </div> </div> <div style="clear: both"><br></div> <div id="system_requirements"> <span class="title">System Requirements</span><br> <p>Processor:&ensp;{{ product.processor }}<br> <br> Graphic Card:&ensp;{{ product.video }}<br> <br> Memory:&ensp;{{ product.ram }}<br> <br> Disk Space:&ensp;{{ product.disk_space }}<br> <br> OS:&ensp;{{ product.oS }} </p> </div> </div> <div id="screenshots"> {% for image in product_images %} <div class="screenshot"> <img width="1920px" height="1080px" src="{{ image.image }}" > </div> {% endfor %} </div> </div> </div> <aside> <div id="news"> <h2 class="heading">News</h2> <div style="clear: both"><br></div> {% for articles in news_articles %} <div id="articles"> <div class="article"> <a href="{{ articles.article.get_absolute_url }}"> <img src="{{ articles.image …