Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I deal with rendering a selected template - getting a ,,Http request has no attribute'' meta error
def thanks(request): template = select_template(['poll/a.html', 'poll/b.html']) template.render({'a': 'b'}, HttpRequest) This is my code and it throws an error as above. I tried using return too. In documentaion it tells that it should be specifically HttpRequest, not request. Where is the problem? -
Remote Access to mysql from DigitalOcean Droplet
I have created my own server on Digital Ocean to upload the Django project to the Internet. But the problem is that I have a project-specific mysql database on phpmyadmin. The question is how can I link or upload this database to the server that I created so that the site can work normally? -
How i can get all these items in order page? There is no add to cart
I want to get all these items from this page. It was a customer order item where i select which items customer need. When all items are added than i want to click on check in button then it will rendered me into ordered page i can add customers information. It was an inventory management concept. -
DRF: router for ViewSet with a foreign-key lookup_field
Using Django REST Framework 3.12.4, I cannot properly get the URLs for a ViewSet to work if that ViewSet has a foreign-key lookup field. I have the following in models.py: class Domain(models.Model): name = models.CharField(max_length=191, unique=True) class Token(rest_framework.authtoken.models.Token): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) domain_policies = models.ManyToManyField(Domain, through='TokenDomainPolicy') class TokenDomainPolicy(models.Model): token = models.ForeignKey(Token, on_delete=models.CASCADE) domain = models.ForeignKey(Domain, on_delete=models.CASCADE) class Meta: constraints = [models.UniqueConstraint(fields=['token', 'domain'], name='unique_entry')] In views.py, I have: class TokenDomainPolicyViewSet(viewsets.ModelViewSet): lookup_field = 'domain__name' permission_classes = (IsAuthenticated,) serializer_class = serializers.TokenDomainPolicySerializer def get_queryset(self): return models.TokenDomainPolicy.objects.filter(token_id=self.kwargs['id'], token__user=self.request.user) You can see from TokenDomainPolicyViewSet.lookup_field that I would like to be able to query the -detail endpoint by using the related Domain's name field instead of its primary key. (name is unique for a given token.) I thought this can be done with lookup_field = 'domain__name'. However, it doesn't quite work. Here's my urls.py: tokens_router = SimpleRouter() tokens_router.register(r'', views.TokenViewSet, basename='token') tokendomainpolicies_router = SimpleRouter() tokendomainpolicies_router.register(r'', views.TokenDomainPolicyViewSet, basename='token_domain_policies') auth_urls = [ path('tokens/', include(tokens_router.urls)), # for completeness only; problem persists if removed path('tokens/<id>/domain_policies/', include(tokendomainpolicies_router.urls)), ] urlpatterns = [ path('auth/', include(auth_urls)), ] The list endpoint works fine (e.g. /auth/tokens/6f82e9bc-46b8-4719-b99f-2dc0da062a02/domain_policies/); it returns a list of serialized TokenDomainPolicy objects. However, let's say there is a Domain object with name = 'test.net' related … -
Object type <class 'str'> cannot be passed to C code CCAvenue payment gateway interation pycryptodome::3.10.1
I want to integrate CCAvenue payment gateway into my website, for that purpose I have to send all the requirements such as Merchant ID, working key etc in encrypted form to their page for payment. For encryption I am using pycryptodome==3.10.1. This is the method which I am using to encrypt my details. def encrypt(plain_text, working_key): """ Method to encrypt cc-avenue hash. :param plain_text: plain text :param working_key: cc-avenue working key. :return: md5 hash """ iv = '\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f' plain_text = pad(plain_text) byte_array_wk = bytearray() byte_array_wk.extend(map(ord, working_key)) enc_cipher = AES.new(hashlib.md5(byte_array_wk).digest(), AES.MODE_CBC, iv) #error line hexl = hexlify(enc_cipher.encrypt(plain_text)).decode('utf-8') return hexl At 3rd last line, I am getting this error Object type <class 'str'> cannot be passed to C code. Here is the data which I am encrypting, just in case if you need it. merchant_data = 'merchant_id=' + p_merchant_id + \ '&' + 'order_id=' + p_order_id + \ '&' + "currency=" + p_currency + \ '&' + 'amount=' + p_amount + \ '&' + 'redirect_url=' + p_redirect_url + \ '&' + 'cancel_url=' + p_cancel_url + \ '&' + 'language=' + p_language + \ '&' + 'billing_name=' + p_billing_name + \ '&' + 'billing_address=' + p_billing_address + \ '&' + 'billing_city=' + p_billing_city … -
Django: Include a html on ajax request
I am using Django as my Webframework togehter with Ajax for async calls. When a button is pressed I want an entire HTML file to be loaded in (like normal includes). This is the AJAX code: $.ajax({ url: "{% url 'project-detail' project_object.id %}", type: 'get', data: { ... }, success: function (response) { $("#div1").html("{% include 'projects/recommendations.html' %}") } }) As you can see I try to wrap {% include 'projects/recommendations.html' %} with ".". This unfortunatley doesnt work. As a work around I thought of reading the file in and output the string. As the to be included file is also relatively large ~150 LOC I try to avoid having it all in one file. Is there a way to neatly load this in? -
nginx - gunicorn - django allauth redirect to 127.0.0.1 issue, how can I solve this?
I want to deploy my django app with nginx-gunicorn. so I set nginx and gunicorn conf like this. /etc/nginx/conf.d/default.conf included by /etc/nginx/nginx.conf server { listen 80; server_name my.domain.com; charset utf-8; location /static/ { root /home/flood/dj-eruces-ango; } location / { proxy_pass http://127.0.0.1:8000; #include proxy_params; #proxy_pass http://unix:/etc/systemd/system/gunicorn.socket; } } /etc/systemd/system/gunicorn.service [Unit] Description=gunicorn daemon After=network.target [Service] User=flood Group=www-data WorkingDirectory=/home/flood/dj-eruces-ango/ ExecStart=/home/flood/dj-eruces-ango/secure/bin/gunicorn \ --workers 2 \ --bind 0.0.0.0:8000 \ config.wsgi:application [Install] WantedBy=multi-user.target and I set my google social-auth api to 'my.domain.com' and 'my.domain.com/auth/google/login/callback/' but when I try social auth, the error occurs below. 400 error: redirect_uri_mismatch http://127.0.0.1:8000/auth/google/login/callback/ I want to solve this. show localhost issue(not a my.domain.com) and redirect_uri_mismatch issue. How can I try? -
django.db.utils.ProgrammingError: (1146, "Table 'zebrapro.corpann_comments_updated' doesn't exist") Error. How to fix?
I shifted my django website to MySQL DB on localhost. Post this migrated models in MySQL. However, I deleted one table directly from SQL language. Now no matter what I run, the django python manage.py migrate command shows this error - django.db.utils.ProgrammingError: (1146, "Table 'zebrapro.corpann_comments_updated' doesn't exist") I tried creating similar table using SQL too. However, does not work. Please help fix this. -
ISSUE ON NOT NULL constraint failed: accounts_user.course_id
I'm trying to create a multiple user model in django. I am a beginner using django and as such not in a position to get the exact result I need. I got an error when trying to createsuperuser. Here is my model.py *from django.db import models from admin_dash.models import Course from django.contrib.auth.models import ( BaseUserManager, AbstractBaseUser ) class UserManager(BaseUserManager): def create_user(self,roll,phone,name,password=None): if not roll: raise ValueError('You Don't have Permission to do exam') user = self.model( roll=roll, phone=phone, name=name ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self,roll,phone,name, password): user = self.create_user(roll,phone,name,password=password) user.is_admin = True user.is_staff=True user.save(using=self._db) return user class User(AbstractBaseUser): phone= models.CharField(verbose_name='phone number', max_length=12,unique=True) name=models.CharField(max_length=150,null=True) roll=models.CharField(max_length=20,verbose_name='roll',unique=True) course=models.ForeignKey(Course,on_delete=models.CASCADE) date_joind=models.DateTimeField(verbose_name='date joind', auto_now_add=True) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) is_staff=models.BooleanField(default=False) USERNAME_FIELD = 'roll' REQUIRED_FIELDS = ['name','phone'] objects = UserManager() def __str__(self): return self.name def has_perm(self, perm, obj=None): return self.is_admin def has_module_perms(self, app_label): return True* This is My admin.py *from django.contrib import admin from .import models # Register your models here. admin.site.register(models.User)* Trying to create a superuser I got the following traceback *Traceback (most recent call last): File "C:\Users\freddyparc\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\utils.py", line 86, in _execute return self.cursor.execute(sql, params) File "C:\Users\freddyparc\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\sqlite3\base.py", line 396, in execute return Database.Cursor.execute(self, query, params) sqlite3.IntegrityError: NOT NULL constraint failed: accounts_user.course_id The above exception was … -
Django - my function doesn't update data in the database
My function does not update the data in the database. It seems to work properly, but nothing changes in the database task.py import time from celery import shared_task from store.models import Product @shared_task # do something heavy def hh(self): records = Product.objects.filter() for rec in records: rec.price_before_offer = rec.price * 4 / 3 rec.save() while True: hh() time.sleep(10000) -
Can anyone tell how to upload multiple files using Restangular, I'm using Django Rest Framework as a backend
On my web page, I have multiple questions and their answers and all fields have a browse button that selects files, images. I have put attachment and answer in the $scope.question.attachment so when I am making API call it is taking this data from Frontend sends to the backend and also I am not using the element and FYI answers are going to the backend correctly and storing in database. (now you are thinking how answers are going in backend and not attachments because I have put attachments read_only = true) class ServiceProjectAnswerSerializer(serializers.ModelSerializer): attachement = AnswerAttachmentsSerializer(read_only=True, many=True) def create(self, validated_data): instance = ServiceProjectAnswer(**validated_data) if isinstance(self._kwargs["data"], dict): instance.save() return instance class Meta: model = ServiceProjectAnswer fields = ('project', 'question', 'answer', 'attachement') list_serializer_class = BulkCreateListSerializer My problem is that how can I select multiple files and how to do a rectangular post method for files (with files I am also sending answers and question id)so please keep that in mind. how to select multiple files? How to send files and data both? with this method (If you want more info please tell me in comments and If you don't understand what I am talking about then also please tell me in comments … -
Django Bulk Create doesn't respect ignore_conflicts for django.db.utils.IntegrityError
I am trying to do two sequential bulk creates to sync data to django from another data store. The problem is the data store allows duplicates but I don't want to allow that in my django schema. I'm ok losing the duplicates. Duplicates are based on two of the items fields The first bulk create generates a bunch of items, the second creates a through field for those items. If there is a duplicate in the first list of items, the second bulk create fails since it is trying to create a through field for a item that doesn't exist. I would want that second create to fail gracefully like the first since I'm using ignore_conflicts=True but it throws an exception and no other items get created. Even worse, since I'm supplying the primary key the first bulk create returns all of the items, even if they weren't actually created. I'm creating hundreds of these every second, so I have to use bulk create. Anyway to get bulk create to ignore the IntegrityError exception? I'm using postgresql. -
Heroku deployment failure-- psycopg2 installation failure
I am getting a persisting error when I am deploying my python/Django project to heroku. I keep getting "It appears you are missing some prerequisite to build the package from source. You may install a binary package by installing 'psycopg2-binary' from PyPI. If you want to install psycopg2 from source, please install the packages required for the build and try again. For further information please check the 'doc/src/install.rst' file (also at <https://www.psycopg.org/docs/install.html>)." and when I install psycopg2 I also get the same message, any help please github repo Link : https://github.com/moeabraham/finalsoccer Also, they might be helpful, when typing commands for pip I usually get an error unless I wrote it as pipenv! I am a beginner and this has been confusing so far :) -
Django Forms: Attributes on Select Element not being applied?
I've got a Django Model Form that I am rendering in a modal window. It's displaying fine and I have no issues except for the styling of one of the dropdowns. I can add/remove classes to the other field in the form without issue - but the Select widget does not use the attrs I am giving it. My Issue: The select widget in the Django model form is not applying the correct classes My Attempts To Fix: I've tried setting the attributes in the __init__ method Setting them as they currently are (which is the recommended method from documentation) Creating another model to extend the Select widget as found here on SO My Code: forms.py: class EvaluationForm(forms.ModelForm): """Form definition for Evaluation.""" # THESE ATTRS LOAD FINE AND CLASSES APPLIED AS EXPECTED evaluation_date = forms.CharField( max_length=100, widget=forms.TextInput(attrs={"class": "form-control test"}), ) # THESE ATTRS ARE NOT BEING APPLIED TO THE SELECT WIDGET - NO CLASSES APPLIED evaluation_level = forms.ModelChoiceField( queryset=EvaluationLevel.objects.all(), widget=forms.Select( attrs={"class": "form-control something something-else"} ), ) class Meta: """Meta definition for Evaluationform.""" model = Evaluation fields = [ "summative", "evaluation_type", "evaluation_level", "evaluation_date", ] widgets = { "summative": forms.HiddenInput(), "evaluation_type": forms.HiddenInput(), } template html that renders the form: {% if form.non_field_errors … -
Page not found (404), The empty path didn’t match any of these
I know this question is asked in many different forms, but I can't find a solution for my problem; My problem is I need to display the static pages and I have run into this error:enter image description here I have also used URL instead of re_path but it doesn't work, I am newly to Django please any help would be appreciated. Here is my code: `urlpatterns = [ path('admin/', admin.site.urls), re_path(r'^', include('EmployeeApp.urls')) ]` App.urls: `urlpatterns=[ re_path(r'^department$',views.departmentApi, name='department'), re_path(r'^department/([0-9]+)$',views.departmentApi, name='departmentApi'), re_path(r'^employee$',views.employeeApi, name='employee'), re_path(r'^employee/([0-9]+)$',views.employeeApi, name='employeeApi'), re_path(r'^Employee/SaveFile$', views.SaveFile, name='SaveFile') ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)` The view: @csrf_exempt def departmentApi(request, id=0): if request.method == 'GET': department = Departments.objects.all() departments_serializer = DepartmentSerializer(department, many=True) return JsonResponse(departments_serializer.data, safe=False) elif request.method == 'POST': department_data = JSONParser().parse(request) department_serializer = DepartmentSerializer(data=department_data) if department_serializer.is_valid(): department_serializer.save() return JsonResponse("Added Successfully!!", safe=False) return JsonResponse("Failed ro Add.",safe=False) elif request.method=='PUT': department_data = JSONParser().parse(request) department=Departments.objects.get(DepartmentId=department_data['DepartmentId']) department_serializer=DepartmentSerializer(department,data=department_data) if department_serializer.is_valid(): department_serializer.save() return JsonResponse("Updated Successfully!!", safe=False) return JsonResponse("Failed to Update.", safe=False) elif request.method == 'DELETE': department = Departments.objects.get(DepartmentId=id) department.delete() return JsonResponse("Deleted Successfully!!", safe=False) @csrf_exempt def employeeApi(request,id=0): if request.method=='GET': employees = Employees.objects.all() employees_serializer = EmployeeSerializer(employees, many=True) return JsonResponse(employees_serializer.data, safe=False) elif request.method=='POST': employee_data=JSONParser().parse(request) employee_serializer = EmployeeSerializer(data=employee_data) if employee_serializer.is_valid(): employee_serializer.save() return JsonResponse("Added Successfully!!" , safe=False) return JsonResponse("Failed to Add.",safe=False) elif request.method=='PUT': employee_data = … -
<!DOCTYPE html> missing in Selenium Python page_source
I'm using Selenium for functional testing of a Django application and thought I'd try html5lib as a way of validating the html output. One of the validations is that the page starts with a <!DOCTYPE ...> tag. The unit test checks with response.content.decode() all worked fine, correctly flagging errors, but I found that Selenium driver.page_source output starts with an html tag. I have double-checked that I'm using the correct template by modifying the title and making sure that the change is reflected in the page_source. There is also a missing newline and indentation between the <html> tag and the <title> tag. This is what the first few lines looks like in the Firefox browser. <!DOCTYPE html> <html> <head> <title>NetLog</title> </head> Here's the Python code. self.driver.get(f"{self.live_server_url}/netlog/") print(self.driver.page_source And here's the first few lines of the print when run under the Firefox web driver. <html><head> <title>NetLog</title> </head> The page body looks fine, while the missing newline is also present between </body> and </html>. Is this expected behaviour? I suppose I could just stuff the DOCTYPE tag in front of the string as a workaround but would prefer to have it behave as intended. Chris -
Poner un request en un graficador con Django
estoy haciendo un codigo en Django que me permite graficar funciones con Django, he usado las librerias de matplotlib y numpy para poder graficarlas. El caso es que, si yo quiero graficarlas en codigo quemado me funciona de maravilla, si le doy la función ya definida por el sistema si me genera la grafica, pero si lo hago para que el usuario escriba por teclado la función para que se grafique me sale un error, alguna idea de que pueda hacer? Funcion import numpy as np import matplotlib.pyplot as plt def Graficador(request): t = np.arange(-10.0, 10.0, 0.010, ) s = 1 + np.sin(2 * np.pi * t) s = parse_expr(s) fig, ax = plt.subplots() ax.plot(t, s) ax.set(xlabel='time (s)', ylabel='voltage (mV)', title='About as simple as it gets, folks') ax.grid() g = mpld3.fig_to_html(fig) fig.savefig("test.png") context = {'g': g} return render(request, 'Graficar.html', context) Y Así lo mando al HTML {% autoescape off %} <div>{{ g }}</div> {% endautoescape %} El codigo que adjunté funciona solo con los valores ya establecidos por el sistema, es decir "s" viene siendo la función a graficar, pero no he entendido muy bien como hacer que el usuario pueda entrar por teclado la función que quisiera graficar, alguna … -
Django/DRF: Is it ok to make validate methods static?
In an effort to make my code as clean as possible, I'm making a pass to add @staticmethod to all methods that don't use self. In DRF, a typical validate method looks like this: def validate_website(self, value): value = value.strip() if len(value) > 200: raise ValidationError(_('Website may have up to 200 characters.')) return value In other words, validate methods almost always use value instead of self, so they are candidates for being @staticmethod. In addition to wanting to eliminate the annoying squiggly underscores my IDE puts under the method name to let me know it "might be static", I'm thinking that there is surely some overhead associated with passing self to each method. So eliminating that overhead if not needed can't be a bad thing, right? So, two questions... 1) Is it ok to add @staticmethod to those validate methods?; and, 2) Is it worth it from a performance perspective? -
Django Model form not rendering
Im trying to create a model form on django but it doesnt want to render even though I mapped it properly and created the path. models.py from django.db import models # Create your models here. Media_Choices = ( ("TV", "TV"), ("Radio", "Radio"), ("Youtube", "Youtube"), ("Podcast", "Podcast"), ) class Appear(models.Model): Show = models.CharField(max_length=100) Media = models.CharField(max_length=30, blank=True, null=True, choices=Media_Choices) Episode = models.IntegerField() Date = models.DateField(max_length=100) Time = models.TimeField(auto_now=False, auto_now_add=False) Producer = models.CharField(max_length=100) Producer_Email = models.EmailField(max_length=254) def __unicode__(self): return self.Show + ' ' + self.Producer_Email forms.py from django import forms from django.core.exceptions import ValidationError from django.forms import ModelForm from .models import Appear class AppsForm(ModelForm): class Meta: model = Appear fields = '__all__' def clean_Producer_Email(self): Producer_Email = self.cleaned_data.get('Producer_Email') if (Producer_Email == ""): raise forms.ValidationError('field cannot be left empty') for instance in Appear.objects.all(): if instance.Producer_Email == Producer_Email: raise forms.ValidationError('Please fill in correct email') return Producer_Emailenter views.py from django.shortcuts import render from .forms import AppsForm # Create your views here. def AppS(request): form = AppsForm() context = {'forms': form} return render(request, 'AppsForm.html', context) it refuse to render but it displays the html tag that is in the file but not the fields from the form. -
How to Import razorpay payment gateway in django
I am integrating razorpay payment gateway in django project but i am getting error while importing razorpay as :- Import razorpay could not be resolved from django.shortcuts import render import razorpay # Here i am getting error from .models import coffee -
unable to upload files in django through web forms
I am trying to create a django website similar to that of Udemy or Coursera. I am trying to implement a feature that lets users add courses. Here is my view for adding the course: def create_course(request): form = CreateCourseForm() if request.method == 'POST': form = CreateCourseForm(request.POST) if form.is_valid(): new_course = form.save(commit=False) new_course.instructor = request.user new_course.save() return redirect('home') return render(request, 'courses/create.html',{'form':form}) Here is my form: class CreateCourseForm(forms.ModelForm): class Meta: model = Course fields = ('name','video','description','category',) My course model: class Course(models.Model): name = models.CharField(max_length=200) instructor = models.ForeignKey(User, on_delete=models.CASCADE) video = models.FileField(upload_to='videos/') description = models.TextField() category = models.ForeignKey(Category, on_delete=models.CASCADE) def __str__(self): return self.name And finally my web form: {% extends "base.html" %} {% load crispy_forms_tags %} {% block content %} <h1>Create a Course</h1> <hr> <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form|crispy }} <button class="btn btn-sm btn-outline-primary" type="submit">Create Course</button> </form> {% endblock %} The issue i am facing is that when i try to create a course, the video field shows an error "This field is required" even when I have uploaded a video. I tried researching a bit and found out that adding enctype="multipart/form-data" to the form was required, but even adding that didn't solve my problem Can anyone help me … -
Getting DoesNotExist at /admin/auth/user/, when deleting an user in admin panel
I use UserCreationForm.While creating the user there was some error while creating that. Some crashing with typo after the form.save. But when i decide to delete it, it shows error. Iam sharing my whole settings.py, sorry for the inconvenience, this is the first time i got this error while using admin panel,So i don't actually know where will the error, I'am assuming this is. Thankyou! my settings.py ALLOWED_HOSTS = ['localhost','127.0.0.1'] INSTALLED_APPS = [ 'projects', 'users', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'whitenoise.middleware.WhiteNoiseMiddleware', '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' ] ROOT_URLCONF = 'devsearch.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ BASE_DIR / "templates" ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } 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', }, ] LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True STATIC_URL = '/static/' STATICFILES_DIRS=[ BASE_DIR / 'static' ] STATIC_ROOT= BASE_DIR / 'staticfiles' MEDIA_URL = '/images/' MEDIA_ROOT=BASE_DIR / 'static' DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField``` -
Django forms: How to set the initial value of a field, the value it currently contains in the database
i want the user to be able to see what the current value of the field is, while submitting another value forms.py: class CustomerInfoForm(forms.Form): first_name = forms.CharField( label="Firstname", widget=widgets.TextInput(), required=False, ) last_name = forms.CharField( label="Lastname", widget=widgets.TextInput(), required=False, ) views.py: (authentication by phone number) @login_required def customer_panel_info_view(request): info_form = CustomerInfoForm(request.POST or None) if request.user.is_authenticated: user_phone_number = request.user.phone_number if info_form.is_valid(): first_name = info_form.cleaned_data.get("first_name") last_name = info_form.cleaned_data.get("last_name") customer = User.objects.get(phone_number=user_phone_number) customer.first_name = first_name customer.last_name = last_name customer.save() context = { "info_form": info_form, } return render(request, "panel/info.html", context) the template: <form action="" method="post"> {% csrf_token %} {% info_form %} <button type="submit" class="btn btn-success">submit</button> </form> here is the flow: user goes to this form and wants to add, change or delete a piece of information(this is a piece of the whole template. actually it contains gender birthdate and other things). I want the fields to have the current value so user knows which fields already has a value -
NameError at /list_items/ Django [closed]
im making an app and was trying to add a queryset but it shows an error like thisenter image description here my code: from django.shortcuts import render #from djangoproject.stockmgmt.models import Stock # Create your views here. def home(request): title = 'Welcome: This is the Home Page' form = 'Welcome: This is the Home Page' context = { "title": title, "test": form } return render(request, "home.html",context) def list_item(request): title = 'List of Items' Queryset = Stock.object.all() context = { "title": title, "Queryset": Queryset, } return render(request, "list_items.html", context) -
How to generate an embed code on a Django video sharing platform?
I have created a video sharing platform on Django that uses Plyr player to play videos on the platform. Users can upload any video directly on the platform. Now I want my users to be able to generate an embed code for the video so that they can share it on any other HTML/CSS website like you could do on YouTube. How do I go about achieving this?