Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django login_required decorator does not work with ip 127.0.0.1
I have created a login system the view is as follows: def login_view(request): if request.method == 'POST': form = AuthenticationForm(data=request.POST) if form.is_valid(): user = form.get_user() login(request,user) return redirect('home:index') else: form = AuthenticationForm() return render(request,'accounts/login.html',{'form':form}) and added a login_required decorator to the home page as follows: @login_required(login_url="/login/") def index(request): return render(request, 'home/index.html', context) the problem is when I access the index page with localhost:8000/home/ the page is redirected correctly to the login page but with 127.0.0.1:8000/home/ the home page is rendered and i am not redirected to the login page! any solution? thanks in advance! -
Why are images stored in a Django DB not displaying on a rendered template?
I have the following code snippets in which I am trying to display images stored in a database. (Django2); however, the images are not rendering on my template, they only display a broken image link icon. It is a simple DB model that receives images, and then displays those images in a div below. I presume that my issue must be the routing of the development server, but the documentation isn't explicit as I'd like it to be, since there are many different ways of doing this. Objective: How can I display images that are uploaded to my DB on a django rendered template? See below: # models.py from django.db import models CATE_CHOICES = ( ('MIN', 'MINIMAL'), ('BLOG', 'BLOG'), ('BIO', 'BIO'), ('STORE', 'STORE') ) # NEW_CHOICE = ( # (0, '0'), # (1, '1'), # ) NEW_CHOICE = ( ('NEW', 'new'), ('OLD', 'old'), ) # Create your models here. class catalogdb(models.Model): ''' This is used to handle the actual themes for WP. ''' name = models.CharField(null=False, max_length=20) dateAdded = models.DateField(auto_now_add=True) dloads = models.IntegerField(default=0) imgpocket = models.ImageField(null=False, upload_to='images/preview_icons') filepocket = models.FileField(upload_to='themes') desc = models.TextField(null=False, max_length=500) categ = models.CharField(max_length=15, choices=CATE_CHOICES) new = models.CharField(max_length=7, choices=NEW_CHOICE) def __str__(self): return "{0}/\n{1}/\n{2}/\n{3}/\n{4}/\nNew:{5}/".format( self.name, self.dateAdded, self.dloads, self.desc, … -
Cannot query "The Witcher 3: Wild Hunt": Must be "Article" instance
models.py for products from django.db import models from django.urls import reverse class ProductCategory(models.Model): name = models.CharField(max_length=128, blank=True, null=True, default=None) is_active = models.BooleanField(default=True) def __str__(self): return '%s' % self.name class Meta: verbose_name = 'Category' verbose_name_plural = 'Categories' class Product(models.Model): name = models.CharField(max_length=128, blank=True, null=True, default=None) description = models.TextField(default=None) processor = models.CharField(max_length=300, blank=True, null=True, default=None) video = models.CharField(max_length=300, blank=True, null=True, default=None) ram = models.CharField(max_length=300, blank=True, null=True, default=None) disk_space = models.CharField(max_length=300, blank=True, null=True, default=None) oS = models.CharField(max_length=300, blank=True, null=True, default=None) video_trailer = models.CharField(max_length=10000, blank=True, null=True, default=None) img = models.CharField(max_length=10000, blank=True, null=True, default=None) category = models.ManyToManyField(ProductCategory, blank=True, default=None) is_active = models.BooleanField(default=True) created = models.DateTimeField(auto_now_add=True) slug = models.SlugField(primary_key=True, max_length=250, unique=True, default=None) def __str__(self): return '%s' % self.name def get_absolute_url(self): return reverse('product', args=[str(self.slug)]) class Meta: verbose_name = 'Game' verbose_name_plural = 'Games' class ProductDownload(models.Model): product = models.ForeignKey(Product, blank=True, null=True, default=None, on_delete=False) link = models.CharField(max_length=10000, blank=True, null=True, default=None) is_active = models.BooleanField(default=True) number = models.PositiveIntegerField(blank=True, default=True) def __str__(self): return '%s' % self.product.name class Meta: ordering = ['number'] class Meta: verbose_name = 'Download Link' verbose_name_plural = 'Download Links' class ProductImage(models.Model): product = models.ForeignKey(Product, blank=True, null=True, default=None, on_delete=False) image = models.CharField(max_length=10000, blank=True, null=True, default=None) is_main = models.BooleanField(default=False) is_active = models.BooleanField(default=True) def __str__(self): return '%s' % self.product class Meta: verbose_name = 'Image' … -
Django testing: How to test if an instance is part of the model object set?
The wording to this question is clumsy, sorry about that. I am trying to test whether an instance has been included in model objects. In short is instance, _ = AModel.objects.get_or_create(...) is instance is included AModel.objects. I am using: self.assertIn(model_name_instance, model_name.objects) but I get the error: TypeError: argument of type 'Manager' is not iterable Thank you for your time. -
Django local development server hangs after calling pandas df.plot a second time
I'm trying to build a small website, using django, that stores network performance data. The user will be able to use filters to retrieve the exact data he/she wants and then have the option to graph that data. I'm using django-pandas to convert filtered queryset to a dataframe and from there to create a plot. Everything works fine the first time the plot function is called. When the plot function is called a second time, the python web server just hangs (started from python2.7.exe manage.py runserver). Here is the django view function: def FilteredPerformanceChartsView(request): f = PerfvRtrOnlyFilter(request.GET, queryset=PerfvRtrOnly.objects.all()) df = read_frame(f.qs, fieldnames=['runDate', 'deviceName', 'aggrPPS', 'jdmVersion']) ################################################################# # Let's pass the Pandas DataFrame off to a seperate function for # further processing and to generate a chart. # This should return an image (png or jpeg) ################################################################# chart = pandas_generate_chart(f.qs) return render(request, 'performance_charts.html', context={'filter': f, 'chart': chart, 'dataFrame': df, }, ) The function pandas_generate_chart is where the problem is. After performing a lot of troubleshooting, what appears to trigger the hang is calling df.plot a second time. In other words, when the user hits the button to generate a different chart. Until that second request to generate a chart is submitted, … -
CSRF Cookie Not Set
I have problem with Django CSRF. When I try to register new user or log in I get the next error: CSRF cookie not set. Also on the register page the username and web-site label's don't load correctly, I get symbols like this: 'Ð˜Ð¼Ñ Ð¿Ð¾Ð»ÑŒÐ·Ð¾Ð²Ð°Ñ‚ÐµÐ»Ñ' instead. I have already tried CSRF_COOKIE_SECURE = True,django.middleware.csrf.CsrfViewMiddleware, clearing browser data, my {% csrf_token %} is placed inside the form. Could anyone give me at least some hints about possible errors? My code: forms.py: <form method="post" action="register/"> {% csrf_token %} {{ user_form.as_p }} {{ profile_form.as_p }} views.py def register(request): c = {} c.update(csrf(request)) registered = False if request.method == 'POST': user_form = UserForm(data=request.POST) profile_form = UserProfileForm(data=request.POST) if user_form.is_valid() and profile_form.is_valid(): user = user_form.save() user.set_password(user.password) user.save() profile = profile_form.save(commit=False) profile.user = user profile.save() registered = True else: print(user_form.errors, profile_form.errors) else: user_form = UserForm() profile_form = UserProfileForm() return render_to_response( 'register.html', {'user_form': user_form, 'profile_form': profile_form, 'registered': registered}, c) Thank you for your consideration! -
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?