Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
validators for bulk image upload
I have setup a validator for a image upload field to check if the image is too large, it is working as expected. def validate_image(image): file_size = image.file.size if file_size > settings.MAX_UPLOAD_SIZE: raise ValidationError(f'Image {image} is too large 3mb max') image = models.ImageField(default='default.jpg', storage=PublicMediaStorage(), upload_to=path_and_rename, validators=[validate_image]) Now I want to do the same thing for a bulk image upload field I have. def validate_image_bulk(images): file_size = images.file.size if file_size > settings.MAX_UPLOAD_SIZE: raise ValidationError(f'Image {images} is too large 3mb max') images = models.ImageField(upload_to=path_and_rename_bulk, validators=[validate_image]) If you upload more than one image and one of the images is above the max upload threshold it does not upload any of the images and does not throw the validation error but it still submits the form. If you upload a single image that is too large the same thing occures How can I raise the validation error and not have the form submit like it does for the single image field view: (the bulk model is PostImagesForm) postForm = PostForm() if request.method == 'POST': postForm = PostForm(request.POST, request.FILES) if len(request.FILES.getlist('images')) > 30: raise Exception("Max of 30 images allowed") else: if postForm.is_valid(): PostFormID = postForm.save(commit=False) PostFormID.author = request.user PostFormID.save() if len(request.FILES.getlist('images')) == 0: return redirect('post-detail', … -
How to index Image url in elasticsearch using django
I am trying to index an Image url to elasticsearch in but I keep on failing. And I recieve photo_main = null in my search responses. anyone have an idea how it should be done? below is my relevant code, I summarized it as far as possible. thanks in advance model.py class Recipe(models.Model): id = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False, ) photo_main = models.ImageField(upload_to='media/', blank=True) title = models.CharField(max_length=150) instructions_text_list = ArrayField(models.CharField(max_length=100,),default=list, size=15,) ingredients_text_list = ArrayField(models.CharField(max_length=100,),default=list, size=15,) def get_absolute_url(self): """Return absolute URL to the Recipe Detail page.""" return reverse('recipes:detail', kwargs={"pk": self.id}) def __str__(self): return self.title documents.py from django_elasticsearch_dsl import Document, fields from django_elasticsearch_dsl.registries import registry from elasticsearch_dsl import analyzer, tokenizer from .models import Recipe autocomplete_analyzer = analyzer('autocomplete_analyzer', tokenizer=tokenizer('trigram', 'edge_ngram', min_gram=1, max_gram=20), filter=['lowercase'] ) @registry.register_document class RecipeDocument(Document): title = fields.TextField(required=True, analyzer=autocomplete_analyzer) ingredients_text_list = fields.ListField(fields.TextField()) instructions_text_list = fields.ListField(fields.TextField()) photo_main = fields.FileField() class Index: name = 'recipes' settings = { 'number_of_shards': 1, 'number_of_replicas': 0, 'max_ngram_diff': 20 } class Django: model = Recipe fields = [ 'id', ] -
Djanog display user specific objects
I solved the last problem. Now I tested some stuff and got a problem. I want to display user specific objects. If user a user enters his details (for example number), I just want to display the phone number of the user in the html template, not from someone else. So the user can only see his number. I created this. forms.html <form method='POST' action="." enctype="multipart/form-data"> {% csrf_token %} {{ form }} <button type='submit' class=''>Submit</button> </form> <p>{% if details.phone %} {{details.phone}} {% else %} &nbsp; {% endif %} </p> <p> {{ request.user }} </p> views.py def edit_profile(request): details = UserProfile.objects.all()[0] try: profile = request.user.userprofile except UserProfile.DoesNotExist: profile = UserProfile(user=request.user) if request.method == 'POST': form = UserProfileForm(request.POST, instance=profile) if form.is_valid(): form.save() return redirect('/') else: form = UserProfileForm(instance=profile) return render(request, 'forms.html', {'form': form, 'details': details}) models.py class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(blank=True) phone = models.CharField(max_length=10, blank=True) address = models.CharField(max_length=1024) age = models.PositiveIntegerField(blank=True, null=True) gender = models.IntegerField(default=1) The {{ request.user }} works fine, it shows the current username of the signed in user. And with {{ details.phone }} I want to just display the number the user entered in the phone field. But currently it is displaying the number of … -
django alter css style width on progress bar
I have a progress bar, with style width set in css, is there a way to update that style width with some logic in django, and how? <div class="progress-bar bg-warning" role="progressbar" style="width: 25%" aria-valuenow="25" aria-valuemin="0" aria-valuemax="100"></div> Now lets say that i want a more dynamic update on the width? -
how to popup form with django formset
i've have application in the home page there shows some posts with a contact form, i want to create a modal formset in another view! is it possible please ? @login_required def addPopupVistor(request): formset = VistorFormSet(queryset=Vistor.objects.none(),prefix='formsetvisitor') if request.is_ajax() and request.method == 'POST': formset = VistorFormSet(request.POST,prefix='formsetvisitor') if formset.is_valid(): for form in formset: obj = form.save(commit=False) if form.cleaned_data !={}: obj.admin = request.user obj.save() return JsonResponse({'success':True}) else: return JsonResponse({'success':False,'error_msg':formset.errors}) return render(request,'main/home.html',{'formsetvisitor':formset}) const addNewFormRow = document.getElementById('addPopUpButton') const totalNewPopUpForms = document.getElementById('id_formsetvisitor-TOTAL_FORMS') addNewFormRow.addEventListener('click',add_new_popuprow); function add_new_popuprow(e){ if(e){ e.preventDefault(); } const currentFormPopUpClass = document.getElementsByClassName('popup_modal_formset') const countpopupForms = currentFormPopUpClass.length const formCopyPopupTarget = document.getElementById('visitorform') const empty_form = document.getElementById('empty_popup_formset').cloneNode(true); empty_form.setAttribute('class','relative p-2 bg-gray-900 bg-opacity-25 border border-gray-900 rounded-xl pb-14 popup_modal_formset') empty_form.setAttribute('id',`form-${countpopupForms}`) const rgx = new RegExp('__prefix__','g') empty_form.innerHTML = empty_form.innerHTML.replace(rgx,countpopupForms) totalNewPopUpForms.setAttribute('value',countpopupForms + 1) formCopyPopupTarget.append(empty_form) } <button onclick="modal()" class="some css class">add new guest</button> <div id="modal" class="w-full fixed top-0 md:overflow-y-scroll hidden flex flex-wrap p-1 h-screen justify-center items-center bg-black opacity-90" style="z-index: 99999;"> <div class="w-full md:w-10/12 p-2 bg-white rounded-xl"> <button id="addPopUpButton" class="px-4 py-1 pb-2 text-white focus:outline-none header rounded-xl"> {% trans "add new form" %} <i class="fas fa-plus"></i> </button> <form method="POST" class="mt-2" id="addnewguests">{% csrf_token %} {{formsetvisitor.management_form}} <div id="visitorform" class="grid md:grid-cols-3 gap-16 md:gap-x-3 md:gap-y-8"> {% for form in formsetvisitor.forms %} {{ form.pk }} {{form}} <!-- first form --> <div class="relative … -
django project creation, could not find django.core.managment error
Everytime I create a new django project. I get an error message as shown below: Import "django.core.management" could not be resolved from source Pylance(reportMissingModuleSource)[11,14] Below is the steps I use to create django project: create folder go to the folder. Activate virtual environment using pipenv shell pipenv install django (... and other dependencies) while virtual environment mode is enabled, I do: django-admin startproject projectname When I do above. I get an error as shown. I try again, same problem. I am a newbie, so a detailed explanation would be greatly appreciated! below is the manage.py, where the source of error is coming from: #!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main(): """Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'testapp.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': main() -
PGADMIN4 with DJANGO on google cloud 404 error
ok I can see the files. I can use the database. Apparently its running: (myprojectenv) michael@contra:~/myproject$ sudo systemctl status postgresql ● postgresql.service - PostgreSQL RDBMS Loaded: loaded (/lib/systemd/system/postgresql.service; enabled; vendor preset: enabled) Active: active (exited) since Sun 2022-01-16 23:51:55 UTC; 2 days ago Main PID: 22981 (code=exited, status=0/SUCCESS) Tasks: 0 (limit: 613) Memory: 0B CGroup: /system.slice/postgresql.service However, when I go to contra.nz/pgadmin4 Django takes over and is looking for a page. How do I access PGADMIN4 without uninstalling DJANGO :( -
How can I use a url parameter(that is a user id <str:pk>) to prepopulate a field in DJANGO form
I'm doing a management application with 2 pages: users(clientes) and a user datail page that contains a user payment history(cheques). I'm trying to do a create a form in payment history page(cheques.html) to add a new payment, but I'd the Cheque.cliente would be equals to the current user URL. Ex.: if your URL is cheque/5/, the Cheque.cliente should be 5, and when I add a new payment, the payment should be tracked(ForeignKey) to the user 5(each user has many payments). Resuming: This application has the functions to CRUD all the user(clientes) and all the payments(cheques), but only the add payment(cheque) function isn't working. VIEWS.py #CLIENTES def index(request): clientes = Cliente.objects.all() form = ClienteForm() if request.method == 'POST': form = ClienteForm(request.POST) if form.is_valid(): form.save() return redirect('/') context = {'clientes':clientes, 'form':form} return render(request, 'clientes/home.html', context) #CHEQUES #THE ERROR IS IN THIS VIEW! def chequesCliente(request, pk): cheques = Cheque.objects.filter(id=pk) nome = Cliente.objects.get(id=pk) formc = ChequeForm() if request.method == 'POST': formc = ChequeForm(request.POST) print(formc.data['cliente']) if formc.is_valid(): print(formc.cleaned_data) formc.save() return redirect('/') context = {'cheques':cheques, 'formc':formc, 'nome':nome,} return render(request, 'clientes/cheques.html', context) def updateCheque(request, pk): cheque = Cheque.objects.get(id=pk) formc = ChequeForm(instance=cheque) if request.method == 'POST': formc = ChequeForm(request.POST, instance=cheque) if formc.is_valid(): formc.save() return redirect('/') context = {'formc':formc} … -
Django Password Reset Email sending incorrect link
I am using the auth_views login and password reset system for the accounts app in a Django project. The password reset functionality works fine on the localhost. However once deployed when trying to reset the password the email that is sent to the user's registered email account contains the incorrect reset URL. The domain part of the reset URL contains the localhost address and not the domain of the site. The email is sent to a link like http://127.0.0.1:8000/accounts/reset/MTk/azifmz-484db716de96c7628427b41e587c1910/[![enter image description here]1]1 What I am expecting is for the sent email to contain the correct return URL specific to the domain that is sending it. e.g https://www.example.com/accounts/reset/MTk/azifmz-484db716de96c7628427b41e587c1910. In settings.py LOGIN_REDIRECT_URL = '/' LOGOUT_REDIRECT_URL = 'index' STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] SOCIALACCOUNT_PROVIDERS = { 'google': { 'SCOPE': [ 'profile', 'email', ], 'AUTH_PARAMS': { 'access_type': 'online', } } } EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend" EMAIL_HOST= 'smtp.gmail.com' EMAIL_HOST_USER= 'myemail@gmail.com' EMAIL_HOST_PASSWORD= 'mypassword' EMAIL_USE_TLS= True EMAIL_PORT= 587 In my accounts urls.py I am using the default classed bassed views provided by django.contrib.auth. There are no custom views for the reset workflow. I am hoping to configure this workflow to avoid having to write custom views for now. urls.py path('password_reset/', auth_views.PasswordResetView.as_view( template_name="accounts/password_reset_form.html", success_url="done/"), name="password_reset"), path('password_reset/done/', auth_views.PasswordResetDoneView.as_view( … -
Django-Admin Reload Inline based on parent Field
I have simple scenario with a Account class and a AccountDetail class. The AccountDetail is a inline: class AccountDetailInLine(admin.TabularInline): model = AccountDetail @admin.register(Account ) class Account Admin(admin.ModelAdmin): inlines = [AccountDetailInLine] The problem is that I can't have multiples records for the same account on same date. So when the user is adding a new Account, if he chooses a previously created Account and date, the inline should reload the table with elements he created before to continue filling the records. Sorry if it's not clear. How could I do this? The flow is: User adds a new Account with name and date and the details in Inline User Saves User go to Add again and choose a date that was previously saved The tool should fill the Inline with the previously added to this date so he can to continue filling the data. <---- Here's my doubt -
How can I save a django form
So I want to save a Biographie for each new created User. The user can enter his Bio and it will the it to his Profile. For this I created a model with OneToOneField from django.db import models 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, null=True, blank=True) bio = models.CharField(max_length=30) To create the form I did the following in forms.py: class BioForm(forms.ModelForm): class Meta: model = Profile fields = ('bio',) Then I created in the views.py the saving, so the bio will be saved to the specific user: from .forms import LoginForm, RegisterForm from django.shortcuts import render, redirect from django.contrib.auth import authenticate, login, logout, get_user_model from django.contrib.auth import get_user_model def test_view(request): form = BioForm(request.POST) user = get_user_model if form.is_valid(): profile = form.save(commit=False) profile.user = request.user profile.phone_number = request.phone_number profile.save() return render(request, 'test.html', {'form': form}) There is something big wrong in the views.py but I don't get it. I can submit the form and the form will be saved (sometimes) but without the user who wrote it + I get this error: ValueError at /test/ Cannot assign "<SimpleLazyObject: <django.contrib.auth.models.AnonymousUser object at 0x00000253B7140D00>>": "Profile.user" must be a "User" instance -
django2 vs django3 how to write path instead of url
so I'm trying to type this in django3 with path url(r'^tag/(?P<slug>[-\w]+)/$', TagIndexView.as_view(), name='tagged') I tried tag/slug but I guess it didn't work. -
Hosting platforms for python django api with docker
What is the best platform to host a python django api with a react front end and also have a docker setup that runs jobs in the background which populates my data -
Solutions for tracking time user spent on a context
I working on case management system. We have operation staffs working on filling out/processing data for a case. The system is built using React on frontend and Django on backend. The URL for a single case is like this pattern: /case//< action name> I'm looking for a solution (open source or commercial) to track user activities and eventually calculate how much time a user spends on a case, e.g: how much time in total operation staffs spend on a specific case, and how much time on average operation staffs spend on a single case, etc. Right now I'm looking into Real User Monitoring(RUM) solutions like Datadog RUM. The data structure can be used to achieve what I want but the challenge is there is no way to extract those raw data or stream it to another database to do further calculations. Am I going in the right direction? Really appreciate any suggestion. -
What's the pros and cons of having a model for each Product Attribute?
I have a two generic models in my app: ProductAttributes and ProductAttributesValue (besides Product and ProductCategory, which are not relevant for this discussion). These two models contain respectively all the different attributes and their values. For example, "brand" as an Attribute, and "nike" and "addidas" as its Attribute Values. I'm running into an issue with this setup, though, as I want to create a page for each brand. I think this would be easier, if brands did not share model with other attributes, like color, size etc., which I do not want to create unique pages for. There may also be other scenarios. In general, what's the pros and cons of having a unique model for each Product Attribute, versus having a shared model? Note: I want to still be able to have long URLs that contain one category and several attribute values, like domain.com/shoes/red/nike -
CSS not work without ".min.css" as the name format
I'm currently using bootstrap on django but somehow one of the CSS below does not work this doesn't work: https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.css this works!! https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css I ensure them they have the same version of bootstrap. This is my static file code on my base template html: <!-- THIS DOES NOT WORK --> {% load static %} <link rel="stylesheet" href="{% static 'css/bootstrap.css' %}"> <!-- THIS WORKS --> {% load static %} <link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}"> my static dirs contains both of the file. does anyone know why the .min.css works? or any other possible causes on why the .css file does not work? I want to use the .css not the min. -
django-oauth-toolkit : Test Custom TokenView
I am trying to write a unit test for a custom implementation of the django-oauth-toolkit TokenView The reason for inheriting from the TokenView is to require a 2FA token before generating the access token. Below is what the view looks like class CustomTokenView(TokenView): @method_decorator(sensitive_post_parameters("password")) def post(self, request, *args, **kwargs): meta = request.META grant_type = urllib.parse.parse_qs(request.body.decode("utf-8")).get("grant_type")[0] if grant_type == "password": """ Users trying to log in with email and password. """ try: email = urllib.parse.parse_qs(request.body.decode("utf-8"))["username"][0] except KeyError: return JsonResponse(data={"message": "Email is required", "status": "0"}, status=400) try: token = urllib.parse.parse_qs(request.body.decode("utf-8"))["token"][0] except KeyError: return JsonResponse(data={"message": "Token is required", "status": "0"}, status=400) email = simplefunctions.remove_unicode(email) user_obj = CustomUser.objects.filter( email=email, is_active=True, is_staff=True, is_account_disabled=False).first() if user_obj is None: return JsonResponse(data={"message": "Invalid Email", "status": "0"}, status=400) else: application_log.debug(f"User {user_obj.email} tried to login with password. Request header data {meta}") if token: if not services.UserService.is_valid_2fa_token(user_obj, token): return JsonResponse(data={"message": "Invalid Token", "status": "0"}, status=400) return super().post(request, *args, **kwargs) return JsonResponse(data={"message": "Invalid grant type", "status": "0"}, status=400) I can extract each request data and perform validation on them but returns an error when the return super().post(request, *args, **kwargs) is called. What my test looks like from oauth2_provider.settings import oauth2_settings from oauth2_provider.models import get_access_token_model, get_application_model from django.contrib.auth import get_user_model from django.utils import … -
Django - Select don't save form
I have a form with categories (MultipleChoiceField), but I need "select categories". I'm having trouble with widget categories. When I remove the "categories" widget (from the code below), save the form without a problem. But when I use this widget form don't save. I tried a lot of combinations. choices = Category.objects.all().values_list('name', 'name') class ZeroForm(forms.ModelForm): class Meta: model = IdeaPage fields = ['title','categories'] widgets = { 'categories': forms.Select(choices=choices, attrs={'class': 'form-control'}), } -
how to fix memory leak issue ''Possible EventEmitter memory leak detected''?
I am working on React App, when I run it on localhost it takes significate time to load the homepage, and even with I just refresh the page( takes about 5 seconds to load) and some time is not from the first refresh, I have got this warning lately, I am familier with the term the memory leak theoretically, but not in-depth when come to debug it. and I am running Django server on the backend if this helps! (node:18208) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 _cacheReadyToWrite listeners added to [Browserify]. Use emitter.setMaxListeners() to increase limit -
How to automatically index new data in elasticsearch and django
as the title describes I am using django and elasticsearch and currently everytime I want to index new data I run the command python manage.py search_index --populate I want to index new data automatically anyone has a clue how can I do this? -
What's causing the tuple and get error in the django?
I am learning from the book Django3 by example. I am having a problem and I am unable to debug it. I am unable to understand what does this mean? I am displaying list of posts on a page. This error happens when I click the particular post to view whole of the blog post. Here is my error: - Traceback (most recent call last): File "/mnt/g/Programming/django/blog/my_env/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/mnt/g/Programming/django/blog/my_env/lib/python3.8/site-packages/django/utils/deprecation.py", line 96, in __call__ response = self.process_response(request, response) File "/mnt/g/Programming/django/blog/my_env/lib/python3.8/site-packages/django/middleware/clickjacking.py", line 26, in process_response if response.get('X-Frame-Options') is not None: Exception Type: AttributeError at /blog/2022/1/19/what-is-model/ Exception Value: 'tuple' object has no attribute 'get' my views.py from django.shortcuts import render, get_object_or_404 from .models import Post # Create your views here. def post_lists(request): posts = Post.published.all() return render(request, 'blog/post/list.html', { 'posts': posts}) def post_detail(request, year, month, day, post): post = get_object_or_404(Post, slug = post, status='published', publish__year=year, publish__month=month, publish__day=day) return(request, 'blog/post/detail.html', {'post': post}) My models.py from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse # Create your models here. class PublishedManager(models.Manager): def get_queryset(self): return super(PublishedManager, self).get_queryset().filter(status='published') class Post(models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published') ) title = models.CharField(max_length=250) slug = … -
I can't create a django project
I typed django-admin startproject myproject in command pallet and it gave me this error message: 'django-admin' is not recognized as an internal or external command, operable program or batch file. I would realy appreciate some explination or tips. Thank you! -
is there any way to save child model class with pandas in save method of parent model class while saving parent model class in django
i want to save an excel file to a model class and its detail into another one by pandas without using pandas to do it in view engine = create_engine('sqlite:///db.sqlite3') class Excel(models.Model): name = models.CharField(max_length=150, unique=True) excel = models.FileField(upload_to=set_name_and_folder_file) class ExcelDetail(models.Model): title = models.CharField(max_length=100) extract_excel = models.ForeignKey(ExtractExcel, on_delete=models.CASCADE, default=None) @receiver(post_save, sender=ExtractExcel) def my_save_handler(sender, **kwargs): instance = kwargs['instance'] if instance.id is None: id__max = ExtractExcel.objects.aggregate(models.Max('id'))['id__max'] if id__max is None: id__max = 0 instance.id = id__max + 1 df = pd.read_excel( rf'{instance.excel.path}') count_col = df.shape[0] df['extract_excel_id'] = [instance.id for i in range(count_col)] #above: to add a column named extract_excel_id to df for Foreign Key df.to_sql(ExcelDetail._meta.db_table, con=engine, index=true) when i save the Excel file to Excel model by admin, the error is shown that is like following error: (sqlite3.OperationalError) database is locked [SQL: INSERT INTO extract_excel_file_exceldetail (title, extract_excel_id) VALUES (?, ?)] [parameters: ((1, 9), ('title2', 9), (4, 9), ('title4', 9), ('w', 9), ('w', 9), ('amir', 9), (12, 9))] (Background on this error at: https://sqlalche.me/e/14/e3q8) it says 'database is locked' i think that a conflict is made up in database connection that is between django and engine above. what should i do? -
Django: How to save a OneToOneField
I have code that should assign a "bio" to each user. Until now, every time a user is created, a UserProfile is also created, where "Bio", "Birthday"... are in it. models.py from django.db import models 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) bio = models.TextField(max_length=500, blank=True) phone_number = models.CharField(max_length=12, blank=True) birth_date = models.DateField(null=True, blank=True) @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() forms.py from django import forms from django.contrib.auth import get_user_model from .models import Profile non_allowed_usernames = ['abc'] User = get_user_model() class RegisterForm(forms.Form): username = forms.CharField() email = forms.EmailField() password1 = forms.CharField( label='Password', widget=forms.PasswordInput( attrs={ "class": "form-control", "id": "user-password" } ) ) password2 = forms.CharField( label='Confirm Password', widget=forms.PasswordInput( attrs={ "class": "form-control", "id": "user-confirm-password" } ) ) def clean_username(self): username = self.cleaned_data.get("username") qs = User.objects.filter(username__iexact=username) if username in non_allowed_usernames: raise forms.ValidationError( "This is an invalid username, please pick another.") if qs.exists(): raise forms.ValidationError( "This is an invalid username, please pick another.") return username def clean_email(self): email = self.cleaned_data.get("email") qs = User.objects.filter(email__iexact=email) if qs.exists(): raise forms.ValidationError("This email is already in use.") return email class LoginForm(forms.Form): username = forms.CharField(widget=forms.TextInput( attrs={ "class": "form-control" })) … -
Django server does not start, the site does not work when starting dockerfile
I'm training in the dockerfile assembly, I can't understand why it doesn't work. Python django project GitHub: [https://github.com/BrianRuizy/covid19-dashboard][1] At the moment I have such a dockerfile, who knows how to create docker files, help me figure it out and tell me what my mistake is. FROM python:3.8-slim RUN apt-get update && \ apt-get install -y --no-install-recommends build-essential ENV PYTHONUNBUFFERED=1 ADD requirements.txt / RUN pip install -r /requirements.txt EXPOSE 8000 CMD ["python", "manage.py", "runserver", "127.0.0.1:8000"]