Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
can anyone help me to figure out how to embed terminal to webpage so that I can take user input for programs written in webpage
I am working on online coding platform. As of now I am using subprocess module of python to run the program of other language and it's successfully also showing the output and as well as taking input from the code editor terminal of vs code . Basically it's interacting with the developmental code editor. but I need to make it interactive with web user i.e. when user write a code in web platform and click run then user should be able to enter the input from web platform. So, please can anyone help to figure out how to do that? -
I want to pass productid in my url so as to display details of only a specific product
this is how my django code looks like <a href="{% url 'product-details' product.id %}">Details</a> this is how my urls look like path('product/<int:id>/, views.product-details, name='product-details') after clicking on the link am getting this error noReverseMatch at /products/ what could be the problem with my code -
Heroku doesn't migrate models in Django
I have a Django app deployed on Heroku. I am trying to switch the database from mySQL to Postgres using the Heroku Postgres addon I erased all migrations and ran manage.py makemigrations to get a clean migration log. Then I commit and push. If I run manage.py migrate on my local machine, this is what I get: Migrations for 'manager': manager/migrations/0001_initial.py - Create model AbiMapping - Create model MissingContracts - Create model TempEmailAccounts - Create model UnsupportedMetaContracts - Create model Users - Create model Passwords - Create model ContractMapping - Create model Tokens I added this command to Procfile so migrate runs when I push to Heroku: release: python3 manage.py migrate When pushing to Heroku, the migrate call works but it doesn't migrate the models I have in the app: remote: Verifying deploy... done. remote: Running release command... remote: remote: Operations to perform: remote: Apply all migrations: admin, auth, contenttypes, manager, sessions remote: Running migrations: remote: No migrations to apply. This is how I setup the database is settings.py: .env sets environment variables on local machine. On heroku database environment variables are loaded from environment as there is not .env dotenv_file = os.path.join(BASE_DIR, ".env") if os.path.isfile(dotenv_file): dotenv.load_dotenv(dotenv_file) Setup database: DATABASES … -
How to perform live application update in Django server, without full shutdown?
Django has a very clear methodology how to update version of application code in the server(I.e deploy version): Make sure it works locally. Make migrations(could be additionally before 1) Shut down the server. Push code to the server. Migrate DB changes. Start the server again. But the big trouble is how to do this action without shutting down the server, so it will be still available to the users, even during update. Pinterest and Instantgram are both using Django, but you never saw them unavailable. What is the recommended or even a possible methodology? -
MultiValueDictKeyError 'name'
I have few apps in my project and now Im stuck with following problem, when Im filling up all fields and pressing "submit" then following error is showing: MultiValueDictKeyError at / 'name' Request Method: POST Request URL: http://127.0.0.1:8000/ Django Version: 3.1.2 Exception Type: MultiValueDictKeyError Exception Value: 'name' Views form main directory(which is colliding name = request.POST['name']): def home(request): if request.method == 'POST': name = request.POST['name'] email = request.POST['email'] subject = request.POST['subject'] message = request.POST['message'] send_mail( 'message from' +' '+ name +' '+ email, message, email, ['blablablabla@gmail.com'], fail_silently=False, ) return render(request, 'wwwapp/home.html', {'name': name}) else: return render(request, 'wwwapp/home.html') I think with this views: def become_vendor(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): user = form.save() login(request, user) vendor = Vendor.objects.create(name=user.username, created_by=user) return redirect('frontpage') else: form = UserCreationForm() return render(request, 'vendor/become_vendor.html', {'form': form}) @login_required(login_url='loggin') def vendor_admin(request): vendor = request.user.vendor product = vendor.products.all() return render(request, 'vendor/vendor_admin.html', {'vendor': vendor, 'product': product}) @login_required def add_product(request): if request.method == 'POST': form = ProductForm(request.POST, request.FILES) if form.is_valid(): product = form.save(commit=False) product.vendor = request.user.vendor product.slug = slugify(product.title) product.save() return redirect('vendor_admin') else: form = ProductForm() return render(request, 'vendor/add_product.html', {'form': form}) Forms for this Model: from django.forms import ModelForm from product.models import Product class ProductForm(ModelForm): class Meta: model … -
Display info from django database in a Map
j query vector map of Nigeria Good morning, please can i be given a tutorial on how to display information from my data base in a map? Its a django project. I want to for each state show its corresponding information in a tooltip format. -
I have the following problem when using autocomplete_fields field under django3.2
The following problems will occur!!! enter image description here When I use the version below django3.2, everything is normal. I don't know if this is my problem? And django will prompt the following error: During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\admin\.virtualenvs\easyshow\lib\site-packages\django\contrib\admin\views\autocomplete.py", line 61, in process_request app_label = request.GET['app_label'] File "C:\Users\admin\.virtualenvs\easyshow\lib\site-packages\django\utils\datastructures.py", line 78, in __getitem__ raise MultiValueDictKeyError(key) django.utils.datastructures.MultiValueDictKeyError: 'app_label' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\admin\.virtualenvs\easyshow\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\admin\.virtualenvs\easyshow\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\admin\.virtualenvs\easyshow\lib\site-packages\django\contrib\admin\sites.py", line 250, in wrapper return self.admin_view(view, cacheable)(*args, **kwargs) File "C:\Users\admin\.virtualenvs\easyshow\lib\site-packages\django\utils\decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "C:\Users\admin\.virtualenvs\easyshow\lib\site-packages\django\views\decorators\cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "C:\Users\admin\.virtualenvs\easyshow\lib\site-packages\django\contrib\admin\sites.py", line 232, in inner return view(request, *args, **kwargs) File "C:\Users\admin\.virtualenvs\easyshow\lib\site-packages\django\contrib\admin\sites.py", line 417, in autocomplete_view return AutocompleteJsonView.as_view(admin_site=self)(request) File "C:\Users\admin\.virtualenvs\easyshow\lib\site-packages\django\views\generic\base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\admin\.virtualenvs\easyshow\lib\site-packages\django\views\generic\base.py", line 98, in dispatch return handler(request, *args, **kwargs) File "C:\Users\admin\.virtualenvs\easyshow\lib\site-packages\django\contrib\admin\views\autocomplete.py", line 20, in get self.term, self.model_admin, self.source_field, to_field_name = self.process_request(request) File "C:\Users\admin\.virtualenvs\easyshow\lib\site-packages\django\contrib\admin\views\autocomplete.py", line 65, in process_request raise PermissionDenied from e django.core.exceptions.PermissionDenied -
How to run view.py file in Django in order to scrape and store data
I want to open and run a django project in pycharm. The project is about scrape data from another website by using beautifulsoup and selenium and store data to django database and show them in our own website. In order to launch scraping process when I run view.py file, I encounter the following error. File "C:\Users\XXXX\XXXXX\lib\site-packages\django\conf_init_.py", line 63, in _setup raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. Can you please help me to figure out the issue. I struggled too much to solve the problem but could not solve that. I need to accomplish my task in a very limited time. I would be very grateful if anyone pioneer me to solve the issue -
Django doesn't show field
So, I'm new to django and I am learning I created a form but django doesn't show it in the page I am using python 3.9.4 django 3.2 this is my code models.py from django.db import models # Create your models here. class Commande(models.Model): name = models.CharField(max_length=300) forms.py from django import forms from .models import Commande class home_form(forms.ModelForm): class Meta: model = Commande fields = ['name'] class RawCmdForm(forms.Form): name = forms.CharField() views.py from .models import Commande from django.shortcuts import render from .forms import home_form, RawCmdForm # Create your views here. def home_view(request): medocs = Commande.objects.all() #print(medocs) context = {'medoc' : medocs} return render(request, "index.html", context) def cmd_Form_view(request): my_form = RawCmdForm() if request.method == "POST": my_form = RawCmdForm(request.POST) if my_form.is_valid(): print("Good Data") Commande.objects.create(**my_form.cleaned_data) my_form = RawCmdForm() #if request.method == "POST": # new_name= request.POST.get("name") # Medoc.objects.create(name = new_name) context = {"form" : my_form} return render(request, "index.html", context) index.html <!DOCTYPE html> <html> <head> <title>My Commande</title> </head> <body> <h1 style="color: red"> Mes Manqants</h1> {% for instance in medoc %} <input type="checkbox" id= {{instance.id}} name= {{instance.name}} value= {{instance.name}} > <label for= {{medoc.id}} > {{instance.name}} </label><br> {% endfor %} </body> </html> formadd.html {% extends "index.html" %} {% block content %} {{ form }} {% endblock %} … -
how to provide django key using .env file using Circle CI
I want to test my Django project in Circle CI. I came across few ways to set up .config file to do this but none of them mentioned how to set up for a django project using .env file to read keys I want a solution which doesn't require me to change my django project way of reading keys public .env file in my repo IDEAL SOLUTION I'M LOOKING FOR allows me to add keys via project key setup but doesn't require me to remove this line from my settings .py SECRET_KEY = env.str('SECRET_KEY') -
passing a list from jquery to a view function in django
Suppose I have the following function in my django project. getValues2() returns a list with numbers. How can I pass this numbers to my view using window.location? <script> let getValues2 = () => $("input[name='checkb']:checked").map((i,el) => el.id.trim()).get(); console.log('getValues2 ',getValues2()) window.location('eprint/checked' + getValues?() </script> views.py def eprint(request): print('eprint') # how to get the list from jquery? print(checked) -
Django - Error during template rendering for crispy forms with dynamic fields : 'int' object has no attribute 'get'
I have been trying to implement dynamic forms with a given number of fields and rendering these with crispy forms. However, the following errors are coming when rendering the page: Template error: In template C:\Users\USER14\Documents\testprep\lib\site-packages\crispy_forms\templates\bootstrap4\errors.html, error at line 1 'int' object has no attribute 'get' 1 : {% if form.non_field_errors %} 2 : <div class="alert alert-block alert-danger"> 3 : {% if form_error_title %}<h4 class="alert-heading">{{ form_error_title }}</h4>{% endif %} 4 : <ul class="m-0"> 5 : {{ form.non_field_errors|unordered_list }} 6 : </ul> 7 : </div> 8 : {% endif %} 9 : Traceback (most recent call last): File "C:\Users\USER14\Documents\testprep\lib\site-packages\django\forms\forms.py", line 304, in non_field_errors return self.errors.get(NON_FIELD_ERRORS, self.error_class(error_class='nonfield')) File "C:\Users\USER14\Documents\testprep\lib\site-packages\django\forms\forms.py", line 170, in errors self.full_clean() File "C:\Users\USER14\Documents\testprep\lib\site-packages\django\forms\forms.py", line 372, in full_clean self._clean_fields() File "C:\Users\USER14\Documents\testprep\lib\site-packages\django\forms\forms.py", line 384, in _clean_fields value = field.widget.value_from_datadict(self.data, self.files, self.add_prefix(name)) File "C:\Users\USER14\Documents\testprep\lib\site-packages\django\forms\widgets.py", line 657, in value_from_datadict getter = data.get Exception Type: AttributeError at /upload/1/SingleCorrect/10/ Exception Value: 'int' object has no attribute 'get' What exactly prompts this error? Following are the code snippets I am using. views.py: def uploadQP(request,qp,typeofq,numberOfquestion): if request.method == 'POST': form=CreateForm(repetitions=numberOfquestion,data=request.POST,files=request.FILES) if form.is_valid(): if typeofq=='SingleCorrect': for i in range(numberOfquestion): files=SingleIntegerType() files.QuestionPaper=get_object_or_404(QuestionPaper,pk=qp) files.question=request.FILES['question_%d' % i] files.correct_answer=request.POST['correct_answer_%d' % i] files.QuestionNumber=request.POST['question_number_%d' % i] files.save() return redirect('create_q') elif request.method=='GET': form=CreateForm(numberOfquestion) return render(request, 'upload_q.html',{'form':form}) … -
Django Modelform ForeignKey Listing Problem
I have a staff list. I have a model for this as follows. models.py: class NumberOfMealsEaten(models.Model): month = models.ForeignKey(Months, on_delete=models.CASCADE) staff = models.ForeignKey(Staffs, on_delete=models.CASCADE) maelseaten = models.IntegerField("Number of meals eaten", validators=[MinValueValidator(0)], default=0) def __str__(self): return str(self.staff) For these employees, the meal fee is calculated every month according to how many meals each staff has eaten. First, at the beginning, I want to choose "the name of the relevant month" only once. Then I want the staff names from Foreignkey to be automatically listed as "text" in the template, not in the form of a drop-down menu. So I just want the "maelseaten" field filled in for the staff. As an example, the list will look like this: enter image description here In other words, this form will add the number of meals for each staff member for the selected month to the database. Thank you in advance for your attention and help. -
Increment number until it matches another number
I am trying to write an algorithm that will increase portion size until the total_cals are as close to the specified argument calories as possible. Here is my model: class Foods(models.Model): name = models.CharField(max_length=100) calories = models.IntegerField() protein = models.FloatField() carbs = models.FloatField() fat = models.FloatField() sugar = models.FloatField(null=True) fiber = models.FloatField(null=True) amount_in_grams = models.IntegerField(default=100) portion_size_in_grams = models.IntegerField() Here is the function I have: def mealPlanMaker(calories): total_cals = 0 meal = [Foods.objects.get(name='Rice'), Foods.objects.get(name='Broccoli'), Foods.objects.get(name='Chicken') while calories > total_cals: for i in meal: portion_size = i.portion_size_in_grams + 1 total_cals += i.calories * portion_size / 100 meal_dict[i.name] = portion_size meals.append(meal_dict) So what I want to do is increase the portion size until the total_cals is as close as possible to calories, say within a range of 50. But my function doesn't work. -
Django access grandchild instances from grandparent
I have the following models class City(models.Model): name = models.CharField() class Surburb(models.Model): name = models.CharField() city = models.ForeignKey( 'City', related_name='surburbs') class ShoppingMall(models.Model): name = models.CharField() location = models.ForeignKey( 'Location', related_name='shoppingmalls') class Store(model.Model): shoppingmall = models.ForeignKey( 'ShoppingMall', related_name='stores') storetype = models.ForeignKey( 'Storetype', related_name='stores') class Storetype(models.Model): title = models.CharField() #View def index(request): cities = City.objects.all().prefetch_related( 'locations__shoppingmalls__stores') return render(request, 'index.html', {'cities':cities}) #Template {% for city in cities %} {% ifchanged %} <li><a href="#">{{ city }}</a> <ul class="sub-menu"> {% with locations=city.locations.all|dictsort:'name' %} {% for location in locations %} {% ifchanged %} <li><a href="#">{{ surburb.name }} </a> <ul class="sub-menu"> {% with shoppingmalls=surburb.shoppingmalls.all|dictsort:'name' %} {% for shoppingmall in shoppingmalls %} {% ifchanged %} {% with stores=shoppingmall.stores.all|dictsort:'name' %} {% for store in stores %} <li> {% ifchanged %} {{ store.storetype.title }} {% endifchanged %} </li> {% endfor %} {% endwith %} {% endifchanged %} {% endfor %} {% endwith %} </ul> </li> {% endifchanged %} {% endif %} {% endfor %} {% endwith %} </ul> <span class="arrow-main-menu-m"> <i class="fa fa-angle-right" aria-hidden="true"></i> </span> </li> {% endifchanged %} {% endfor %} I have tried many things to get the storetype not to display duplicate storetypes without success. This is because each mall can have the same storetypes from another … -
Django: update not saving date without raising error
I have a view in my Django app where I want to update a queryset´s DateField. It´s quite simple, the field works fine in other views (not a model problem) and it doesn´t raise any error when running the view. The other elements in the view are stored ok. The view @transaction.atomic @login_required def BocetoArmando(request): operaciones = OperacionK.objects.filter(creador__username='this_user', estatus__id=1) operaciones.update( fecha_conf_comercial=date.today(), fecha_conf_admin=date.today(), confirmador_admin=request.user, estatus=EstatusOperacionK.objects.get(estatus__icontains="Armando")) lista = [x.id for x in operaciones] pedidos = PedidosK.objects.filter(comprobante__in=lista) pedidos.update(fecha_conf_comercial=datetime.datetime.today()) for pedido in pedidos: producto = ProductosBase.objects.get(pk=pedido.producto.id) producto.existencias = producto.existencias - pedido.uds producto.existencias_bloqueada = producto.existencias_bloqueada - pedido.uds producto.save(update_fields={'existencias', 'existencias_bloqueada'}) return DispatchManager(request) I tried both options with the same result: pedidos.update(fecha_conf_comercial=datetime.datetime.today()) pedidos.update(fecha_conf_comercial=date.today()) If I run pedidos.update(fecha_conf_comercial=date.today()) in Django´s shell it´s updated correctly. This is part of a big app that handles this datefield without any problems in the rest of the views. I can´t figure out what is happening here. Any clues welcome. Thanks in advance! -
How to have django-admin recognized in Eclipse/LiClipse?
I've been trying to execute django-admin from within a LiClipse project using: projectName = "someProject" command = 'django-admin startproject ' + projectName process = subprocess.Popen(command.split(), stdout=subprocess.PIPE) and also subprocess.check_call(shlex.split(command)) But each time I get the error: FileNotFoundError: [Errno 2] No such file or directory: 'django-admin' However, when I run the same program from the Linux terminal using python3 main.py, it works fine. So I figured it might be because django-admin's path isn't added to PYTHONPATH. I did a locate "django-admin" to find these paths: /home/nav/.pyenv/shims/django-admin /home/nav/.pyenv/shims/django-admin.py /home/nav/.pyenv/versions/3.8.7/bin/django-admin /home/nav/.pyenv/versions/3.8.7/bin/django-admin.py /home/nav/.pyenv/versions/3.8.7/bin/__pycache__/django-admin.cpython-38.pyc /home/nav/.pyenv/versions/3.8.7/lib/python3.8/site-packages/django/bin/django-admin.py /home/nav/.pyenv/versions/3.8.7/lib/python3.8/site-packages/django/bin/__pycache__/django-admin.cpython-38.pyc and added it to PYTHONPATH... ...but I get the same error when I run the program from within LiClipse. Does anyone know why this problem is happening and how it can be fixed? -
How to disconnect channel from group using custom key only?
Good day! I writing chat according on django-channels official guide. In my connection to the group, I have instance of my custom Django model named Player. How I can disconnect channel to chat group, if I know only pk of Player, which need to be banned? class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): self.player = await sync_to_async(Player.objects.get, thread_sensitive=True)(account=self.scope["user"]) self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name # Join room group await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() async def disconnect(self, close_code): # Leave room group await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) # Receive message from WebSocket async def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] # Send message to room group await self.channel_layer.group_send( self.room_group_name, { 'type': 'chat_message', 'id': self.player.pk, 'nickname': self.player.nickname, 'image': self.player.image.url, 'message': message } ) # Receive message from room group async def chat_message(self, event): message = event['message'] id = event['id'] nickname = event['nickname'] image = event['image'] # Send message to WebSocket await self.send(text_data=json.dumps({ 'message': message, 'time': datetime.now().time().strftime("%H:%M"), 'id': id, 'nickname': nickname, 'image': image, })) -
no such table: django_session On azure web app
Im trying to deploy a django app through azure web app service, Im choosing Postgress db for the deployment, However i have prepared my settings for the pg db, like so DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME':'..' , 'USER': '...', 'PASSWORD': '..', 'HOST': '....', 'PORT':'...', } } I have deleted all the migrations/__pycache__ files, db.sqlite3 And then I did manage.py makemigrations AppName followed by manage.py migrate AppName , The migrations are done, and i can see all the tables created to the PgAdmin. But there is weird stuff going, every time i delete db.sqlite3, its created again after i finish migrate even with the settings where there is no sqlite3 mentioned. I tried to find a solution for this issue but seems im out of tricks. any help would be so appreciated. -
how to use get_context_data in django ListView(three class model)
I have three class models. A contains the Academy's class name, B contains the student name, and refers to A (class name) as an foreign value. C contains the date the student enrolled in the academy and refers to B (student) as an outpatient value. Set Academy as the object of get_context_data and return the for statement to output the entire class anem of academy in the first field of the table. This is a problem that I am not solving from here. I would like to output the number of students who satisfy a specific condition for each class name. <table> {% for academy in academies %} <tr class="text-center"> <td>{{ academy.academy_class_name }}</td> <td>{{ i want to count }}</td> ----- problem </tr> {% endfor %} </table> class ListView(ListView): model = Academy context_object_name = 'academies' template_name = 'list.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['to_date'] = self.request.GET.get('to_date') context['from_date'] = self.request.GET.get('from_date') context['option_radio'] = self.request.GET.get('optionRadios') if context['option_radio'] == 'period': context['student'] = Student.objects.filter(academy_id=self.id) ----- I want to load the class name of each academy being returned by the for statement. context['screening'] = Attribute.objects.filter( entry_date__lte=context['to_date'], entry_date__gte=context['from_date'], student_id__in=context['student'] ).count() return context -
load multuple dummy data dinago for windows
I have this script python manage.py loaddata ./project_apps/*/fixtures/test/*.json It works perfectly on linux. This scrip says 'take all dirs from /project_apps, in every dirs, if there is fixtures folder take it and than search for /test dir, if there is take it and grab all files there which have .json extension'. That is fine, but when i run the same command on windows python manage.py loaddata .\project_apps\*\fixtures\test\*.json it throws me an error: there is no fixtures with that '*' name If i pass the absolute path to the file which a want. It is ok. The windows finds it. So is there an analogous command for windows, to can grab all files i want at once. -
import Django Conventional structure
hello, im new with django, how can I create standard structure of django in Pycharm as I create new django project in python there is no such a file like apps.py or models.py please help me how can I import all those standard files to project (sorry if it is stupid question) -
Django costume save form cant save in user id field
please someone help me i have form costum save to crop and save but cannt crop and also cannt save in user field in db its all in edit profile to edit profile name and photo its separate model for profile picture bcs i dont know how to save with name and profile info thanks so much NOT NULL constraint failed: authy_photo.user_id models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile') name = models.CharField(max_length=50, null=True, blank=True , default='') profile_info = models.TextField(max_length=150, null=True, blank=True, default='') created = models.DateField(auto_now_add=True) favorites = models.ManyToManyField(Post) def __str__(self): return self.user.username class Photo(models.Model): picture = models.ImageField(upload_to=user_directory_path,blank=True, null=True, verbose_name='photos') uploaded_at = models.DateTimeField(auto_now=True) user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='photo') class Meta: verbose_name = 'photo' verbose_name_plural = 'photos' forms.py class PhotoForm(forms.ModelForm): x = forms.FloatField(widget=forms.HiddenInput()) y = forms.FloatField(widget=forms.HiddenInput()) width = forms.FloatField(widget=forms.HiddenInput()) height = forms.FloatField(widget=forms.HiddenInput()) class Meta: model = Photo fields = ('picture', 'x', 'y', 'width', 'height',) def save(self, *args, **kwargs): photo = super(PhotoForm,self).save() self.instance.user_id = user x = self.cleaned_data.get('x') y = self.cleaned_data.get('y') w = self.cleaned_data.get('width') h = self.cleaned_data.get('height') image = Image.open(photo.picture) cropped_image = image.crop((x, y, w+x, h+y)) resized_image = cropped_image.resize((200, 200), Image.ANTIALIAS) resized_image.save(photo.picture.path) return photo class EditProfileForm(forms.ModelForm): class Meta: model = Profile fields = ('name', 'profile_info') and one view views.py @login_required def EditProfile(request): … -
mannual authentication system in django
views.py i am trying to get user and check if it is verified then login otherwise submit otp and do verify. but i can't get user and on otp page i got error. please tell me how to do better this code def login(request,pk): if request.method == 'POST': get_otp = request.POST.get('otp') get_user = request.POST.get('useremail') print(get_user) if get_otp: usr = Customer.objects.get(email=get_user) if int(get_otp) == Customer.objects.filter(email=usr).last().otp: usr.is_active = True usr.is_verified = True usr.save() messages.success( request, 'Your account is successfully verified') return render(request, "index.html") else: messages.error(request, "Otp is wrong") return render(request, "authentication/register.html", {'otp':True , 'user':usr}) email = request.POST['em'] password = request.POST['ps'] user_id = Customer.objects.get(id=pk) user = Customer.objects.filter(email=email) print(user) if len(user) > 0: if user[0].is_verified and user[0].password == password: request.session['firstname'] = user[0].firstname request.session['lastname'] = user[0].lastname request.session['email'] = user[0].email request.session['phone'] = user[0].phone_no request.session['id'] = user[0].id return redirect('index') elif user[0].password != password: messages.error( request, 'Please enter correct password') return render(request, "authentication/login.html") elif not user[0].is_active: messages.info(request, "Please varify your account") user_otp = random.randint(100000, 999999) user[0].otp = user_otp user[0].save() subject = f"Welcome to DV creation" message = f"Hi {user[0].email} , Your OTP for varificaion is {user_otp} , (Note: OTP is only for 5 min)" email_from = settings.EMAIL_HOST_USER recipient_list = [user[0].email, ] send_mail(subject, message, email_from, recipient_list) return render(request, "authentication/register.html", … -
Trying to access existing mySql table with data but I get typeerror: not enough arguments for format string
I connected my database correctly in my settings.py. I created models via inspectdb for my already existing tables, I migrated them, but when I try to access them through the administration panel I get this error. What should I do? django: v3.2 python: v3.7.9 mySql: v8.0.19