Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Clicking the button in the html template does not change the "status" field in the django model
everyone! I have models.py class Post(models.Model): ... status = models.CharField(max_length=16, choices=STATUS_CHOICES, default='Activated') ... urls.py app_name = 'posts' urlpatterns = [ ... path('<int:pk>/update/', views.PostUpdateView.as_view(), name='update_status')] views.py class PostUpdateView(UpdateView): model = Post template_name = 'post_detail.html' def change_status(self): if request.method == "POST": post = Post.objects.filter(id=self.id) if post.status == 'Activated': post.status = 'Deactivated' post.save() elif post.status == 'Deactivated': post.status = 'Activated' post.save() return redirect('posts:post_detail') posts_detail.html ... <form action="{% url 'posts:update_status' post.id %}" method="post"> {% csrf_token %} <button type="button"> {% if post.status == 'Activated' %} Deactivate {% else %} Activate {% endif %}</button> </form> ... I want to switch the field on the button "Activate/Deactivate" and redirect to the same page. At the moment there is a button and when clicked nothing changes. Well or maybe the redirect works, but the status does not switch. I'm assuming wrong views.py, but can't figure out where. I tried it like this @require_http_methods(['POST']) def update_status(request, id): if post.status == 'Activated': Post.objects.filter(id=id).update(status='Deactivated') elif post.status == 'Deactivated': Post.objects.filter(id=id).update(status='Activated') return redirect('posts:post_detail') But that doesn't work either. I know these are similar ways, but I don't have any more ideas. -
Django admin inline and multiple queries
I'm optimizing Django admin, and have some issues with inlines. I saw a few questions from Stack Overflow, but none was helpful. Here is my code: models/consumer_application.py class ConsumerApplication(TimeStampedModel, ActivatorModel, HumanReadableIdModel): uuid = models.UUIDField(default=uuid.uuid4, db_index=True, unique=True) status = models.ForeignKey("consumer.ApplicationStatus", on_delete=models.PROTECT) ... models/offer.py class ConsumerApplication(TimeStampedModel, ActivatorModel, HumanReadableIdModel): uuid = models.UUIDField(default=uuid.uuid4, db_index=True, unique=True) application = models.ForeignKey("consumer.ConsumerApplication", on_delete=models.PROTECT, related_name="offers") ... admin.py @admin.register(ConsumerApplication) class ConsumerApplicationAdmin(UserInlineCustomAdminMixin, AddNewDisabled, admin.ModelAdmin): exclude = [...] list_display = (...) search_fields = (...) readonly_fields = (... ) inlines = [OfferInline] def get_queryset(self, request): return super().get_queryset(request).prefetch_related("offers") class OfferInline(admin.TabularInline): model = Offer exclude = [...] And when I open ConsumerApplication detail view, I have 6 offers displayed, and 12 queries: SELECT "consumer_offer"."id", "consumer_offer"."application_id" FROM "consumer_offer" WHERE "consumer_offer"."id" = 675 LIMIT 21 I was trying to override get_queryset of OfferInline, but whatever I did, I get the same. How can I optimize it, so that I don't have these 12 queries? -
Overriding django admin pagination along with dynamic values
I am working on a project, I have a requirement from my client he wants to implement a dynamic paginator in django admin panel. Requirement is when user input 10, ten record will display per page same for 20,30 is there any way to do it. -
Argon2 password hashing in django
i noticed my django is hashing the passwords asargon2$argon2id$v=19$m=102400,t=2,p=8$salt$hash according to Argon2 in browser the encription is $argon2id$v=19$m=102400,t=2,p=8$salt$hash if i try to match argon2$argon2id$v=19$m=102400,t=2,p=8$salt$hash to the actual password it will not match, but if i test it against $argon2id$v=19$m=102400,t=2,p=8$salt$hash it matches Is there a way that i can hash a password to argon2$argon2id$v=19$m=102400,t=2,p=8$salt$hash offline so it will work if i replace it in the database of django? -
I am trying to create a circle progress bar, but I can not access the javascript variables, why?
I am working with tailwind.css in my Django HTML template. I am trying to recreate this circle https://tailwindcomponents.com/component/circular-progress-bar, but I am not rolling my screen, I am setting a static percentage based on a value from my view. This average rate calculation does not matter, this is working in another part, it is just an example to show what I want to do in my radial bar. class RatePage(TemplateView): template_name = "tailwind/rate-page.html" def get_context_data(self, **kwargs): context = super(RatePage, self).get_context_data(**kwargs) context['average_rate'] = 4.5 return context This is my HTML template. <div class="flex flex-col"> Score <svg class="w-20 h-20"> <circle class="text-gray-300" stroke-width="5" stroke="currentColor" fill="transparent" r="30" cx="40" cy="40" /> <circle class="text-blue-600" stroke-width="5" :stroke-dasharray="circumference" :stroke-dashoffset="circumference - percent / 100 * circumference" stroke-linecap="round" stroke="currentColor" fill="transparent" r="30" cx="40" cy="40" /> </svg> <span class="absolute text-xl text-blue-700" x-text=30></span> </div> <script> let percent = rate; let circumference = 2 * Math.PI * 30; </script> I am trying to connect JavaScript with the rate value from view to make this calculus. But, everything I am getting is this: But, I am trying to do it: Any suggestion? -
Django TemplateSyntaxError - for loop counter issue
I am attempting to call a function in my Django template. This function is called within a forloop and the function should take the loop index (counter of sorts) as its parameter. Below is the template code for which I am receiving an issue. {% for showing in show.num_of_performances %} {% with index=forloop.counter0 %} <tr> <td> {{ show.next(index) }} </td> <td> {{ show.performer }} </td> </tr> {% endwith %} {% endfor %} The error I am receiving is: TemplateSyntaxError at /showing_list/2/ Could not parse the remainder: '(index)' from 'show.next(index)'. I had tried just putting 'forloop.counter0' in the parentheses for show.next initially but received a similar error and so have been trying this but it does not seem to be working no matter what I try. -
Unpacking a JSONField into multiple django forms fields to update with UpdateView
l'm new to Django and don't understand what exactly i need to do to update my JSONfield in django model. models.py: class Schemas(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=15) modified = models.DateField() column_separator = models.CharField(max_length=1) string_character = models.CharField(max_length=1) json_data = models.JSONField() forms.py: class UpdateSchemaForm(forms.ModelForm): class Meta: model = Schemas fields = ['title', 'column_separator', 'string_character', 'json_data'] views.py: class UpdateSchema(UpdateView): model = Schemas form_class = UpdateSchemaForm template_name = 'updateschema.html' success_url = 'home' I have a form where user can add new fields and fill them with data. enter image description here Then these fields save in JSONfield in models.py I want to allow user to update the JSONfield using UpdateView like making the same forms but filed. -
Views return html from another app in Django
I want to show a data with different feature .. So, there's 2 role where admin have 5 column on table when the teacher only have 4 column on table. I change the HTML already but when i return classlist.html on teacherpage views.py .. it return the admin classlist.html that have 5 column on the table. Here is my code : Urls.py (Teacher APP): from django.urls import path from teacherpage import views urlpatterns = [ path('', views.index, name='index'), path('classlist/', views.classlist, name='classlist'), ] Views.py (Teacher APP): def classlist(request): data = classModel.objects.all() classlist= { "classlist" : data } return render(request,'classlist.html', classlist) -
How to fix Django N+1 problem when you need to get data from a set of objects
I created a function and I wrote a query that results in N+1 Problem how to fix it code sponsors = CustomUser.objects.filter(user_type = 2, is_deleted = False) for s in sponsors: s.sponsor_detail = Sponsor.objects.get_or_create(user = s, is_deleted = False) -
Server Running Issue in Django. Ubuntu
I'm trying to display something on django server but Nothing is happening. I'm facing this error: "snapcraft.io store API service - Copyright 2018-2022 Canonical." I tried Everything But nothin... work. Please tell me correct solution :( I Tried This | python manage.py runserver [::]:8000 |, python manage.py runserver 0.0.0.0:8000 |, sudo nmap -sT -O localhost #to install=> sudo apt-get install nmap -
What is the best Way to modify PDF in Django?
Actually I want to modify PDF which is Certificate need to change name, date, course name and course description. I have tried the pypdf2 but doesn't work for me. Here is What i tried so far pdfFileObj = open('/home/nawaf/Documents/5_dec_truck_courses/29_Nov_Updated/truck_courses/LMS_Online_App/static/certificate.pdf', 'rb') pdf_reader = PdfFileReader(io.BytesIO(pdfFileObj.read())) pdf_page = pdf_reader.pages[0] pdf_text = pdf_page.extractText() change_name = pdf_text.replace("John Doe", "Nawaf").replace("NAME OF THE COURSETO","Rent Everything").replace("The course description will go her.","My Own Description") pdfFileObj.close() pdf_writer = PdfFileWriter(pdfFileObj) with open('/home/nawaf/Documents/5_dec_truck_courses/29_Nov_Updated/truck_courses/test/test.pdf', 'wb') as f: pdf_writer.addPage(page=pdf_page) pdf_writer.add_annotation(page_number=0, annotation=pdf_reader.metadata) pdf_writer.write(f) f.close() -
Page contents in Navbar not filling the screen:
Click here for image of problem Basically I sourced the code from getbootstrap.com but the search bar and search button are not being right-aligned in the navbar. Have tried to selectively align the search option but to no avail. Would live it if anyone helped. Thank you. Here is the code: ``` <nav class="navbar navbar-expand-lg navbar-light bg-light"> <a class="navbar-brand" href="#">Navbar</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav mr-auto"> <li class="nav-item active"> <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a> </li> <li class="nav-item"> <a class="nav-link" href="#">Link</a> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Dropdown </a> <div class="dropdown-menu" aria-labelledby="navbarDropdown"> <a class="dropdown-item" href="#">Action</a> <a class="dropdown-item" href="#">Another action</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="#">Something else here</a> </div> </li> <li class="nav-item"> <a class="nav-link disabled" href="#">Disabled</a> </li> </ul> <form class="form-inline my-2 my-lg-0"> <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search"> <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button> </form> </div> </nav> ``` -
Wagtail add functions to models.py
i'm trying to make a custom plotly-graphic on a wagtail homepage. I got this far. I'm overriding the wagtail Page-model by altering the context returned to the template. Am i doing this the right way, is this possible in models.py ? Thnx in advanced. from django.db import models from wagtail.models import Page from wagtail.fields import RichTextField from wagtail.admin.panels import FieldPanel import psycopg2 from psycopg2 import sql import pandas as pd import plotly.graph_objs as go from plotly.offline import plot class CasPage(Page): body = RichTextField(blank=True) content_panels = Page.content_panels + [ FieldPanel('body'), ] def get_connection(self): try: return psycopg2.connect( database="xxxx", user="xxxx", password="xxxx", host="xxxxxxxxxxxxx", port=xxxxx, ) except: return False conn = get_connection() cursor = conn.cursor() strquery = (f'''SELECT t.datum, t.grwaarde - LAG(t.grwaarde,1) OVER (ORDER BY datum) AS gebruiktgas FROM XXX ''') data = pd.read_sql(strquery, conn) fig1 = go.Figure( data = data, layout=go.Layout( title="Gas-verbruik", yaxis_title="aantal M3") ) output = plotly.plot(fig1, output_type='div', include_plotlyjs=False) # https://stackoverflow.com/questions/32626815/wagtail-views-extra-context def get_context(self, request): context = super(CasPage, self).get_context(request) context['output'] = output return context -
Nginx: "The requested resource was not found on this server."
I have a Django app listening at 127.0.0.1:8000, my Nginx config is simply location / { proxy_pass http://127.0.0.1:8000; proxy_ssl_server_name on; } Everything works as expected. But then I changed the configuration to location /xxx { proxy_pass http://127.0.0.1:8000; proxy_ssl_server_name on; } I got error "The requested resource was not found on this server" when trying to access the website with "/xxx". What might be the problem? -
How to access Django parent model using Foreign key
I have this model: class Cohort(models.Model): id = models.AutoField(primary_key=True,editable=True) origin=models.BooleanField(default=False) title = models.CharField(max_length=200,validators=[MaxLengthValidator(100)]) email = models.ForeignKey(Userdata, on_delete=models.PROTECT,default='0',db_constraint=False) def __str__(self): return self.title class Subcohort(models.Model): cohort_id=models.ForeignKey(Cohort,on_delete=models.PROTECT,default=0,db_constraint=False,related_name='subcohortid') parent_id=models.ForeignKey(Cohort,on_delete=models.PROTECT,default=0,db_constraint=False,related_name='subparentid') From views.py I want to read Cohort model data using the subcohort cohort_id. I want to get an object which contains cohort data along with subcohort data. Can someone help? Thank you. -
How to use .get(id=some_model_field) in Model constraints?
I have class 'Car' class 'EngineType' and i want to add to it constraints. I want to check what type of engine is in the car, so i tried: models.CheckConstraint(check=(Q(EngineType.objects.get(id=engine_type).name=='electric')), name='test_constraint') where 'engine_type' is foreign key to EngineType. It gives me this error: NameError: name 'engine_type' is not defined. Did you mean: 'EngineType'? Constraints perfectly works without .get(), e.g. models.CheckConstraint(check=(Q(engine_type=1)), name='test_constraint2'), so it means that there is access to the 'engine_field' from constraints, but i have to check current engine type, not static. Any help would appreciate! 'Car' and 'EngineType' listing without some other fields: class EngineType(models.Model): name = models.CharField(max_length=100) class Car(models.Model): engine_type = models.ForeignKey(EngineType, on_delete=models.PROTECT) class Meta: constraints = [ models.CheckConstraint(check=(Q(EngineType.objects.get(id=engine_type).name=='electric')), name='test_constraint') ] Django automatically adds 'id to foreign key fields, i tried to replace in .get() 'engine_type' to 'engine_type_id', but got the same error with 'engine_type' replaced to 'engine_type_id'. -
Python Django Error: FileNotFoundError: [Errno 2] No such file or directory: '/proc/393/task/558'
I receive this error. It is happening during regular requests from front end, previous request has response 200, but then my backend container is suddenly reloading. Previously it was working and everything worked well. Django version 3.2.13 Python version 3.9 Cloud AWS Traceback: Traceback (most recent call last): File "/app/manage.py", line 21, in <module> main() File "/app/manage.py", line 17, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.9/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.9/site-packages/django/core/management/commands/runserver.py", line 61, in execute super().execute(*args, **options) File "/usr/local/lib/python3.9/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.9/site-packages/django/core/management/commands/runserver.py", line 96, in handle self.run(**options) File "/usr/local/lib/python3.9/site-packages/django/core/management/commands/runserver.py", line 103, in run autoreload.run_with_reloader(self.inner_run, **options) File "/usr/local/lib/python3.9/site-packages/django/utils/autoreload.py", line 638, in run_with_reloader start_django(reloader, main_func, *args, **kwargs) File "/usr/local/lib/python3.9/site-packages/django/utils/autoreload.py", line 623, in start_django reloader.run(django_main_thread) File "/usr/local/lib/python3.9/site-packages/django/utils/autoreload.py", line 329, in run self.run_loop() File "/usr/local/lib/python3.9/site-packages/django/utils/autoreload.py", line 335, in run_loop next(ticker) File "/usr/local/lib/python3.9/site-packages/django/utils/autoreload.py", line 375, in tick for filepath, mtime in self.snapshot_files(): File "/usr/local/lib/python3.9/site-packages/django/utils/autoreload.py", line 391, in snapshot_files for file in self.watched_files(): File "/usr/local/lib/python3.9/site-packages/django/utils/autoreload.py", line 294, in watched_files yield from directory.glob(pattern) File "/usr/local/lib/python3.9/pathlib.py", line 1177, in glob for p in selector.select_from(self): File "/usr/local/lib/python3.9/pathlib.py", line 611, in _select_from for p in successor_select(starting_point, is_dir, exists, … -
Queryset filter
i whant to count a number of policy that have the status 2 and filter by date and by health_facilities i have 4 tables this are the model class Policy(core_models.VersionedModel): id = models.AutoField(db_column='PolicyID', primary_key=True) uuid = models.CharField(db_column='PolicyUUID', max_length=36, default=uuid.uuid4, unique=True) stage = models.CharField(db_column='PolicyStage', max_length=1, blank=True, null=True) status = models.SmallIntegerField(db_column='PolicyStatus', blank=True, null=True) value = models.DecimalField(db_column='PolicyValue', max_digits=18, decimal_places=2, blank=True, null=True) family = models.ForeignKey(Family, models.DO_NOTHING, db_column='FamilyID', related_name="policies") enroll_date = fields.DateField(db_column='EnrollDate') start_date = fields.DateField(db_column='StartDate') effective_date = fields.DateField(db_column='EffectiveDate', blank=True, null=True) expiry_date = fields.DateField(db_column='ExpiryDate', blank=True, null=True) product = models.ForeignKey(Product, models.DO_NOTHING, db_column='ProdID', related_name="policies") officer = models.ForeignKey(Officer, models.DO_NOTHING, db_column='OfficerID', blank=True, null=True, related_name="policies") offline = models.BooleanField(db_column='isOffline', blank=True, null=True) audit_user_id = models.IntegerField(db_column='AuditUserID') class InsureePolicy(core_models.VersionedModel): id = models.AutoField(db_column='InsureePolicyID', primary_key=True) insuree = models.ForeignKey(Insuree, models.DO_NOTHING, db_column='InsureeId', related_name="insuree_policies") policy = models.ForeignKey("policy.Policy", models.DO_NOTHING, db_column='PolicyId', related_name="insuree_policies") enrollment_date = core.fields.DateField(db_column='EnrollmentDate', blank=True, null=True) start_date = core.fields.DateField(db_column='StartDate', blank=True, null=True) effective_date = core.fields.DateField(db_column='EffectiveDate', blank=True, null=True) expiry_date = core.fields.DateField(db_column='ExpiryDate', blank=True, null=True) offline = models.BooleanField(db_column='isOffline', blank=True, null=True) audit_user_id = models.IntegerField(db_column='AuditUserID') class Insuree(core_models.VersionedModel, core_models.ExtendableModel): id = models.AutoField(db_column='InsureeID', primary_key=True) uuid = models.CharField(db_column='InsureeUUID', max_length=36, default=uuid.uuid4, unique=True) family = models.ForeignKey(Family, models.DO_NOTHING, blank=True, null=True, db_column='FamilyID', related_name="members") chf_id = models.CharField(db_column='CHFID', max_length=12, blank=True, null=True) last_name = models.CharField(db_column='LastName', max_length=100) other_names = models.CharField(db_column='OtherNames', max_length=100) gender = models.ForeignKey(Gender, models.DO_NOTHING, db_column='Gender', blank=True, null=True, related_name='insurees') dob = core.fields.DateField(db_column='DOB') dead = models.BooleanField(db_column='Dead') dod = core.fields.DateField(db_column='DOD', … -
How to fetch the user saved model form data and return this to the user?
Scenario: A user has already completed a form. What's required: How do you return a completed model form in Views.py? I have followed a few guides on here such as this one with no success. Here is my shortened code containing the relevant sections: models.py APPROVAL_CHOICES = [ (None, 'Please select an option'), ("Yes", "Yes"), ("No", "No"), ] class Direct(models.Model): def __str__(self): return self.registered_company_name class Meta: verbose_name_plural = 'Company Direct Application' user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True") registered_company_name = models.CharField(max_length=250, verbose_name="Company") trading_name = models.CharField(max_length=250) registered_company_address = models.CharField(max_length=250) further_details_required = models.CharField(max_length=3, choices=APPROVAL_CHOICES, blank=True, verbose_name="Further Details Required") forms.py class CompanyDirectApplication(forms.ModelForm): class Meta: model = Direct fields = ["registered_company_name", "trading_name", "registered_company_address"] widgets = { "registered_company_name": TextInput(attrs={'class': 'form-control'}), "trading_name": TextInput(attrs={'class': 'form-control'}), "registered_company_address": TextInput(attrs={'class': 'form-control'}) } views.py if Direct.objects.filter(further_details_required="Yes", user=request.user).exists(): form = CompanyDirectApplication() form.instance.user = request.user return render(request, 'direct_application.html', {'form': form}) #otherwise render a blank model form else: form = CompanyDirectApplication() return render(request, 'direct_application.html', {'form': form}) The HTML template renders the form with a simple {{form.as_p}} -
How to solve "could not change permissions of directory "/var/lib/postgresql/data": Operation not permitted" error on Windows 10?
I am working on Windows 10 and running commands in git bash. I have following docker-compose.yml file: services: db: image: postgres:latest user: 1000:1000 volumes: - postgres-data:/var/lib/postgresql/data environment: - POSTGRES_USER='postgres' - POSTGRES_PASSWORD='postgres' ports: - 8000:8000 volumes: postgres-data: external: True I have created postgres-data volume in terminal by running docker volume create postgres-data. Then I type in docker-compose up. I have read in the Internet that I need to name a volume to run postgres. However there is still an error: initdb: error: could not change permissions of directory "/var/lib/postgresql/data": Operation not permitted On top of that, when the postgres db works on Docker, I want to add web component. I have been following a tutorial https://github.com/docker/awesome-compose/tree/master/official-documentation-samples/django/. What is missing in the docker-compose.yml? -
localhost doesn't work when I dockerize postgres with Django
My system is Ubuntu 22.04.1 LTS. I was going through the Django for professionals book and follow all line by line but somehow when i dockerize my django project with postgres it just doesn't run localhost properly, with sqlite all works fine. Dockerfile # Pull base image FROM python:3.10.6-slim-bullseye # Set environment variables ENV PIP_DISABLE_PIP_VERSION_CHECK 1 ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # Set work directory WORKDIR /code # Install dependencies COPY ./requirements.txt . RUN pip install -r requirements.txt # Copy project COPY . . docker-compose.yml version: "3.9" services: web: build: . command: python /code/manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - 8000:8000 depends_on: - db db: image: postgres:13 volumes: - postgres_data:/var/lib/postgresql/data/ environment: - "POSTGRES_HOST_AUTH_METHOD=trust" volumes: postgres_data: django.settings.py DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql", "NAME": "postgres", "USER": "postgres", "PASSWORD": "postgres", "HOST": "db", # set in docker-compose.yml "PORT": 5432, # default postgres port } } When I run docker-compose up that shows and seems like all must be fine, but somehow it just doesn't work: enter image description here And when I go to the localhost: enter image description here I spend a lot of hours of searching for info about this problem but nothing did help. I try even … -
Django xhtml2pdf
Does xhtml2pdf has bugs while using in Django 4.1.1? I am not able to display <pdf:pagenumber/> , nor <pdf:pagecount/> I am struggling to get my static files load too, I am getting SuspiciousFileOperation error. -
Django Form is not saving file to Database
views.py from .forms import palForm def add_form(request): if request.method!="POST": return HttpResponse("Method Not Allowed") else: form = palForm(request.POST, request.FILES) context = {"form": form} if form.is_valid(): form.save() messages.success(request,"Successfully Added") return render(request,"home/pal-form.html",context) else: messages.error(request,"Failed to Add") return render(request,"home/pal-form.html",context) forms.py from django import forms from .models import palabout class palForm(forms.ModelForm): class Meta: model=palabout fields =['fname','lname','dob','gender','profileImage'] models.py from pol.models import CustomUser from django.db import models class palabout(models.Model): user = models.ForeignKey(CustomUser, blank=True, null=True, on_delete=models.SET_NULL) profileImage = models.FileField() fname = models.CharField(max_length=30) lname = models.CharField(max_length=30) gender = models.CharField( max_length=1, choices=(('m', ('Male')), ('f', ('Female'))), blank=True, null=True) dob = models.DateField(max_length=8) .html <form role="form" action="{% url 'pal:add_form' %}" method="post" class="form-style-9",enctype="multipart/form-data"> {% csrf_token %} <div id="profile-container"> <image id="profileImage" src= "{{pic.url}}" style="width:100px" /></div> <input id="imageUpload" type="file" name="profile_photo" placeholder="Photo" required="" capture> <div class="container"> <ul class="personal-details"> <li> <ul class="column"> <li> <label for="fname"><strong>First Name </strong></label> <input type="text" id="fname" tabindex="1" /> </li> </ul> </li> <li> <ul class="column"> <li> <label for="lname"> <strong> Last Name </strong></label> <input type="text" id="lname" tabindex="1" /> </li> </ul> </li> <li> <ul class="column"> <li> <tr> <td for="gender"><strong>Sex:</strong></td> <td><input type="radio" name="gender" value="male" required>Male <input type="radio" name="gender" value="female">Female</td> <td>&nbsp;</td> </tr> </li> </ul> </li> <li> <ul class="column"> <li> <label for="dob"> <strong> Date of birth </strong></label> <input type="date" id="dob" value="YY-DD-MM" max="2040-01-01" > </li> </ul> </li> <ul class="column"> <li> {% … -
Django, Mezzanine: how to enable the functionality of creating a new post?
I got Django/Mezzanine up and running, I am able to login to the admin area and create new blog posts, the posts are shown on the blog, everything works. What I still cannot figure out: is how to allow any other user of my blog to create new blogposts while just browsing the site and not being an admin? Googled a lot, couldn't find an answer :( Would be very grateful for a clue! -
How to dispaly second api response in data table in vue.js
I want to show multiple api response in same datatable Already i am showing response from first api using props.item.name in datatable How to display response data from my second api in same datatable in vue.js