Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django utf-8 urls works on local but not working on production
i have a django project that on local the urls are ok and opens normally but on live server the utf-8 urls get 404 error here is my urls.py from django.conf import settings from django.conf.urls.static import static from django.urls import re_path from .views import law_list, law_detail, post_detail, category_detail app_name = 'book' urlpatterns = [ re_path(r'^$', law_list, name='law_list'), re_path(r'^(?P<law_id>\d+)/$', law_detail, name='law_detail'), re_path(r'^(?P<law_id>\d+)/(?P<law_slug>[-\w]*)/$', law_detail, name='law_detail_slug'), re_path(r'^categories/(?P<category_id>\d+)/$', category_detail, name='category_detail'), re_path(r'^categories/(?P<category_id>\d+)/(?P<category_slug>[-\w]*)/$', category_detail, name='category_detail_slug'), re_path(r'^posts/(?P<post_id>\d+)/$', post_detail, name='post_detail'), re_path(r'^posts/(?P<post_id>\d+)/(?P<post_slug>[-\w]*)/$', post_detail, name='post_detail_slug'), ] # Add the following lines to serve static files if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) thanks i tried to add allow_unicode = true to settings.py but it didnt work! -
For Django project (using VS Code), dynamic images not loading. Possible issue with baseURL
I've started a Django project based off of a tutorial. I didn't use the "Travello" files for the tutorial...set up something simple for myself. There's data defined on Views.py for title, description, images for courses. It should populate containers in a row on homepage. Everything is getting populated but the images are not coming up with this code: ```<img src="{{ baseURL }}/{{ course.image }}" alt="Course Pic" class="img-fluid"/>``` But in the same code I tested using static image and that image shows. I tried different images including same one as in dynamic code. All work in static version. But weirdly for static code the "alt" tag is what I have for dynamic. Here's the full loop: ``` {% for course in courses %} <div class="col-md-3 bg-aqua"> <div class="p-1"> <img src="{{ baseURL }}/{{ course.image }}" alt="Course Pic" class="img-fluid"/> {% if forloop.counter == 2 %} <img src="{% static 'home/img/Dalle1.jpg' %}" alt="Testing" class="img-fluid" /> {% endif %} </div> <div class="fs-3"> <span> {{ course.name }} </span> </div> <div> <span> {{ course.description }} </span><br/> <span> Start Course-1 $ {{ course.price }} </span><br/> </div> </div> {% endfor %} ``` The if/endif is what I added to test the static link and the image populates in 2nd column … -
Django. Can't get absolute url
I need a link to supplier_data for logged in supplier. Can't get it with any method. I get empty element. Model: class Supplier(models.Model): id = models.IntegerField(primary_key=True) company_name = models.OneToOneField(User, max_length=120, on_delete=models.CASCADE) currency = models.CharField('Currency', max_length=4) legal_form = models.CharField('Legal form', max_length=100, choices=legal_form_options, default='Sole proprietorship') accounting_standards = models.CharField('Accounting standards', max_length=100) owner_structure = models.CharField('Owner structure', max_length=100) industry_sector = models.CharField('Industry sector', max_length=100, choices=industry_sector_options, default='Advertising') date_of_establishment = models.DateField('Date of establishment', default=date.today) start_up = models.CharField('Start-up', choices=start_up_options, default='No', max_length=4) email_address = models.EmailField('Email address') web = models.URLField('Website address') def get_absolute_url(self): return reverse('supplier_data', args=[self.id]) View: def all_suppliers(request): supplier_list = Supplier.objects.all() return render(request, 'all_suppliers.html',{'supplier_list': supplier_list}) def supplier_data(request, id): supplier_list = get_object_or_404(Supplier, pk=id) return render(request, 'all_suppliers.html',{'supplier_list': supplier_list}) Url: path('supplier_data/<int:id>', views.supplier_data, name="supplier_data"), Html: {% for supplier in supplier_list %} <a id=link href="{% url 'supplier_data' supplier.id %}">Supplier data</a> {%endfor%} I spent about one week trying with get_absolute_url method and without it... many things... Thanks for taking a look at this. -
Graphs are not sorting according to Dash table
I'm creating a Dash table where data will be shown according to the date selected by a date picker. There will be several bar figures below the table which will be updated according to the table. I've followed the official documentation of sorting, and filtering examples of Dash table. But for some reason, the figures are not updating properly when the table is updated (e.g. sorting, filtering, etc.). Here's the code: from dash import dash_table, dcc, html from datetime import date from dash.dependencies import Input, Output from django_plotly_dash import DjangoDash import dash_bootstrap_components as dbc import pandas as pd df = pd.read_csv('owid-covid-data.csv') df = df[['location', 'new_cases', 'new_cases_per_million', 'total_cases', 'total_cases_per_million', 'continent', 'date']].copy() df['id'] = df['location'] df.set_index('id', inplace=True, drop=False) app = DjangoDash('Cases', external_stylesheets=[dbc.themes.LUX]) selected_date = '2021-01-01' initial_date = df[df['date'] == selected_date] app.layout = html.Div(className='w-75 mb-3', children= [ dbc.Card( [ dbc.CardBody( dcc.DatePickerSingle( id='date-picker', min_date_allowed=date(2020, 1, 1), max_date_allowed=date(2023, 3, 1), initial_visible_month=date(2021, 1, 1), month_format='MMM D, YYYY', display_format='MMM D, YYYY', date=date(2021, 1, 1), ), ), dbc.CardBody( [ dash_table.DataTable( id='casetable-row-ids', columns=[ {'name': i, 'id': i, 'deletable': True} for i in initial_date.columns if i != 'id' ], data=initial_date.to_dict('records'), editable=False, filter_action="native", sort_action="native", sort_mode='multi', row_selectable='multi', selected_rows=[], page_action='native', page_current= 0, page_size= 10, style_as_list_view=True, style_cell={'padding': '5px'}, style_header={ 'backgroundColor': 'black', 'color': 'white', 'fontWeight': … -
django queryset use .values for the foreign key field
I have a model which the creator field is a forign key from user table : class CompanyTemplateMessage(models.Model): name = models.CharField(max_length=100, blank=True, null=True) subject = models.CharField(max_length=256) company = models.ForeignKey('Company', on_delete=models.CASCADE, related_name='company_template') text = models.TextField() created_at = models.DateTimeField(auto_now=True, blank=True, null=True) creator = models.ForeignKey( 'user.User', null=True, blank=True, on_delete=models.SET_NULL, related_name='user_template_message', ) User: class User(AbstractBaseUser, PermissionsMixin): is_active = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) email = models.EmailField(max_length=255, unique=True) phone = PhoneNumberField(unique=True, null=True, blank=True) first_name = models.CharField(max_length=100, null=True, blank=True) last_name = models.CharField(max_length=100, null=True, blank=True) join_date = models.DateTimeField(auto_now_add=True) companies = models.ManyToManyField( 'company.Company', related_name='members', blank=True, ) USERNAME_FIELD = 'email' def __str__(self): return self.email i use this queryset and value() parameter to determine which field is chosen to show def get_queryset(self): company_code = self.kwargs.get('company_code') company_template_objs = CompanyTemplateMessage.objects.filter(company__code=company_code).values( 'name', 'created_at', 'creator') return company_template_objs when i dont use values() it works properly and shows the creator field but when i choose creator in the fields , it shows this error : 'int' object has no attribute 'pk' and when i use something else like : 'creator__email' or 'creator__id' the creator field returns null value while it is filled by a user what should i use for this field to show the user value ? -
Django with Postgresql on MacOS. FATAL error: "Database does not exist"
Trying to get Django to work with Postgres instead of sqlite. Created the database (ytptest1). It exists. It has no tables, thus cannot migrate. kak=# \c ytptest1 You are now connected to database "ytptest1" as user "kak". In settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', # 'NAME': BASE_DIR / 'ytptest1', # 'NAME': str(BASE_DIR / 'ytptest1'), 'NAME': str('/Users/kak/Library/Application Support/Postgres/var-15/ytptest1'), # 'NAME': '/Users/kak/Library/Application Support/Postgres/var-15/ytptest1', 'USER': 'kak', 'HOST': 'localhost', 'PORT': '5432', } } % python manage.py runserver . . . File "/Users/kak/Library/Python/3.10/lib/python/site-packages/psycopg2/__init__.py", line 122, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) django.db.utils.OperationalError: connection to server at "localhost" (::1), port 5432 failed: FATAL: database "/Users/kak/Library/Application Support/Postgres/var-15/ytptest1" does not exist I've tried more things can I can list. I finally figured out that the Django DB's are stored in /Users/kak/Library/Application Support/Postgres/var-15 Very new to this universe. ( I Thanks -
How to take input as audio using django template?
<input type="text" x-webkit-speech name="prompt" value="{{prompt}} enter image description here I'm not able to get audio as an input as shown in image. <input type="text" x-webkit-speech name="prompt" value="{{prompt}} i have tried this but its not working. -
Install mod-wsgi in a poetry virtual environment
I have a django app. I've created a poetry virtual environment to manage dependencies. This app runs on python 3.10. My pyproject.toml looks like this: [tool.poetry] name = "django_manager" version = "0.1.0" description = "A Game manager" authors = [""] [tool.poetry.dependencies] python = "^3.10" Django = "^4.1.7" beautifulsoup4 = "^4.12.0" requests = "^2.28.2" pillow = "^9.4.0" [tool.poetry.dev-dependencies] [build-system] requires = ["poetry-core>=1.0.0"] build-backend = "poetry.core.masonry.api" Now I'm trying to move the app to a CentOS VM, I copied the whole project folder to /var/www/html/GameManager and inside it run poetry install then poetry shell Now if I do python -V I get Python 3.10.4 so that side works OK. If I try to serve the app with apache: /etc/httpd/conf.d/gamemanager.com.conf <VirtualHost *:80> ServerName gamemanager.com ServerAlias *.gamemanager.com Redirect permanent / https://gamemanager.com/ </VirtualHost> <VirtualHost *:443> ServerName gamemanager.com ServerAlias *.gamemanager.com <Directory /var/www/html/GameManager> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess gamemanager.com display-name=gamemanager user=user group=user_group processes=2 threads=15 WSGIScriptAlias / /var/www/html/GameManager/app/wsgi.py WSGIProcessGroup gamemanager.com TimeOut 3600 LogLevel info ErrorLog "/var/log/httpd/gamemanager.com-error.log" CustomLog "/var/log/httpd/gamemanager.com-access.log" common </VirtualHost> I see in gamemanager.com-error.log an expception executing wsgi.py, probably because that it's trying to use /home/user/.local/lib/python3.6/site-packages/django/conf/__init__.py So right now I'm trying to fix that by installing mod-wsgi inside the venv with python3.10 and pip3.10. But … -
How to fill GraphQL ENUM from Django QuerySet?
In my graphql api for Revenue field use Currency enum from constant. from graphene import Enum CurrencyEnum = Enum('Currency', CURRENCY_CHOICES) class RevenueMetrics: revenue = graphene.Float(description='Revenue', currency=CurrencyEnum(required=True)) ... But now CURRENCY_CHOICES constant has moved to DB (Currency table). There are good reasons for this (not related to graphql). I can't figure out how to create CurrencyEnum class with dynamic filling from QuerySet of Currency table. Have an up-to-date set of Currencies.(I suppose that there is another question in the restructuring of the scheme). graphene==2.1.8 graphene-django==2.13.0 I tried like this: def dcm(): return Enum('Currency', tuple((c, c) for c in Currency.objects.values_list('code', flat=True))) revenue = graphene.Float(description='Revenue', currency=dcm()(required=True)) But it still requires a schema regeneration. -
How to get all {% include ... %} and {% extend ... %} tags before/after render Django template?
Using Django, I have html template "name.html" with content like: {% extends "some.html" %} {% for page in pages %} {% include page.html_template_path %} {% endfor %} This will include template wich path is stored in page.html_template_path. Important part is: every html template may extend/include another html templates inside itself. How to recursivly get all templates (path to every template) loaded via {% extend ... %} and {% include %} tags ? RegEx is not solution (path to template may be inside variable/context/{% for %} tag etc I found https://github.com/edoburu/django-template-analyzer/blob/master/template_analyzer/djangoanalyzer.py but it cant properly treat nested {% for %} tags etc -
How can I take the second row from the end from the table of the Django model?
I'm trying to get the second and third rows from the end of the model table. I know how to get the last row. But I need - (last - 1) and (last - 2) rows alternately. How can you get them? qs_select = Model.objects.all() last_row = qs_select.last() -
Catching IntegrityError vs filtering before object creation?
I have a development task. And at some point of this task, I need to create DB objects with a function which takes multiple json objects returning from third-party client request. I am for looping through json objects and calling _create_db_object method to create them one-by-one. Sample model: class MyObject(models.Model): some_unique_field = models.CharField() ... ... The function I use to create objects in DB: def _create_db_object(dict_: dict[str, str]) -> None: try: return MyObject.objects.create(...) except IntegrityError as e: continue My question is: "Would it be better if I used something like this instead of try except?" def _create_db_object(dict_: dict[str, str]) -> None: if MyObject.objects.filter(some_unique_field=dict_["unique_field"]): continue return MyObject.objects.create(...) Which function would be better and why? -
How to assign tags to a post using a form?
I have the following code below, when adding a Post, everything is saved and assigned except for tags that seem to have not even been written. How can I assign them? Thanks in advance for the hints models.py class Post(models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique_for_date='publish') author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts') body = models.TextField() publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft') object = models.Manager() published = PublishedManager() tags = TaggableManager() def get_absolute_url(self): return reverse('blog:post_detail', args=[self.publish.year, self.publish.strftime('%m'), self.publish.strftime('%d'), self.slug]) class Meta: ordering = ('-publish',) def __str__(self): return self.title forms.py class PostAdd(forms.ModelForm): class Meta: model=Post fields=('title', 'body', 'tags','status') views.py def AddPost(request): post_form=PostAdd(request.POST) if post_form.is_valid(): form=post_form.save(commit=False) form.slug=slugify(form.title) form.author=request.user form.save() context={ 'post_form':post_form, } return render(request, 'administration/addpost.html', context) I tried to do something with the documentation but it threw errors. -
How can I work together with my team mate?
I'm making a project with my team members using python-django. I want to know how to use git and docker to collaborate? My version: Column A Column B python 3.8 docker images python:3.11.1 Here’s the code to our dockerfile: FROM python:3.11.1 ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 RUN mkdir /challenge ADD . /challenge WORKDIR /challenge RUN python -m pip install --upgrade pip RUN pip install -r requirments.txt EXPOSE 8000 Here's the code to our docker-compose.yml: version: '3.8' services: web: build: context: . dockerfile: Dockerfile command: sh -c "python3 manage.py runserver 0:8000" volumes: - .:/challenge ports: - "8000:8000" After working with my members, we tried to put docker's images and django files on the git after docker-compose up --build in the container. But I think this method is the same as working in my local environment and putting it on the git. Here's the desired result: I want to know another way to collaborate using Docker, not the method I tried. If there's any another way besides the solution, I'd like you to let me know. -
Template extends base.html but doesn't get the content of the sidebar
I have base_planner.html that contains a navbar and a sidebar. When I extend this base in any other template, both the navbar and sidebar are inherited, but the sidebar doesn't have any content that must be there. And I'm not getting any errors. The only template that has the sidebar content is the home page, which is merely a ListView html page (projectsmodel_list.html) containing one row: {% extends 'app_planner\base_planner.html' %} Here is my views.py (I want TestView to inherit the sidebar content): class ProjectListView(LoginRequiredMixin, generic.edit.FormMixin, generic.ListView): context_object_name = 'project_list' model = ProjectsModel form_class = ProjectsForm success_url = reverse_lazy('app_planner:planner_home') def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['create_project_form'] = ProjectsForm() return context def form_valid(self, form): project_name = form.cleaned_data['project_name'] project_author = self.request.user create_project_form_item = ProjectsModel(project_name=project_name, project_author=project_author) create_project_form_item.save() return super().form_valid(form) def form_invalid(self, form): return super().form_invalid(form) def post(self, request, *args, **kwargs): self.object_list = self.get_queryset() form = self.get_form() if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) class TestView(generic.TemplateView): template_name = 'app_planner/test.html' Here is my urls.py: app_name = 'app_planner' urlpatterns = [ path('', views.ProjectListView.as_view(), name='planner_home'), path('test/', views.TestView.as_view(), name='test'), ] Here is the body of my base_planner.html: {% if user.is_authenticated %} <nav id='navbar' class="navbar navbar-expand-lg bg-white"> <div class="container-fluid"> <a id='logo' class="navbar-brand" href="{% url 'app_planner:planner_home' %}"><h3><b><span style="color:#FC5E5E;">Savvy</span> Planner</b></h3></a> <button class="navbar-toggler" type="button" … -
Insert multiple list in database using python django
Im confused on how can I insert multiple list bycolumn using a loop, let say the output what I want in database is something like this name percentage is_fixed_amount PWD 20 0 Senior 20 0 OPD 6 0 Corporators 20 0 Special 1 What I've tried but it's insert multiple data and it didn't reflect the actual data in database, Can somebody knows the solution? I appreciate any reply. discount = ['PWD','Senior Citizen','OPD','Corporators','Special'] discount_percentage = ['20','20','6','20',''] fixed_amount = [False,False,False,False,True] for dis in discount: for per in discount_percentage: for fix in fixed_amount: discount_val = Discounts(name=dis,percentage = per,is_fixed_amount =fix) discount_val.save() -
Dealing with circular dependencies on API endpoints
I am writing a new Django app with Django Ninja, to build an API. There is an app of "users" that contains an Organization model and a User model (that belongs to an organization). There is another app of "posts" that, for now, only has a Post model, that belongs to a user and an organization. So the "posts" API router is mounted on "/api/v1/organizations/{organization_id}/posts", and I can perform a complete CRUD over this. The problem comes when I want to retrieve the posts of an user. Suppose someone enters to a profile page, and then you want to get all data: user data, organization, posts count, all posts, etc. The more intuitive response would be like: "/api/v1/organizations/{organization_id}/users/xxxx" that returns all of this. But this means that the "users" app should know about "posts". And it introduces a circular dependency. What do you think? Have you been through the same problem? The above answer says it! -
Why I am not saving a wav file but .336Z file in the database after sending audio blob to server Django?
I am currently making a recording application with Recorder.js with Django. After pressing the 'Upload' button, it will send the audio blob to the server side, that is Django, and save in the database. I am trying to save an audio file with wav format into database in Django but it saves a .336Z file in the database. Why I can't save in wav file? function createDownloadLink(blob) { var url = URL.createObjectURL(blob); var au = document.createElement('audio'); var li = document.createElement('li'); var link = document.createElement('a'); //name of .wav file to use during upload and download (without extendion) var filename = new Date().toISOString(); //add controls to the <audio> element au.controls = true; au.src = url; //save to disk link link.href = url; link.download = filename+".wav"; //download forces the browser to donwload the file using the filename link.innerHTML = "Save to disk"; //add the new audio element to li li.appendChild(au); //add the filename to the li li.appendChild(document.createTextNode(filename+".wav ")) //add the save to disk link to li li.appendChild(link); //upload link var upload = document.createElement('a'); upload.href="#"; upload.innerHTML = "Upload"; upload.addEventListener("click", function(event){ var xhr=new XMLHttpRequest(); xhr.onload=function(e) { if(this.readyState === 4) { console.log("Server returned: ",e.target.responseText); } }; var fd=new FormData(); fd.append("audio_data",blob, filename.wav); xhr.open("POST","/save-audio/",true); xhr.send(fd); }) li.appendChild(document.createTextNode (" … -
Is there a way to skip over table when it hasn't been filled with value
I'm still learning Django python and trying to create webapp that display students scores each semester. And I got this error that says Grades2 matching query does not exist.. Because I create separate class for each semester, and for this student I intentionally left second semester's score empty because in they haven't reach that semester yet. with this models: from django.db import models # Create your models here. class Students(models.Model): clas = models.CharField(max_length=6, default='no data') nim = models.IntegerField(primary_key=True) name = models.CharField(max_length=50) year = models.IntegerField() def __str__(self): return f"{self.nim} in class {self.clas}" class Grades1(models.Model): nim = models.ForeignKey(Students, on_delete=models.CASCADE) biology = models.IntegerField(default=0) math = models.IntegerField(default=0) history = models.IntegerField(default=0) def __str__(self): return f"{self.nim.name} with scores \n biology = {self.biology} \n math = {self.math} \n history = {self.history}" class Grades2(models.Model): nim = models.ForeignKey(Students, on_delete=models.CASCADE) biology = models.IntegerField(default=0) math = models.IntegerField(default=0) history = models.IntegerField(default=0) def __str__(self): return f"{self.nim.name} with scores \n biology = {self.biology} \n math = {self.math} \n history = {self.history}" class Achievement(models.Model): nim = models.ForeignKey(Students, on_delete=models.CASCADE) ach = models.CharField(max_length=50) scales = [ ('INT', 'INTERNATIONAL'), ('NA', 'NATIONAL'), ('RE', 'REGIONAL'), ('LO', 'LOCAL'), ('DE', 'DEED') ] scale = models.CharField( max_length=3, choices=scales, default='DE' ) def __str__(self): if self.ach is not None: return f"{self.nim.name} has achieve {self.ach}" else … -
Error: This field is required. React Form Post To Django Rest Framework API with React RTK Query
I have tried many ways to POST data to my backend which is Django Rest Framework. I kept receiving the error that "This field is required." although my console shows that all the fields are populated. Snippets of my code are below: import React, { useEffect, useState } from "react"; import { useNavigate } from "react-router-dom"; import { money } from "../data"; import { CustomButton, FormField, Loader } from "../components"; import { useCreateCampaignMutation } from "../utils/userAuthApi"; import { getToken } from "../utils/index"; const CreateCampaign = () => { const navigate = useNavigate(); const { access_token } = getToken(); const [createCampaign, { isLoading }] = useCreateCampaignMutation(); const [form, setForm] = useState({ title: "", description: "", target: "", deadline: "", }); const handleFormFieldChange = (fieldName, e) => { setForm({ ...form, [fieldName]: e.target.value }); console.log(form); }; const handleSubmit = async (e) => { e.preventDefault(); console.log({ form, access_token }); const res = await createCampaign({ form, access_token }); if (res.data) { console.log(res.data); } else { console.log(res.error.data.errors); } }; return ( <div className="bg-[#1c1c24] flex justify-center items-center flex-col rounded-[10px] sm:p-10 p-4"> {isLoading && <Loader />} <div className="flex justify-center items-center p-[16px] sm:min-w-[380px] bg-[#3a3a43] rounded-[10px]"> <h1 className="font-epilogue font-bold sm:text-[25px] text-[18px] leading-[38px] text-white"> Start a Campaign </h1> </div> <form onSubmit={handleSubmit} … -
Problems with {% extends 'base.html' %} command in Django
I have been bothering so long with this problem. I don't where I have made a mistake. Been sitting over this for 1h.... Someone, please help. It's home.html file: {% extends 'base.html' %} {% block head %} Home {% endblock %} {% block body %} <h1>HomeHome</h1> {% endblock %} And it's base.html : <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-aFq/bzH65dt+w6FI2ooMVUpc+21e0SRygnTpmBvdBgSdnuTN7QbdgL+OapgHtvPp" crossorigin="anonymous"> {% block head %} Base {% endblock %} {% block body %} <h1>BaseBase</h1> {% endblock %} </body> My page shows base.html with no changes - it doesn't use {% extends 'base.html' %} thank you :) -
Gmail removing hyperlinks from email. Why?
My application is expected to send email verification link to user. When I open such an email in Gmail, the links are not shown, Gmail removes them. If I select [Show original] option, I can see that the links are there. Why is it so? How can I fix this ? Note: I'm on development server. Displayed Email: Hi from Team! You just subscribed to our newsletter. Please click the link below in order to confirm: Thank You! Team Original Email: Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit Hi from Team! You just subscribed to our newsletter. Please click the link below in order to confirm: http://127.0.0.1:8000/newsletter/verify_email/MTQ/bmq8o8-15cab7bf32186aab16c2c086e9beaec3/ Thank You! Team Thanks! -
Why django form is submitted but the valued is null in the database?
We have a model called Column, and we want user to be able to create Table model based on Column model fields he created, we successfully do that using the method below: def create_table(request): columns = Column.objects.filter(user=request.user) fields = {} for column in columns: if column.field_type.data_type == 'number': fields[column.name] = forms.IntegerField() elif column.field_type.data_type == 'character': fields[column.name] = forms.CharField(max_length=20) elif column.field_type.data_type == 'decimal': fields[column.name] = forms.DecimalField(max_digits=20, decimal_places=10) elif column.field_type.data_type == 'image': fields[column.name] = forms.ImageField() elif column.field_type.data_type == 'boolean': fields[column.name] = forms.BooleanField() elif column.field_type.data_type == 'date': fields[column.name] = forms.DateField() TableForm = type('TableForm', (forms.Form,), fields) if request.method == 'POST': form = TableForm(request.POST, request.FILES) if form.is_valid(): table = Table() table.user = user=request.user for column in columns: setattr(table, column.name, form.cleaned_data[column.name]) table.save() return redirect('Table') else: form = TableForm() return render (request, 'create_table.html', {'form':form}) As you can see our view, our users can create Table model based on a Column model fields they created, but when the form is submitted, the value created from TableForm is null in the database, instead of showing us the object of the Table model created by a user, it is shown nothing, how can we solve this problem? the models: class Column(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) list_of_album = models.ForeignKey(Album, on_delete=models.CASCADE) name … -
My cpanel doesn’t have the “setup python app”
I want to deploy my Django application using cpanel, but my problem is that my cpanel does not have the setup python application option in its software section, please help me, this is my first project, I don't want to fail in this project. -
Django cannot query data from another table by using OneToOneField
I create django model like this which api_key of Setting table is OneToOneField to Key table. class Key(models.Model): api_key=models.CharField(max_length=100,unique=True) api_key_name=models.CharField(max_length=100) def __str__(self): return self.api_key class Setting(models.Model): api_key=models.OneToOneField(DeviceKey,on_delete=models.CASCADE) field_en=models.BooleanField(default=False) def __str__(self): return str(self.api_key) I add data to table Key like this. api_key="abc1" api_key_name="test" In views.py I use key to query like this code. def keyForm(request): key="abc1" data, created = Setting.objects.get_or_create(api_key__api_key=key) key = Key.objects.get(api_key=key) data = {'setting':data, 'key':key} return render(request,'key_form.html', data) Data in table Key It show error like this. How to fix it? MySQLdb._exceptions.OperationalError: (1048, "Column 'api_key_id' cannot be null") IntegrityError at /keyForm (1048, "Column 'api_key_id' cannot be null")