Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python - Convert PDF to HTML through stream instead of path
I am trying to convert a PDF file to HTML by using PDF2HTML: pdf_path = "path\to\pdf_file.pdf" subprocess.run(["pdf2htmlEX.exe",pdf_path]) This works well. However, I would like pdf_path be a Stream instead of a path on my server. My use case is a Django App that lets users upload a PDF file and it converts it to an HTML page without saving anything on a server. I tried converting the uploaded PDF file to a BytesIO and then to a stream and trying to pass that: from PyPDF2 import PdfFileReader, PdfFileWriter # Request.FILES is from the Django Form file_memory = request.FILES # BytesIO file file_handle_file = file_handle.file pdf = PdfFileWriter() pdf_file = PdfFileReader(file_handle_file) page = pdf_file.getPage(0) pdf.addPage(page) pdf.write(open("output.pdf","wb")) subprocess.run(["pdf2htmlEX.exe",pdf]) But this returns a argument of type 'PdfFileWriter' is not iterable error. The pdf.write does write the pdf to storage and if I use subprocess.run to get that file (so using path again), it does work. Also, opening a Stream doesn't work: outputStream = open("test.pdf", "wb") output.write(outputStream) outputStream.close() subprocess.run(["pdf2htmlEX.exe",outputStream]) Is it even possible to pass a pdf file from memory to pdf2htmlEX instead of a path? I've also looked at making it a base64 (base64.b64encode(file_handle_file.getvalue()).decode()), but also to no avail. Many thanks everyone! -
["'%(value)s' value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format."] will show up if I check for full_clean()
I am getting the following error when I try to see if my object is valid using full_clean(). django.core.exceptions.ValidationError: {'schedule_date': ["'%(value)s' value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format."]} I have tried all the formats recommended here, but none of them work for me: Whats the correct format for django dateTime? I won't get error when I create the object like Object.objects.create(...) Here is my models.py: from datetime import datetime, timedelta, date from django.db import models from django import forms from django.utils import timezone from django.core.exceptions import ValidationError from userstweetsmanager.constants import LANGUAGE_CHOICES def password_validator(value): if len(value) < 6: raise ValidationError( str('is too short (minimum 6 characters)'), code='invalid' ) class User(models.Model): name = models.TextField(max_length=30, unique=True) password = models.TextField(validators=[password_validator]) twitter_api_key = models.TextField(null=True, blank=True) twitter_api_secret_key = models.TextField(null=True, blank=True) twitter_access_token = models.TextField(null=True, blank=True) twitter_access_token_secret = models.TextField(null=True, blank=True) expire_date = models.DateField(default=date.today() + timedelta(days=14)) language = models.TextField(choices=LANGUAGE_CHOICES, default='1') def schedule_date_validator(value): if value < timezone.now() or timezone.now() + timedelta(days=14) < value: raise ValidationError( str('is not within the range (within 14 days from today)'), code='invalid' ) def content_validator(value): if len(value) > 140: raise ValidationError( str('is too long (maximum 140 characters)'), code='invalid' ) class Tweet(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) content = models.TextField(validators=[content_validator]) schedule_date = models.DateTimeField(validators=[schedule_date_validator]) … -
pip can not install requirements after docker-compose up
i got these errors and warnings after step 6 of sudo docker-compose up WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError(': Failed to establish a new connection: [Errno -3] Temporary failure in name resolution')': /simple/asn1crypto/ WARNING: Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError(': Failed to establish a new connection: [Errno -3] Temporary failure in name resolution')': /simple/asn1crypto/ WARNING: Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError(': Failed to establish a new connection: [Errno -3] Temporary failure in name resolution')': /simple/asn1crypto/ WARNING: Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError(': Failed to establish a new connection: [Errno -3] Temporary failure in name resolution')': /simple/asn1crypto/ WARNING: Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError(': Failed to establish a new connection: [Errno -3] Temporary failure in name resolution')': /simple/asn1crypto/ ERROR: Could not find a version that satisfies the requirement asn1crypto==0.24.0 (from -r requirements.txt (line 1)) (from versions: none) ERROR: No matching distribution found for asn1crypto==0.24.0 (from -r requirements.txt (line 1)) this is my Dockerfile codes: FROM python:3 ENV PYTHONUNBUFFERED 1 RUN mkdir /todo_service WORKDIR /todo_service COPY /requirements.txt /todo_service RUN pip install -r requirements.txt COPY . … -
UI field for text and picture editing
I have a CreateView with title, content and image fields. I would like to allow users to put the picture where they please within the contend field. I would like to add to my site a field like this : I don't need something so detailed but for the moment the picture position is where I have put the img html tag. And I want it to be chosen by the user as he is writing a post. If someone could help me please to figure out how to achieve this with bootstrap and django. thx -
problem in django sitting , server doesn't run
i have face in django such this problem in the sitting, raise ImproperlyConfigured("The %s setting must be a list or a tuple. " % setting) django.core.exceptions.ImproperlyConfigured: The INSTALLED_APPS setting must be a list or a tuple. when i add new app, djano doesn't migrate neither makemogrations and even server doesn't run, so please could you help me -
Error while trying to connect Django to Micro soft server - Error was: No module named 'sql_server'
I am trying to connect Django to remote Microsoft Server, but I keep getting the following error : django.core.exceptions.ImproperlyConfigured: 'sql_server.pyodbc' isn't an available database backend. Try using 'django.db.backends.XXX', where XXX is one of: 'mysql', 'oracle', 'postgresql', 'sqlite3' Error was: No module named 'sql_server' DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'OPTIONS':{ "driver": "FreeTDS", "extra_params": "tds_version=7.3", }, 'NAME': 'db_name', 'USER': 'user_name', 'PASSWORD': 'password', 'HOST': 'host_address', 'PORT': '1433' } } -
Cannot test many-to-many references in Django
I want to test m2m reference that I've created. In models, it's like this: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) def __str__(self): return self.user.username class List(models.Model): name = models.CharField(max_length = 4) user = models.ManyToManyField(Profile) def __str__(self): return f'{self.name} by {self.user.__str__()}' @receiver(post_save, sender = User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user = instance) @receiver(post_save, sender = User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() My test looks as follows: def test_create_list(self): self.create_user("test_user") # returns User.objects.create_user extended_user = Profile.objects.get(pk = 1) l = List.objects.create( name = "2019" ) l.user.add(extended_user) self.assertEqual(l.__str__(), f"2019 by {extended_user.__str__()}") This results in a failed test: Expected :'2019 by hay.Profile.None' Actual :'2019 by test_user' Why this hay.Profile.None comes up? I tried adding l.save() before the assertion, but it doesn't help. What can I do? -
Deploying Django code (which needs Selenium) to heroku - Python
I have a website made using Django, click a button on the website triggers a scraper to start. This scraper uses selenium. I have added the following two build packs needed for selenium to my heroku app: 1) https://github.com/heroku/heroku-buildpack-chromedriver 2) https://github.com/heroku/heroku-buildpack-google-chrome chrome_options = webdriver.ChromeOptions() chrome_options.binary_location='/app/.apt/usr/bin/google-chrome' os.environ.get("GOOGLE_CHROME_BIN", "chromedriver") browser=webdriver.Chrome(executable_path=os.environ.get("GOOGLE_CHROME_BIN", "chromedriver"),chrome_options=chrome_options) But yet it fails to find the chromedriver and throws the error chromedriver needs to be in PATH, how to fix this issue? Where is the chromedriver executable? -
Testing extended user profile returns false positives in Django
I have an extended user profile, done like this: from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) def __str__(self): return f'{self.user.username} 123' @receiver(post_save, sender = User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user = instance) @receiver(post_save, sender = User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() And I want to test it: from models import Profile from django.contrib.auth.models import User def test_create_profile(self): base_user = self.create_user("test_user") self.assertTrue(isinstance(base_user, User)) extended_user = Profile.objects.last() self.assertTrue(extended_user.__str__(), "test_user") As you can see, __str__() should return '{self.user.username} 123', so for this example, test_user 123. But, those tests are passing fine. What can I do? -
Want to Pass a Message to the User and Make him redirect to index page on Invalid Login credentials
In Views.py, I've Queried the login credentials of the user who registered on a web page. On Invalid Credentials, He must return to Index page or must be given a url / button to return to index page. Here's the current code that's not working: def user_login(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(username=username,password=password) if user: if user.is_active: login(request,user) return HttpResponseRedirect(reverse('index')) else: return HttpResponse('Account Not Active') else: return HttpResponse('Invalid Login Details Supplied!') return HttpResponseRedirect(reverse('index')) else: return render(request,'basicapp/login.html') It's only showing the statement 'Invalid login Details Supplied!' to the user for wrong credentials without changing the webpage link (Link getting unchanged is certain) Can't figure out how to place a button / url in html file in case of such scenarios. Any Hint on Redirect + Message display? A redirect after a few seconds of message display is also fine without a button / url. -
Django : After selecting element from dropdown list, how to perform an action
I want to select the option from dropdown list and according to selected element go to my database file which is CSV show the result related to that selected element. my HTML code: {% extends "base.html"%} {%block body%} {% load static %} <section> <h2 align ="center" margin = 10px> Selecting parameters </h2> <div> <form align = 'center' method ="post" action=" help to describe this action url where to direct ?" > {%csrf_token%} <label class="label">Generators</label> <select id = "myList" onchange="this.form.submit()"> {% for name in generator %} <option> {{name}}</option> {%empty%} <option> no list found </option> {%endfor%} </select> </div> <div> <button type="submit" class="myButton"> submit </button> </div> </form> <textarea>{{selected_generator}}</textarea> </section> <footer id="main-footer"> <p> Copyright &2019; polito interdispilinary group 2019</p> </footer> {%endblock%} </body> </html> Views.py def generator(request): file = pd.read_csv("G:/interdispilinary project/Website/resources/generator/up_op_zone.csv") df = pd.DataFrame(file) generator= df['generator'] operator = df['operator'] zone = df['zone'] return render(request, 'generator.html',{'generator':generator}) def gen_results(request): if request.method =='POST': user_submit = gen_form(request.POST) print(request.POST) if user_submit.is_valid(): print(user_submit) selected_generator = user_submit.cleaned_data['generator'] request.session['selected_generator'] = selected_generator df = pd.read_csv("G:/interdispilinary project/Website/resources/generator/up_op_zone.csv",names=["generator","operator","zone"]) df1 = df[df["generator"]==selected_generator][["operator","zone"]] return render(request, 'generator.html',{'selected_generator':selected_generator}) url.py urlpatterns = [ url(r'^$', views.homepage, name='homepage'), url(r'^generator', views.get, name='generator_url'), url(r'^gen_results', views.gen_results, name='gen_results_url'), url(r'^market', views.market, name='market_url'), url(r'^operator', views.operator, name='operator_url'), when i will click to submit button it have to save the result … -
Django-Rest-Framework Custom User not Hashing Password (Serializer Issue)
I am trying to use token authentication, but it is not working due to my create user serializer not hashing the passwords. I am able to login with the superuser as that has a hashed password. Using rest_auth and rest_framework.authtoken. The user.set_password command is supposed to hash the password, so is there an issue with the prior code? class CreateUserSerializer(serializers.HyperlinkedModelSerializer): username = serializers.CharField() password = serializers.CharField(write_only = True, style = {'input_type': 'password'}) class Meta: model = get_user_model() fields = ( 'id','username', 'password', 'email', 'first_name', 'last_name' ) write_only_fields = ('password') read_only_fields = ('is_staff', 'is_superuser', 'is_active') def create(self, validated_data): password = validated_data.pop('password') user = super().create(validated_data) user.set_password(validated_data['password']) user.save() return user class CreateUserAPIView(CreateAPIView): """ Create a new user. """ serializer_class = CreateUserSerializer permission_classes = [AllowAny] def create(self, request, *args, **kwargs): serializer = self.get_serializer(data = request.data) serializer.is_valid(raise_exception = True) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) # Create a token that will be used for future auth token = Token.objects.create(user = serializer.instance) token_data = {"token": token.key} return Response( {**serializer.data, **token_data}, status = status.HTTP_201_CREATED, headers = headers ) AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', 'PAGE_SIZE': 20, 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', ), … -
How can I access This particular Page and extend it.. Its a django admin page
Ill put this in a very simple way. I would want to access django-admin html of a particular page. here is the image. https://ibb.co/N7m5TZ0 of the page I want to access. The link is as http://127.0.0.1:8000/admin/listings/listing/12/change/ I just want to add my custom html button to it which will introduce a feild once clicked. How would I extend the html of this particular page. Thank You -
how to display only last six words
so I want to display only last six words and truncate the first part. {% for each_season in season %} <a href="{% url 'season_detail' slug=each_season.slug %}">{{each_season|something}}</a> {% endfor %} is there anything i can put into |something to achieve this goal? -
I can't find Django functions in the source code
I am writing a Django app and creating a custom user model. To do this I'm importing get_user_model from django.contrib.auth and this works fine. However, in order to understand things better, I'm trying to find this function in the Django source code but when I go to django.contrib.auth in the Git repo I can't find it. Could anyone tell me where I'm going wrong, please? -
Running Management command with celery?
I have never used Celery before and am trying to configure it correctly. I am using redis as the broker and hosting on heroku. This is my first time trying to run asynchronous tasks and I'm struggling. I have a Management command that I would like to run periodically. celery.py from __future__ import absolute_import, unicode_literals import os import celery from celery import Celery import django from django.conf import settings os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'coffee.settings') app = Celery('coffee') app.config_from_object('django.conf:settings', namespace = 'CELERY') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) @app.task(bind= True) def debug_task(self): print('Request: {0!r}'.format(self.request)) app.conf.beat_schedule = { 'add-every-30-seconds':{ 'task': 'inventory.tasks.boarshead', 'schedule' : 30.0, 'args' : () }, } settings.py CACHES = { "default": { "BACKEND": "redis_cache.RedisCache", "LOCATION": os.environ.get('REDIS_URL'), } } tasks.py from celery import shared_task import celery import time from django.core import management @celery.task def boarshead(): try: print("in celery module") """Boarshead expired sessions by using Django Management Command.""" management.call_command("clearsessions", verbosity=0) CreateBoarsHeadList.py return "success" except: print(e) init.py from __future__ import absolute_import, unicode_literals from .celery import app as celery_app procfile worker: celery worker --app=tasks.inventory.app -
"This field is required" when all fields are filled in Django
When filling out a form I get "This field is required." even though all fields are filled in. It doesn't have to do with setting required to False or anything like that, because all fields are required. views.py def upload(request): if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): title = form.cleaned_data['title'] username = request.user.get_username() category = form.cleaned_data['category'] handle_uploaded_file(request.FILES['file'],title,username,category) return HttpResponseRedirect('') else: form = UploadFileForm() return render(request, 'main/upload.html', {'form': form}) function def handle_uploaded_file(f,title,username,category): with open('/uploads/' + category + '/' + title, 'wb+') as destination: for chunk in f.chunks(): destination.write(chunk) forms.py class UploadFileForm(forms.Form): title = forms.CharField(max_length=50) category = forms.CharField(max_length=50) file = forms.FileField() upload.html {% extends 'base.html' %} {% block title %}Upload{% endblock %} {% block content %} {% if user.is_authenticated %} Uploading as: {{ user.username }} <form method="post"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Submit"/> </form> {% else %} <p>You are not logged in</p> <a href="{% url 'login' %}">login</a> {% endif %} {% endblock %} The error I get when filling out a form is: "This field is required" Screenshot: https://i.imgur.com/n4zDf0W.png (When I select a file and it throws the error it unselects whatever file I've selected, similar to how the password field is cleared when hitting sign … -
Django: return messages in form.clean()
Suppose I have a CreateView that uses a ModelForm to add a new calendar event. Sometimes, when adding a new calendar event, another calendar event has to be added before the new event to be able to successfully validate the new event (which happens in the ModelForm.clean() method). I think the only place this other event can be added is in the clean method, just before the validation which validates the new event. Am I right that this is the only place I can do this? I want to let the user know that this happened using Django messages, but of course I don't have access to the request object in the ModelForm. That makes me think I have to add this event in another place. Which method of CreateView is suited for this purpose? I'm sorry in advance for my English and if my question isn't worded good enough. Thanks in advance. -
Websocket related errors when working with Django Rest Framework and Vue
I'm working with Django 2, Django Rest Framework, Vue and Docker on a rather simple CRUD SPA. The basic CRUD functions are already working properly, but I'm constantly getting a long list of errors in the browsers developer console. These are the errors: WebSocket connection to 'ws://localhost:8000/sockjs-node/960/pxv3l3z5/websocket' failed: Error during WebSocket handshake: Unexpected response code: 200 POST http://localhost:8000/sockjs-node/960/mf1pj0yr/xhr_streaming?t=1558372142795 403 (Forbidden) WebSocket connection to 'ws://localhost:8000/sockjs-node/124/3qg4rd5f/websocket' failed: Error during WebSocket handshake: Unexpected response code: 200 EventSource's response has a MIME type ("text/html") that is not "text/event-stream". Aborting the connection. They all seem to be related with a web socket issue, but I'm not actively using websockets. The app just issues a couple of requests to the Django Rest Framework backend. So I really don't know what is causing these errors. Maybe I configured something wrong? -
Use custom UserCreationForm with GeoDjango admin (OSMGeoAdmin)
Django==2.2.1 GDAL==2.3.2 django-username-email==2.2.4 I have a simple Django application with a custom user model based on django-username-email's AbstractCUser, which removes the username from the user model, using e-mail address instead. On the user model, I defined a PointField field storing the user's current location. models.py from django.contrib.gis.db import models as gis_models from cuser.models import AbstractCUser class User(AbstractCUser): """Custom user model that extends AbstractCUser.""" current_location = gis_models.PointField(null=True, blank=True,) I would like to register this model in Django admin so that I can register new users and view/set their location with a map widget. This kind of works if I use a custom user admin based on admin.OSMGeoAdmin in combination with a custom user change form: admin.py from django.contrib.gis import admin from django.contrib.auth import get_user_model from .forms import CustomUserCreationForm, CustomUserChangeForm class CustomUserAdmin(admin.OSMGeoAdmin): model = get_user_model() add_form = CustomUserCreationForm # <- there seems to be a problem here form = CustomUserChangeForm list_display = ['email', 'last_name', 'first_name'] readonly_fields = ['last_login', 'date_joined'] admin.site.register(get_user_model(), CustomUserAdmin) forms.py from django.contrib.auth import get_user_model from django.contrib.auth.forms import UserCreationForm, UserChangeForm class CustomUserCreationForm(UserCreationForm): class Meta(UserCreationForm.Meta): model = get_user_model() exclude = ('username',) class CustomUserChangeForm(UserChangeForm): class Meta(UserChangeForm.Meta): model = get_user_model() fields = ( 'email', 'first_name', 'last_name', 'current_location', # ... ) When I open an … -
psycopg2.OperationalError: SSL error: unknown protocol expected authentication request from server, but received S
I am setting up a Django Website. It works on my local computer a windows, but throws this error whenever I try to run a command say python manage.py X I run it on my remote server, which runs a CentOs7 terminal: The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/usr/local/lib/python3.6/threading.py", line 916, in _bootstrap_inner self.run() File "/usr/local/lib/python3.6/threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "/home/DavFri/my_site/env/lib/python3.6/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/home/DavFri/my_site/env/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 120, in inner_run self.check_migrations() File "/home/DavFri/my_site/env/lib/python3.6/site-packages/django/core/management/base.py", line 453, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "/home/DavFri/my_site/env/lib/python3.6/site-packages/django/db/migrations/executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "/home/DavFri/my_site/env/lib/python3.6/site-packages/django/db/migrations/loader.py", line 49, in __init__ self.build_graph() File "/home/DavFri/my_site/env/lib/python3.6/site-packages/django/db/migrations/loader.py", line 212, in build_graph self.applied_migrations = recorder.applied_migrations() File "/home/DavFri/my_site/env/lib/python3.6/site-packages/django/db/migrations/recorder.py", line 73, in applied_migrations if self.has_table(): File "/home/DavFri/my_site/env/lib/python3.6/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 "/home/DavFri/my_site/env/lib/python3.6/site-packages/django/db/backends/base/base.py", line 256, in cursor return self._cursor() File "/home/DavFri/my_site/env/lib/python3.6/site-packages/django/db/backends/base/base.py", line 233, in _cursor self.ensure_connection() File "/home/DavFri/my_site/env/lib/python3.6/site-packages/django/db/backends/base/base.py", line 217, in ensure_connection self.connect() File "/home/DavFri/my_site/env/lib/python3.6/site-packages/django/db/utils.py", line 89, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "/home/DavFri/my_site/env/lib/python3.6/site-packages/django/db/backends/base/base.py", line 217, in ensure_connection self.connect() File "/home/DavFri/my_site/env/lib/python3.6/site-packages/django/db/backends/base/base.py", line 195, in connect self.connection = self.get_new_connection(conn_params) File "/home/DavFri/my_site/env/lib/python3.6/site-packages/django/db/backends/postgresql/base.py", line 178, in get_new_connection connection = Database.connect(**conn_params) File "/home/DavFri/my_site/env/lib/python3.6/site-packages/psycopg2/__init__.py", line … -
how to get environment variables when using pipenv?
I have the following: .env: REDIS_HOST=localhost REDIS_PORT=6379 When I got to the PyCharm shell, and do the following: import os print(os.getenv('REDIS_HOST')) I get None I tried using the following: print(os.environ.get('REDIS_HOST')) But no luck. Any help will be appreciated <3 -
two slugs in one url, kwargs and args
I want my url to be like 'slug/slug/' if they are not combined together each slug works fine but when I try to combine these two, I get into the problem. I think I can use args and kwargs for this but I don't know how to apply this. path('series/<slug>/', views.season_pg, name='season_detail'), def season_pg(request, slug, slug): series = Series.objects.get(slug=slug) season_nr = Season.objects.get(slug=slug) content_dict = { 'season_nr':season_nr } return render(request, 'series.html', content_dict) Models.py class Series(models.Model): name = models.CharField(max_length=128, unique=True) genre = models.CharField(max_length=128, default=1) tv_or_movie = models.CharField(max_length=128, default=1) period = models.CharField(max_length=128, default=1) descritpion = models.TextField() slug = models.SlugField(unique=True) #img #video def __str__(self): return self.name def get_absolute_url(self): return "/%s/" %self.slug class Season(models.Model): series = models.ForeignKey(Series, on_delete=models.CASCADE, blank=True, null=True) season_nr = models.CharField(max_length=128, default=1) date = models.DateTimeField(auto_now_add = True) slug = models.SlugField(unique=True) def __str__(self): return str(self.season_nr) -
Django users can't login
I made a custom UserCreationForm. I can signup but after that I can't login into my web app. I can only login as a superuser. I imported the LoginView() but when I try to login it tells me "Please enter a correct username and password. Note that both fields may be case-sensitive.". [views.py] @csrf_exempt def signup(request): if request.method == 'POST': user_form = UserForm(data=request.POST) profile_form = UserProfileInfoForm(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 if 'profile_pic' in request.FILES: print('found it') profile.profile_pic = request.FILES['profile_pic'] profile.save() # registered = True login(request, user, backend='django.contrib.auth.backends.ModelBackend') return redirect('../') else: print(user_form.errors,profile_form.errors) else: user_form = UserForm() profile_form = UserProfileInfoForm() return render(request,'users/signup.html', {'user_form':user_form, 'profile_form':profile_form,'registered':registered}) forms.py class UserForm(UserCreationForm): class Meta(): model = User fields = ('username','email') def __init__(self, *args, **kwargs): super(UserCreationForm, self).__init__(*args, **kwargs) for fieldname in ['username', 'password1', 'password2']: self.fields[fieldname].help_text = None class UserProfileInfoForm(forms.ModelForm): class Meta(): is_photographer = forms.BooleanField() model = UserProfileInfo fields = ('portfolio_site','profile_pic', 'type_of_photography', 'is_photographer',)``` models.py class UserProfileInfo(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) portfolio_site = models.URLField(blank=True) profile_pic = models.ImageField(upload_to='profile_pics',blank=True) is_photographer = models.BooleanField(default=False) type_of_photography = models.CharField(max_length=120, blank=True) def __str__(self): return self.user.username -
How can I apply a filter to {%?
I need to apply my own filter to this line. How to do it? srcset="{% static 'images/img/shop.png' %}" filter @register.filter def to_retina(value): pointer = value[value.rfind('.'):] return value[:value.rfind('.')]+'@2x'+pointer