Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: How to update an Integerfield and decrement its value
This seemingly innocuous problem has turned out to be quite difficult to find any information on. I just want to decrement the value of an Integerfield column by 1 in my database, by calling a function. views.py function call StudentProfile.objects.add_lesson(student_id) managers.py class StudentQuerySet(models.QuerySet): def add_lesson(self, sid): self.filter(student_id=sid).update(remaining_lessons=remaining - 1) class StudentProfileManager(models.Manager): def add_lesson(self, sid): self.get_queryset().add_lesson(sid) Full StudentProfile model class StudentProfile(models.Model): student = models.OneToOneField( User, related_name='student', primary_key=True, parent_link=True, on_delete=models.CASCADE) portrait = models.ImageField( upload_to='studentphotos', verbose_name=_('Student Photo')) about_me = models.TextField(verbose_name=_("About Me")) spoken_languages = models.CharField(max_length=255) teacher_default = models.OneToOneField( 'teachers.TeacherProfile', related_name='teacher_default', parent_link=True, on_delete=models.CASCADE, default=None, blank=True, null=True) membership_start = models.DateTimeField( verbose_name="Membership Start Date", default=now, editable=False) membership_end = models.DateTimeField( verbose_name="Membership End Date", default=now, editable=False) remaining_lessons = models.IntegerField( verbose_name="Membership remaining lessons", default=0) objects = StudentProfileManager() def __str__(self): return User.objects.get_student_name(self.student_id) I know this is totally wrong, any help is appreciated. -
How can I validate uniqueness of an instance in a collection in django rest framework
I have the following models. class ServerGroup(models.Model): name = models.SlugField(unique=True) factor = models.IntegerField() class ServerGroupMember(models.Model): class Meta: unique_together = ( ("server_group", "position"), ("server_group", "server"), ) position = models.IntegerField() server_group = models.ForeignKey( "ServerGroup", related_name="servers", on_delete=models.CASCADE ) server = models.ForeignKey("Server", on_delete=models.CASCADE) A ServerGroup has a couple of properties, name and factor, and a collection of ServerGroupMember objects. Each ServerGroupMember object, contains an integer position and a reference to a Server object. For a given ServerGroup the position must be unique, and for a given ServerGroup the server must be unique. However, globally, the position and server objects do not have to be unique, as in 2 ServerGroups may contain a server at postion 1, and the same Server may appear in multiple Server Groups, just not multiple times in the same Server Group. Given that I have the following serializers, how can I validate the above? The model currently does validate the condition at the database level, but will raise a unique constraint error if I attempt to violate it. What I want is to be able to detect this in my views, such that I can return an appropriate validation error message response before it has a chance to hit the … -
What is the most performant way to store an image as base64 dataURL?
I am using Django 3.0 with PostgreSQL 12. I need to store an image and render it on a page as base64 for use in a javascript function. Is it more performant to: store the image as TextField and save the raw base64 in the database store the image as a file on the server (using filefield), and convert the image server side to base64 before returning it in context store the image as a file on the server, and convert the image client side to base64? The images are all <10kb big, and typically would be less than 50 per page. However there may be a large number of page loads with concurrent users. -
makemigrations isn't working- how to fix it?
I have a dockerized django project. I'm trying to make migrations, but I keep getting this error. What does this mean, and how can I fix it? I am really new to this, so please be as detailed as possible! Thank you The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/Users/jasminedogu/opt/anaconda3/lib/python3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/Users/jasminedogu/opt/anaconda3/lib/python3.7/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/jasminedogu/opt/anaconda3/lib/python3.7/site-packages/django/core/management/base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "/Users/jasminedogu/opt/anaconda3/lib/python3.7/site-packages/django/core/management/base.py", line 369, in execute output = self.handle(*args, **options) File "/Users/jasminedogu/opt/anaconda3/lib/python3.7/site-packages/django/core/management/base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "/Users/jasminedogu/opt/anaconda3/lib/python3.7/site-packages/django/core/management/commands/makemigrations.py", line 101, in handle loader.check_consistent_history(connection) File "/Users/jasminedogu/opt/anaconda3/lib/python3.7/site-packages/django/db/migrations/loader.py", line 283, in check_consistent_history applied = recorder.applied_migrations() File "/Users/jasminedogu/opt/anaconda3/lib/python3.7/site-packages/django/db/migrations/recorder.py", line 76, in applied_migrations if self.has_table(): File "/Users/jasminedogu/opt/anaconda3/lib/python3.7/site-packages/django/db/migrations/recorder.py", line 56, in has_table return self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor()) File "/Users/jasminedogu/opt/anaconda3/lib/python3.7/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/Users/jasminedogu/opt/anaconda3/lib/python3.7/site-packages/django/db/backends/base/base.py", line 260, in cursor return self._cursor() File "/Users/jasminedogu/opt/anaconda3/lib/python3.7/site-packages/django/db/backends/base/base.py", line 236, in _cursor self.ensure_connection() File "/Users/jasminedogu/opt/anaconda3/lib/python3.7/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/Users/jasminedogu/opt/anaconda3/lib/python3.7/site-packages/django/db/backends/base/base.py", line 220, in ensure_connection self.connect() File "/Users/jasminedogu/opt/anaconda3/lib/python3.7/site-packages/django/db/utils.py", line 90, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "/Users/jasminedogu/opt/anaconda3/lib/python3.7/site-packages/django/db/backends/base/base.py", … -
Django call HttpResponse view in Javascript file
I want to call a HttpResponse from a view in my main.js file, but I'm getting this error in the console //localhost:8000/%7B%%20url%20'join_dpt'%20%%7D 404 (Not Found), everything was fine when I had all in a same index.html file but now I don't want to have the scrips in the index.html so I moved it to a main.js file. This is how I'm calling the HttpResponse (I was doing the same in the index.html file and it was fine) d3.json("{% url 'join_dpt' %}") this is how my folders order: -- django -- env -- app -- project -- urls.py -- static -- css -- js -- main.js -- templates -- index.html and I have this in my settings.py STATIC_URL = '/static/' #new STATICFILES_DIRS =( os.path.join(BASE_DIR,'static'), ) any ideas on how can I solve this? -
How to get data from Query set?
I have this data from forms <QueryDict: { 'csrfmiddlewaretoken': ['GKVYyp5MZHM39C4UJU13YOqCr5euox35X6xy19L87FhKwQY7UiT9nQYBpnNm7ZSt', 'GKVYyp5MZHM39C4UJU13YOqCr5euox35X6xy19L87FhKwQY7UiT9nQYBpnNm7ZSt', 'GKVYyp5MZHM39C4UJU13YOqCr5euox35X6xy19L87FhKwQY7UiT9nQYBpnNm7ZSt', 'GKVYyp5MZHM39C4UJU13YOqCr5euox35X6xy19L87FhKwQY7UiT9nQYBpnNm7ZSt'], 'User': ['11', '11', '12', '13'], 'month': ['march', 'march', 'february', 'july'], 'regularFee': ['1500', '988', '7656', '7000'], 'extraFee': ['0', '0', '23', '7'], 'discount': ['234', '0', '0', '7'], 'Total': ['1500', '987', '1500', '7000']}> can anyone please tell me how to extract data from this I want a new dictionary which will have index as key and value will be another dictionary of data, which will include information of each user if request.method == 'POST': keys = [] length = 0 for key in request.POST.keys(): keys.append(key) length = len(request.POST[key]) for index in range(length): dict_messForm = {} for key in keys: dict_messForm.update({key:request.POST[key][index]}) forms.append(messFeeForm(dict_messForm)) this is giving me an error 'string index out of range'...... how can I create forms from this QueryDict ? -
Connecting django to MS SQL Server using odbc
I'm getting an error when trying to execute manage.py runserver. I've installed django-pyodbc and the odbc driver 17 for sql server. Do I need to import pyodbc somewhere in the project? I am very new to django and python in general but I want to use ms sql server instead of sqlite. This is the code in manage.py: DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'database', 'HOST': 'localhost', 'USER': 'user', 'PASSWORD': 'password', 'OPTIONS': {'ODBC Driver 17 for SQL Server', } } } Here is the error: (venv) C:\Users\Kirk\PycharmProjects\PyShop>manage.py runserver Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x000001770CD61438> Traceback (most recent call last): File "C:\Users\Kirk\PycharmProjects\PyShop\venv\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Users\Kirk\PycharmProjects\PyShop\venv\lib\site-packages\django\core\management\commands\runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "C:\Users\Kirk\PycharmProjects\PyShop\venv\lib\site-packages\django\utils\autoreload.py", line 248, in raise_last_exception raise _exception[1] File "C:\Users\Kirk\PycharmProjects\PyShop\venv\lib\site-packages\django\core\management\__init__.py", line 337, in execute autoreload.check_errors(django.setup)() File "C:\Users\Kirk\PycharmProjects\PyShop\venv\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Users\Kirk\PycharmProjects\PyShop\venv\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Kirk\PycharmProjects\PyShop\venv\lib\site-packages\django\apps\registry.py", line 112, in populate app_config.import_models() File "C:\Users\Kirk\PycharmProjects\PyShop\venv\lib\site-packages\django\apps\config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "C:\Users\Kirk\AppData\Local\Programs\Python\Python37\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", … -
Django Rest Framework CI Pipeline
I'm configuring an aws pipeline for my django application that uses elasticsearch, redis-celery and DRF. I'm don't have any devops experience. from best practices. How many stages should my pipeline included? And what are they? -
Adding Slugs to URL pattern
I want users to access posts using either the PK or Slug value. I can get http://localhost:8000/post/8/ to work but not http://localhost:8000/post/working-in-malaysia/. I have looked at a few posts on Stack Overflow but I don't want http://localhost:8000/post/8/working-in-malaysia. And I don't want it to be a case of either the PK works. Or the slug works. I want the user to be able to enter either. Below you can see my failed attempts. path('post/<int:pk>/', views.post_detail, name='post-detail'), #path('post/<slug:the_slug>/', views.post_detail, name='post-detail-slug'), #path('post/<slug:slug>/', views.post_detail, name='post-detail-slug'), #path('post/(?P<slug>[-\w]+)/$', views.post_detail, name='post-detail-slug'), path('post/<slug>', views.post_detail, name='post-detail-slug'), -
Paginate Filtered Search
I have a search form for the users on my page. It is actually a form with POST method, which get all inserted parameters from POST in my function and based on that parameters (check which parameters was filled in form) doing search in my database and sending it back to user like this (searched data are fetched query set based on users searching) paginator = Paginator(searched_data, 15) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) return render(request, 'online_db/terema_kensaku.html', {'page_obj': page_obj}) which works fine, but it has one problem. This ALL happens in my function under if request.method == "POST": And of course if user press NEXT PAGE button on this searched data, he is performing a GET action, so there are no data - no NEXT PAGE. Even if I try to do the same under if request.method == "GET": it's not possible, because I'm not able to get a parameters from users (POST form) to perform database filtering on all data from database. My views.py is too long with a lot of paramaters and variables, so I'm not gonna paste it here but it works like this right now. def terema_kensaku(request): if request.method == "POST": search_data = [] search_list = … -
How to add prefix "token" on django-yasg?
I've installed django-rest-framework and django-yasg to generate the swagger documentation, when i try to use the ui from django-yasg the authentication does not use the prefix Token on the Authentication header, e.g: Header needed for django-rest-framework: "Authentication: Token XXX" Header generated by the django-yasg: "Authentication: XXX" I also have found this issue; https://github.com/axnsan12/drf-yasg/issues/367 saying that i need to add the prefix token through the swagger-ui, but how can i do this? This my swagger settings: SWAGGER_SETTINGS = { 'SECURITY_DEFINITIONS': { 'Token': { 'type': 'apiKey', 'name': 'Authorization', 'in': 'header' }, }, 'USE_SESSION_AUTH': False } -
Django select2 not loadign value on formset extra-views
Select2 is not showing the search or values on the formset to be selected like this, but on the updateView for the individual objects it works fine. form.py class AvaliadorForm(forms.ModelForm): """Defini avaliador""" class Meta(): model = Resultado fields = ['avaliador'] #TODO Não esta funcionando widgets = { # TODO mudar DB para postersql e adiciona unaccent em search fields 'avaliador': s2forms.ModelSelect2Widget( model=User, search_fields=['nome_completo__icontains', 'matricula__icontains'], attrs={'data-minimum-input-length': 0}), } def __init__(self, *args, **kwargs): """Definie user como o user passado em get_kwargs""" super(AvaliadorForm, self).__init__(*args, **kwargs) # filtra os avaliadores com base no is_avaliador self.fields['avaliador'].queryset = User.objects.filter( is_avaliador=True) view.py class AvaliadorFormSetView(PermissionRequiredMixin, ModelFormSetView): "Defini avaliadores em bloco, com base no semestre" model = Resultado template_name = 'cc/manage_avaliadores.html' success_url = reverse_lazy('cc:solicitacoes') factory_kwargs = {'extra': 0} permission_required = 'user.can_add_avaliador' form_class = AvaliadorForm def get_queryset(self): slug = self.kwargs['slug'] return super(AvaliadorFormSetView, self).get_queryset().filter(solicitacao__semestre_solicitacao__slug=slug) I'm also using django-extra-views to render the formset. THe field avaliador is a foregein Key -
Override Django LoginView Error Message With Custom AuthenticationForm
I have a class-based view that subclasses LoginView. from django.contrib.auth.views import LoginView class CustomLoginView(LoginView): def get_success_url(self): url = self.get_redirect_url() return url or reverse_lazy('knowledgebase:user_home', kwargs={ 'username':self.request.user.username, }) I want to override the error message if a user's email is not yet active because they have to click a link sent to their email address. The current default message looks like this: Instead of saying: Please enter a correct email address and password. Note that both fields may be case-sensitive. I want to say something to the effect of: Please confirm your email so you can log in. I tried: accounts/forms.py from django.contrib.auth.forms import AuthenticationForm from django.utils.translation import gettext as _ class PickyAuthenticationForm(AuthenticationForm): def confirm_login_allowed(self, user): if not user.is_active: raise forms.ValidationError( _("Please confirm your email so you can log in."), code='inactive', ) accounts/views.py class CustomLoginView(LoginView): # 1. <--- note: this is a class-based view form_class = PickyAuthenticationForm # 2. <--- note: define form here? def get_success_url(self): url = self.get_redirect_url() return url or reverse_lazy('knowledgebase:user_home', kwargs={ 'username':self.request.user.username, }) The result is absolutely no effect when I try to log in with a user that does exist, but hasn't verified their email address yet. -
Django django-cors-headers returning `Access-Control-Allow-Origin` header
I feel like I get CORS issues every time I set up a new server. Does anyone see something I’m missing? Access to fetch at 'https://staging-app.example.com/api/token/' from origin 'https://staging.example.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. I’m using django-cors-headers==3.2.1 My Middleware: MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] Other settings: ALLOWED_HOSTS = ["*"] CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True CORS_ORIGIN_WHITELIST = [ 'https://staging.example.com', ] # If this is used, then not need to use `CORS_ORIGIN_ALLOW_ALL = True` CORS_ORIGIN_REGEX_WHITELIST = [ 'https://staging.example.com', ] I’ve implemented every single solution I could find on this thread: "No 'Access-Control-Allow-Origin' header is present on the requested resource" in django What else am I missing? What else can I try? -
How to Fix ModuleNotFoundError
i wrote this code : from .forms import * # Create your views here. def index(request): tasks = Task.objects.all() form= TaskForm() if request.method == "POST": form = TaskForm(request.POST) if form.is_valid(): form.save() return redirect('/') context= {'tasks':tasks , 'form':form} return render(request, 'tasks/list.html' , context) and after running it it gave me this error : ** ModuleNotFoundError: No module named 'tasks.forms' ** -
Django ProgrammingError "Table doesn't exist" looking for a table in the wrong database when running migrate --database=
I have a Django app using two databases: default (created by my django app) and paretodb (legacy db, for which I made the models using inspectdb). Here's the router: class ParetoRouter (object): def db_for_read(self, model, **hints): "Point all operations on buyer_ladder models to 'paretodb'" if model._meta.app_label == 'buyer_ladder': return 'paretodb' return 'default' def db_for_write(self, model, **hints): "Point all operations on buyer_ladder models to 'paretodb'" if model._meta.app_label == 'buyer_ladder': return 'paretodb' return 'default' def allow_relation(self, obj1, obj2, **hints): "Allow any relation if a both models in buyer_ladder app" if obj1._meta.app_label == 'buyer_ladder' and obj2._meta.app_label == 'buyer_ladder': return True # Allow if neither is buyer_ladder app elif 'buyer_ladder' not in [obj1._meta.app_label, obj2._meta.app_label]: return True return False def allow_syncdb(self, db, model): if db == 'paretodb' or model._meta.app_label == "buyer_ladder": return False # we're not using syncdb on our legacy database else: # but all other models/databases are fine return True Here is part of login_registration.models.py: class Company(models.Model): name = models.CharField(max_length=255) cbsa = models.CharField(max_length=5, blank=True, null=True, default=None) authorized_tester = models.BooleanField(default=False) def __str__(self): return self.name class Meta: app_label = "login_registration" class User(models.Model): first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) email = models.CharField(max_length=255) company = models.ForeignKey( Company, related_name="users", on_delete=models.CASCADE, default=None ) password = models.CharField(max_length=255) created_at = models.DateTimeField(auto_now_add=True) … -
auto-populate Model B with the data from Model-A and/or Model-C
firstly abstractly speaking - each time i create an order via Model A i want to auto-populate Model B with the data from Model-A and/or Model-C. now straight to the point - i want both, the customer's name & the product (which they are purchasing) to automatically appear as a concatenated string in the third model, a different one. class Customer name = models.CharField(max_length=200, null=True) plus class Product name = models.CharField(max_length=200, null=True) equals to class Account... customer + product (both in the same field) how to achieve this ? here are my main files. models.py from django.db import models # Create your models here. class CustomerKlase(models.Model): name = models.CharField(max_length=200, null=True) phone = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200, null=True) dateCreated = models.DateTimeField(auto_now_add=True) def __str__(self): return '{}'.format(self.name) class TagKlase(models.Model): name = models.CharField(max_length=200, null=True) def __str__(self): return '{},'.format(self.name) class ProductKlase(models.Model): THE_CATEGORY = ( ("Indoor0","Indoor1"), ("Outdoor0","Outdoor1") ) name = models.CharField(max_length=200, null=True) price = models.FloatField(null=True) category = models.CharField(max_length=200, null=True, choices=THE_CATEGORY, blank=True) description = models.CharField(max_length=200, null=True, blank=True) dateCreated = models.DateTimeField(auto_now_add=True) tags = models.ManyToManyField(TagKlase) def __str__(self): return '{}'.format(self.name) class AccountKlase(models.Model): customer = models.ForeignKey(CustomerKlase, null=True, on_delete=models.SET_NULL) product = models.ForeignKey(ProductKlase, null=True, on_delete=models.SET_NULL) def __str__(self): return '{} & {}'.format(self.customer, self.product) class OrderKlase(models.Model): THE_STATUS = ( ("Pending-0","Pending-1"), ("Out for delivery 0","Out … -
How should one convert Django generic CBVs to the REST API CBVs?
I'm fairly new to Django and webdev -- I've gone through the official tutorials, but I'm a bit confused when it comes to the REST framework. As I understand, the REST framework basically lets me serialize my standard Django models, so I can decouple my Django code from the frontend of the website. This gives me more options than just using the Django templating language for everything, and I can use something like React or Angular to create a frontend. The thing that has me confused is how the Django standard class based views fit into this picture. The serialization of the models makes sense to me -- that said, in my app right now, I have a few different generic CBVs (LoginViews, FormViews, etc.). Do I need to rewrite these using the CBVs provided in the REST framework, or is there something similar to the model serialization that would make this easier? -
Modifying URL patterns so they work with the slug field (Python - Django)
Users are able to write and update posts on my website. I also want the user to be able to access posts using either the PK (primary key) or Slug (Slugify, SlugField) value. I can get http://localhost:8000/post/8/ to work but not http://localhost:8000/post/working-in-malaysia/. I have looked at a few posts on Stack Overflow but I don't want http://localhost:8000/post/8/working-in-malaysia. And I don't want it to be a case of either the PK works. Or the slug works. I want the user to be able to enter either. Below is the code I have tried. I tried to merge together code I saw in a number of other posts. Sadly to no avail. urls.py urlpatterns = [ path('', PostListView.as_view(), name='blog-home'), path('post/<int:pk>/', views.post_detail, name='post-detail'), #path('post/<slug:the_slug>/', views.post_detail, name='post-detail-slug'), path('post/<slug:url>/', views.post_detail, name='post-detail-slug'), path('post/new/', PostCreateView.as_view(), name='post-create'), path('post/<int:pk>/update/', PostUpdateView.as_view(), name='post-update'), path('post/<int:pk>/delete/', PostDeleteView.as_view(), name='post-delete'), path('about/', views.about, name='blog-about'), path('facebook/',TemplateView.as_view(template_name='blog/index.html'), name="facebook") ] views.py class PostDetailView(DetailView): model = Post # Should match the value after ':' from url <slug:the_slug> #slug_url_kwarg = 'the_slug' slug_url_kwarg = 'url' pk_url_kwarg = "id" # Should match the name of the slug field on the model slug_field = 'url' # DetailView's default value: optional query_pk_and_slug = True def dispatch(): post = get_object_or_404(Post) comments = post.comments.filter(active=True, slug=slug) new_comment = … -
Nginx routing everything to /
I used to have the following nginx.conf: upstream xyz{ server web:8000; } server { listen 80; return 301 https://$host$request_uri; } server { listen 443 ssl http2; listen [::]:443 ssl http2; ssl_certificate /etc/ssl/certs/localhost.crt; ssl_certificate_key /etc/ssl/private/localhost.key; ssl_protocols TLSv1.2 TLSv1.1 TLSv1; location / { proxy_pass http://xyz/; proxy_set_header X-Forwarded-Proto https; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } location /staticfiles/ { alias /home/app/web/staticfiles/; } } And when you went to localhost it directed you to web docker image and showed you exactly what you were suppose to see. It was using django and wasnt terribly nice so we created a new UI and attempted to reach the back end via this, but even when I go to localhost/rest/ its directing me to the UI and not to what it was pointing to before just some of the images aren't there: upstream xyz { server web:8000; } server { listen 80; return 301 https://$host$request_uri; } server { listen 443 ssl http2; listen [::]:443 ssl http2; ssl_certificate /etc/ssl/certs/localhost.crt; ssl_certificate_key /etc/ssl/private/localhost.key; ssl_protocols TLSv1.2 TLSv1.1 TLSv1; location /rest/ { proxy_pass http://xyz/; proxy_set_header X-Forwarded-Proto https; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } location /staticfiles/ { alias /home/app/web/staticfiles/; } location / { root /static_ui_volume/; try_files $uri $uri/ … -
How do you set input formats for modelformset_factory in Django?
I am trying to a DateTime picker to my datetime fields as per this guide. However the tutorial requires you to set an input format on your datetime fields, as shown below: date = forms.DateTimeField(input_formats=['%d/%m/%Y %H:%M']) How would you accomplish this for a FormsetFactory or ModelFormsetFactory? -
Django: "no such table: auth_user" on attempt to create superuser using custom user model
Custom user model I use works great on my another project, but here it refuses to allow creating superuser returning error I pointed out in title. Normal users can be created easily. Here is models.py class UserManager(BaseUserManager): def create_user(self, username, password=None): if not username: raise ValueError('Please select your username') if not email: raise ValueError('Tell us your email address') user = self.model( email = self.normalize_email(email), username = username, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, username, email, password): user = self.create_user( email = self.normalize_email(email), username = username, password = password, ) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class User(AbstractBaseUser): first_name = models.CharField(max_length=30, blank=True) last_name = models.CharField(max_length=30, blank=True) email = models.EmailField(unique=True) username = models.CharField(max_length=50, unique=True) date_joined = models.DateTimeField(auto_now_add=True) last_login = models.DateTimeField(auto_now_add=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) bio = models.TextField(max_length=500, blank=True) role = models.CharField(max_length=20, default='user') USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email', 'username'] objects = UserManager() def __str__(self): return self.first_name + ' ' + self.last_name def has_perm(self, perm, obj=None): return self.is_admin def has_module_perms(self, app_label): return True Any help is appreciated, thank you. -
Can I not use django.contrib.contenttypes?
I use django-admin startproject mysite and created a sample django project. I don't think the sample project has any models so I commented out "django.contrib.contenttypes" in INSTALLED_APPS in settings.py. I also commented out all middlewares. I then wrote a simple view from django.shortcuts import render def index(request): return render(request, 'hello.html') and hello.html is just a blank file. Once I access the page, django throws exception Model class django.contrib.contenttypes.models.ContentType doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. Can anyone help explain the exception? The sample project doesn't have any model, why do I need django.contrib.contenttypes? Can django websites live without django.contrib.contenttypes? -
is there a way to automatically update database structure in django as soon as new field added/updated?
Basically subj. I know that there are some implementations, using django-idmapper but I haven't found any instructions how to implement that in an actual project. The idea is that during the development it would superuseful if the change in the database (new models added to models.py, new fields added to existing models, etc. would automatically lead to database reset, and new migrations applied. In development only, of course. Any ideas or ready-made solutions that are available? -
TypeError: __init__() got an unexpected keyword argument 'required'
I have an error when using the field_classes attribute, in my form: class UserChangeForm(UserChangeForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['username'].widget.attrs.update({'class': 'form-control form-control-sm'}) self.fields['url'].widget.attrs.update({'class': 'form-control form-control-sm'}) self.fields['avatar'].widget.attrs.update({'class': 'custom-file-input'}) self.fields['biography'].widget.attrs.update({ 'class': 'form-control form-control-sm', 'placeholder': 'Cuéntanos un poco sobre ti', 'style': 'height: 70px; max-height: 150px; min-height: 70px;' }) class Meta: model = User fields = ['username', 'avatar', 'biography', 'url'] field_classes = {'avatar': forms.FileInput} labels = {'biography': 'Biografia', 'url': 'URL'} If I comment out the field_classes = {'avatar': forms.FileInput} line, everything works fine and without any errors, but why is this happening? ERROR: Exception in thread django-main-thread: Traceback (most recent call last): File "/home/lcteen/miniconda3/envs/django/lib/python3.7/threading.py", line 926, in _bootstrap_inner self.run() File "/home/lcteen/miniconda3/envs/django/lib/python3.7/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/home/lcteen/miniconda3/envs/django/lib/python3.7/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/home/lcteen/miniconda3/envs/django/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "/home/lcteen/miniconda3/envs/django/lib/python3.7/site-packages/django/core/management/base.py", line 390, in check include_deployment_checks=include_deployment_checks, File "/home/lcteen/miniconda3/envs/django/lib/python3.7/site-packages/django/core/management/base.py", line 377, in _run_checks return checks.run_checks(**kwargs) File "/home/lcteen/miniconda3/envs/django/lib/python3.7/site-packages/django/core/checks/registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "/home/lcteen/miniconda3/envs/django/lib/python3.7/site-packages/django/core/checks/urls.py", line 13, in check_url_config return check_resolver(resolver) File "/home/lcteen/miniconda3/envs/django/lib/python3.7/site-packages/django/core/checks/urls.py", line 23, in check_resolver return check_method() File "/home/lcteen/miniconda3/envs/django/lib/python3.7/site-packages/django/urls/resolvers.py", line 398, in check for pattern in self.url_patterns: File "/home/lcteen/miniconda3/envs/django/lib/python3.7/site-packages/django/utils/functional.py", line 80, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/lcteen/miniconda3/envs/django/lib/python3.7/site-packages/django/urls/resolvers.py", line 579, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", …