Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
upload_to attribute giving wrong path
upload_to attribute isn't working correctly. I have no idea what's causing this, instead of uploading a file I'm getting a SuspiciousFileOperation exception. The base path component stated in the exception is correct but joined path is not correct as it should just be 'img/posts'. I'm looking for a reason that's causing this. models.py thumbnail = models.FileField(upload_to='img/posts') Exception value The joined path (/media/tb1.jpg) is located outside of the base path component (/home/user/Documents/project/project/media) -
encoded html reportlab python
I am creating a pdf with reportlab in python I have the following problem one of the data has to show is type longText because html strings have been saved, as I decode it to show it in my pdf if the data arrives as follows, sometimes html will come tables and would like to keep them. I do the following but it still looks the same comentatios = '<p><br></p><table class="table table-bordered"><tbody><tr><td>dato 1</td><td>dato 2</td></tr><tr><td>dato 3</td><td>dato 4</td></tr></tbody></table><p><br></p>' from six.moves.html_parser import HTMLParser h = HTMLParser() data = [][enter image description here][1] data.append(['Comentarios',h.unescape(comentarios),'','']) t4 = Table( data, ) -
Why does I get either NoReverseMatch or FieldError
I am working on a project, and want to create a report on a film. (That it doesn´t exist) At the moment I only get error when I try to go to either film// or film//report. Can anybody help me? **models.py** class Report(models.Model): title = models.CharField(default="", max_length=100) comment = models.TextField(default="") reporter = models.ForeignKey(User, on_delete=models.CASCADE, related_name="Reporter") # receiver = models.ForeignKey( # User, on_delete=models.CASCADE, related_name="Receiver" # ) reports = models.ForeignKey(Film, on_delete=models.CASCADE) def __str__(self): # pragma: no cover return f"{self.reporter.username} reports {self.reports.title}" **urls.py** urlpatterns = [ path("", views.films_view, name="board-home"), path("film/add", FilmAddView.as_view(), name="film-add"), path("film/<int:pk>/", FilmDetailView.as_view(), name="film-detail"), path("film/<int:pk>/report", FilmReport.as_view(), name="film-report") ] **views.py** class FilmReport(LoginRequiredMixin, UpdateView): model = Report fields = ["title", "reported"] # def __str__(self): # return self.title def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) This should be the page where I can click on "Report", and then be redirected to a report page. **film_detail.html** {% extends "board/base.html" %} {% block content %} <article class="media content-section"> <img class="rounded-circle film-img" src="/media/{{object.poster}}"> <!-- Mulighet for å ha en "add review"-knapp på siden der hvor filmene vises. --> <a href=" {% url 'film-add' %}" class="waves-effect waves-light green btn"><i class="material-icons right">rate_review</i>add review</a> <a href=" {% url 'film-report' %}" class="waves-effect waves-light red darken-4"><i class="material-icons right">report</i>report</a> <!-- <a onclick="myFunction()" class="waves-effect … -
Django choices that change automatically based on male/female checkboxes. Categories will be displayed based on the gender choice
I have searched on the internet but did not find anything suitable. I want to have a model that will have a a set of choices of categories which will change based on whether the male or female checkbox/choice (whichever is more appropriate) was selected. In models.py, class MyModel(models.Model): MALE_CATEGORIES = { ('Male Category 1', 'Male Category 1'), ('Male Category 2', 'Male Category 2'), ('Male Category 3', 'Male Category 3'), } FEMALE_CATEGORIES = { ('Female Category 1', 'Female Category 1'), ('Female Category 2', 'Female Category 2'), ('Female Category 3', 'Female Category 3'), } # Male/Female option as either choices or checkboxes depending on whichever one is more suitable gender = # Either MALE_CATEGORIES or FEMALE_CATEGORIES # Depending on gender categories = models.CharField(max_length=18, choices=) In forms.py, class MyModelForm(forms.ModelForm): class Meta: model = MyModel fields = [ 'gender', 'categories', ] -
Can't create PostGis extension on PostgreSQL database?
I'm trying to create a postgis extension on my PostgreSQL database for a Django project, but when I run CREATE EXTENSION postgis I get this error: ERROR: extension "postgis" has no installation script nor update path for version "3.0.1" I installed all the dependencies with Homebrew on macOS, and this database is not on the 'postgres' user, it's on my own superuser. Homebrew Dependency Versions postgresql@12.2 postgis@3.0.1 gdal@2.4.4 geos@3.8.1 proj@7.0.0 Any help is appreciated!! Been working on this issue for the last week. -
Reverse for 'post_detail' not found. 'post_detail' is not a valid view function or pattern name
I am trying to create a new post and when I click on the save button, I get error as stated in the image. I am not able to understand the error and where to look for it. I am new at django. Please help! Main-urls.py file: from django.contrib import admin from django.urls import path from django.conf.urls import url, include from django.contrib.auth import views urlpatterns = [ path('admin/', admin.site.urls), path('',include('blog_app.urls', namespace='blog_app')), url(r'^accounts/',include('accounts.urls', namespace='accounts')), #path('accounts/login/', views.LoginView.as_view(template_name='blog_app/login.html'),name='login'), #path('accounts/logout/',views.LogoutView.as_view(template_name='blog_app/base.html'),name='logout'), ] blog_app-urls.py file: from django.conf.urls import url from blog_app import views from django.urls import path app_name = 'blog_app' urlpatterns = [ url(r'^$', views.PostListView.as_view(),name='post_list'), url(r'^about/$', views.AboutView.as_view(),name='about'), url(r'^post/(?P<pk>\d+)$', views.PostDetailView.as_view(),name='post_detail'), url(r'^post/new/$', views.CreatePostView.as_view(),name='new_post'), url(r'^post/(?P<pk>\d+)/edit/$', views.UpdatePostView.as_view(),name='edit_post'), url(r'^drafts/$', views.DraftListView.as_view(),name='draft_post_list'), url(r'^post/(?P<pk>\d+)/remove/$', views.DeletePostView.as_view(),name='delete_post'), # url(r'^post/(?P<pk>\d+)/remove/$', views.post_remove,name='delete_post'), url(r'^post/(?P<pk>\d+)/publish/$', views.post_publish, name='post_publish'), url(r'^post/(?P<pk>\d+)/comment/$', views.add_comment_to_post, name='add_comment_to_post'), url(r'^comment/(?P<pk>\d+)/approve/$', views.comment_approve, name='comment_approve'), url(r'^comment/(?P<pk>\d+)/remove/$', views.comment_remove, name='comment_remove'), # path('register/',views.register,name='register'), ] blog_app-views.py file: from django.shortcuts import render,get_object_or_404,redirect from django.utils import timezone from django.contrib.auth.decorators import login_required from blog_app.models import Post,Comment from blog_app.forms import PostForm,CommentForm from django.contrib.auth.forms import UserCreationForm, AuthenticationForm from django.views.generic import (TemplateView,ListView,DetailView,CreateView, UpdateView,DeleteView) from django.urls import reverse_lazy from django.contrib.auth.mixins import LoginRequiredMixin from django.contrib.auth.forms import UserCreationForm from django.contrib.auth import login,logout,authenticate class AboutView(TemplateView): template_name = 'about.html' class PostListView(ListView): model = Post def get_queryset(self): return Post.objects.filter(publish_date__lte = timezone.now()).order_by('-publish_date') class PostDetailView(DetailView): model = Post class CreatePostView(LoginRequiredMixin,CreateView): … -
modelForm got an unexpected argument 'initial'
modelForm got an unexpected argument 'initial' I am getting this error. please can anyone explain how to solve this ? Here is my model.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, default=None) StudentID = models.CharField(max_length=8, blank=False, unique=True) Branch = models.CharField(max_length=255,choices=Departments,default="CSE") def __str__(self): return f'{self.user.username} Profile' class complaintForm(models.Model): user = models.ForeignKey(Profile, on_delete=models.CASCADE) category = models.CharField(max_length=255,choices=complaints,default='Mess') title = models.CharField(max_length=20) content = models.CharField(max_length=100) image = models.ImageField(upload_to='complaint_pics/') def __str__(self): return self.title form.py class complaintForm(forms.ModelForm): class Meta: model = complaintForm fields = ['title','content','image',] views.py class CreateComplaintView(CreateView): model = complaintForm form_class = complaintForm template_name = 'user/post_complaint.html' success_url = 'success' -
Django - Which model field for dir path?
I need to define a field in my Model, which is supposed to host a valid dir path on server-side. Basically just a string which should be: 1) a formally valid unix-like dir path 2) an existing dir path Tried with FilePathField with options allow_files=False, allow_folders=True . But when I try to create a new instance of the model from the django admin CRUD, I'm getting an error claiming that the initial value of the field (which is by default an empty string) is a not existing path... I have a feeling this is not the right way. Maybe another field type could be more suitable? Maybe it should be just a simple string? (in this case, shall I be able to define correctly the required validators?) Thanks for any hint, Thomas -
chage choice_field if the name starts with A Django
thanks for your time: i'd like to take one choice option off if the name of the People starts with letter 'a': basically if People.nome or People.user starts with letter 'A' i'd like to take the choice (2,'GATO') off. is there a way to do that or should i try another aproach besides a ChoiceField models.py User = get_user_model() class People(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) nome = models.CharField(max_length=200) birthday = models.DateField() cpf = models.CharField(max_length=11, validators=[RegexValidator(r'^\d{1,10}$')]) def __str__(self): return '%s' % (self.nome) field_choices1 = [ (1, 'CACHORRO'), (2, 'GATO'), (3, 'OUTRO') ] field_choices2 = [ (1, 'CACHORRO'), (3, 'OUTRO') ] def field_choice(): one = People.user slug = slugify(one) big = slug.upper() initial_big = big[0] if initial_big == 'A': return field_choices1 else: return field_choices2 class Pets(models.Model): pessoa = models.ForeignKey(People, on_delete=models.CASCADE) nome = models.CharField(max_length=150) custo = models.DecimalField(max_digits=7, decimal_places=2) tipo = models.SmallIntegerField(choices=field_choice()) forms.py class PetForm(forms.ModelForm): field_choices = [ (1, 'CACHORRO'), (2, 'GATO'), (3, 'OUTRO'), ] name = forms.CharField(max_length=100) tipo = forms.ChoiceField(choices=field_choices) custo = forms.DecimalField(max_digits=7, decimal_places=2) class Meta: prefix = 'animal' model = Animal fields = ('name', 'tipo', 'custo') def clean(self): people_name = self.People.nome upper = people_name.upper() if upper[0] == 'A': Pets.tipo != 2 i've tried o couple of ways: the models.py try returns always … -
How to create unique user folders for different users in django
I have two a user and project models. I want to create a unique folder for each project for a user. In this scenario, whenever the creates a new project, a new project folder is added to the user's folder. So, I want something like this: User_1 Project_1 Project_2 User_2 Project_1 Project_2 Project_3 I am aware of shuntil, I would like to make user that the folder name for each user folder is unique for the user. The name of the project Currently, I have hard coded the following: In my settings.py BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) USER_DIR=os.path.join(BASE_DIR, 'User_1/') In another.py I have: settings.ONTOLOGY_DIR + "Project_1/testing.txt" The scenario, I would have to change the USER_DIR path to User_2 if I want the files/folders for user2. Now, instead of hard coding to get the testing.txt. I want to do this dynamically get the testing.txt based on the user that is authenticated. -
Pass form validation errors back to Wagtail Page template
I have a Wagtail Page model that I am using to render a form. I have overridden the get_context and serve methods to pass in the form as page context and then validate it when receiving a POST request: class RegistrationPage(Page): ... def get_context(self, request, *args, **kwargs): # Avoid circular dependency from registration.forms import RegistrationForm context = super().get_context(request) context["form"] = RegistrationForm return context def serve(self, request, *args, **kwargs): # Avoid circular dependency from registration.forms import RegistrationForm if request.method == "POST": registration_form = RegistrationForm(request.POST) if registration_form.is_valid(): registration = registration_form.save() return redirect("/") else: # How do I return the form with validation errors? else: return super().serve(request) Question: When the form validation fails, how do I pass the form back to the template so the user can see the validation errors? -
3 blocks link together base, category and article
hello I tried to make a block in another block more exactly basic block (fixed) block category (variable) block article (variable) but the problem the part of the category that I would like to leave it in the block article disappears which is normal but I don't want it to be erased you have a solution to offer me -
Django Timezones with offsite server
I have a django project running on a digital ocean server in Toronto Canada. I have clients in Winnipeg and Toronto both using the application. I am confused on the correct method of storing and retrieving dates using Django. In my settings.py I have: TIME_ZONE = 'America/Toronto' USE_I18N = True USE_L10N = True USE_TZ = True And in my various python code when I am storing dates in the project I use: from django.utils import timezone from django.utils.timezone import utc myTimeStamp = timezone.localtime(timezone.now()) Then to show the time in my Django Templates I use: {% load tz %} {{myTimeStamp|localtime}} When I view this template in Winnipeg, the time is wrong by 1 hour (it is showing Toronto time) The easy fix is to change the settings.py to TIME_ZONE = 'America/Winnipeg but then I would assume people in Toronto would be seeing the wrong time (Winnipeg time). The challenge I'm having is that people are writing to the database from multiple timezones and reviewing data from multiple timezones, and I'm confused as heck as you can tell! Any help is appreciated Where am I going wrong here? My assumption is that you write to the database in the timezone where the … -
Reporting in django
I need some advice on what to do. I am developing an app for a course at my university. The userstory I working on at the moment is: "As a user I want to be able to report films that doesn´t exist." My thought was to have a report-button at my film_detail.html, where clicking this button would trigger the BooleanField in my model, and mark the film as reported. When clicking the report-button I was thinking on just having a pop-up window to confirm the reporting, and I believe I won´t need to create a complete new view for this(?). Does anyone have any idea on how to do this (cause I´m kinda stuck), or maybe having a better idea? **models.py** class Film(models.Model): title = models.CharField(max_length=100) title_short = models.CharField(max_length=17, default=None, null=True) plot = models.TextField() poster = models.ImageField(default="default.png", upload_to="posters") release_date = models.DateField(blank=True, null=True) date_posted = models.DateTimeField(default=timezone.now) reported = models.BooleanField("Is reported", default=False) #class Admin: # list_display = ("is_reported") #def is_reported(self): # return self.reported == True #is_reported.BooleanField = False **HTML** {% extends "board/base.html" %} {% block content %} <article class="media content-section"> <img class="rounded-circle film-img" src="/media/{{object.poster}}"> <!-- Mulighet for å ha en "add review"-knapp på siden der hvor filmene vises. --> <!-- <a href=" … -
python 3.8 inconsistent tabs and spaces
when running py manage.py runserver it shows me the following message: File "C: \ Django \ mysite \ forms \ views.py", line 38 producto_sel.delete () Taberror: inconsistent use of tabs and spaces in identation this is views.py: from django.shortcuts import render, redirect from .models import Productos from .forms import RegistrarProducto def index (request): mis_productos = Productos.objects.all() if request.method == 'POST': register_form = RegistrarProducto(request.POST) if register_form.is_valid(): success = register_form.registrar_producto() return redirect('./') else: register_form = RegistrarProducto() return render(request, 'forms/mi_form.html',{'register_form': register_form, 'productos':mis_productos}) def actualizar_producto(request, producto_id): producto_id=int(producto_id) try: producto_sel=Productos.objects.get(id=producto_id) except Productos.DoesNotExist: return redirect('forms/mi_form.html') form = RegistarProducto(request.POST or None, instance=producto_sel) if form.is_valid(): form.save() return redirect('/') return render(request, 'forms/mi_form.html', {'register_form': register_form}) def borrar_producto(request, producto_id): producto_id=int(producto_id) try: producto_sel=Productos.objects.get(id=producto_id) except Productos.DoesNotExist: return redirect('forms/mi_form.html') producto_sel.delete() return redirect('/') try to correct the error with pyhton idle by selecting from product_sel.delete () Format> Untabify Region but the error is not fixed -
Django does redirect to "Next" after custom login when login is required
When I use the login view provided by Django, it redirects to the desired page. My code is as follows: urls.py from django.urls import path from admn import views as views from django.contrib.auth import views as log_views urlpatterns = [ path('login/', log_views.LoginView.as_view(template_name='login.html'), name='login'), path('profile/', views.profile, name='profile'), ] views.py from django.shortcuts import render, redirect from django.contrib.auth.decorators import login_required @login_required(login_url='/login/') def profile(request): return render (request, 'profile.html') However, when I use a customized login (I need it to check other things), it logs in but does not redirect anymore. My code is as follows: urls.py from admn import views as views from django.urls import path urlpatterns = [ path('login/', views.login, name='administration-login'), path('profile/', views.profile, name='profile'), ] views.py from django.shortcuts import render, redirect from django.contrib.auth.decorators import login_required from myforms import UserLoginForm from django.contrib import messages def login(request): if request.method == 'POST': form = UserLoginForm(request.POST) username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: dj_login(request, user) messages.success(request, f'You are logged in {username}!') else: messages.error(request, f'Not logged in') else: form = Admin_UserLoginForm() return render (request, 'login.html',{'form':form}) @login_required(login_url='/login/') def profile(request): return render (request, 'profile.html') -
How to get template variables by using FormView?
I am currently following Mozilla's Django tutorial (https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Forms). The tutorial mostly shows how to create form using functions. I am trying to make the same function view work by using a generic class view (FormView). I am able to make most of the code to work except for 2 things. First one is that I can't seem to be able to save the due date. And, second one, is that I don't know how to access the model fields in my template using template variables. Here is my form model from the forms.py file. class RenewBookModelForm(ModelForm): def clean_due_back(self): data = self.cleaned_data['due_back'] # Check if a date is not in the past. if data < datetime.date.today(): raise ValidationError(ugettext_lazy( 'Invalid date - renewal in past')) # Check if a date is in the allowed range (+4 weeks from today). if data > datetime.date.today() + datetime.timedelta(weeks=4): raise ValidationError(ugettext_lazy( 'Invalid date - renewal more than 4 weeks ahead')) # Remember to always return the cleaned data. return data class Meta: model = BookInstance fields = ['due_back'] labels = {'due_back': ugettext_lazy('New renewal date')} help_texts = {'due_back': ugettext_lazy( 'Enter a date between now and 4 weeks (default 3).')} The form model implemented as a function: @permission_required('catalog.can_mark_returned') … -
is there anyway to connect django with sharepoint
i'm an intern and they asked me to create a web app and deploy it where employees insert their workhour daily but this web app has to connect with sharepoint to import files also if there is any changes in project status like in progress done anything like that , it has to be changed too in sharepoint ps:is there any requirement any web language i should learn before creating this web app if so how to connect the app with sharepoint and how about the database? also if there is any help in deployement ill be thankful :))) -
Need to change the admin panel for User app
When Users of Admin Panel get Permissions for Editing, there is no way of selecting which countries they have access to. My database has multiple countries, and a user with specific permission can do that in any country. I should be able to give "Groups" and "Users" access to only one or some countries [Currently there is no Country Selection Criteria] , So for each User or User-Type created in the Admin panel, there should be an additional selection for the Country Data of Database he can access So how should I create the models in models.py and admin.py? I am quite new to Django. My code for models.py class MyUser(models.Model): COUNTRY_CHOICES = ( ('SA', 'Saudi Arabia'), ('IN', 'India'), ('UAE', 'United Arab Emirates'), ('UK', 'United Kingdom'), ('KW', 'Kuwait') ) user = models.OneToOneField(User, on_delete=models.CASCADE) country_selection = MultiSelectField(choices=COUNTRY_CHOICES) For admin.py from django.contrib import admin from django.contrib.auth.models import User from django.db import models from .models import Guide, MyUser from django.contrib.auth.admin import UserAdmin as BaseUserAdmin class GuideAdmin(admin.ModelAdmin): date_hierarchy = 'date' raw_id_fields = ("country",) list_display = ['en_title', 'country', 'date'] search_fields = ['country__ISOCode', 'en_title'] # readonly_fields = ('slug', 'preload_image', 'feature_image', 'images') ordering = ['-date'] class UserInline(admin.StackedInline): model = MyUser can_delete = False verbose_name_plural = 'user' class … -
Problems with django form fiels for-loop
I've just started to learn Django recently. When implementing a Registration page with a website template(with css, js and some other files), I came across a problem with respect to form fields in for-loop. My form consists of 4 fileds: username, email, password1, password2. According to Django mannual, it can be achieved in html templates using: {% for field in form %} <div class="fieldWrapper"> {{ field.errors }} {{ field.label_tag }} {{ field }} {% if field.help_text %} <p class="help">{{ field.help_text|safe }}</p> {% endif %} </div> {% endfor %} and I noticed it has the same result as using {{ form }}. I want to fit it into my templates, which is: {% for field in form %} <div class="form-group"> <label for="{{ field.label }}" class="col-lg-2 control-label">{{ field.label }}</label> <div class="col-lg-10"> <input class="form-control" id="{{ field.label }}" placeholder="{{ field.label }}" type="text"> </div> </div> {% endfor %} By doing so, I can get the styles I need, but since the type in <input> is hard-coded as text, when inputing password it shows the characters instead of hidden as expected. -
how to translate fields of registration page in django
hey everybody i'm trying to translate a web app with i18n localization i have made .po file and compile messages but there is some view like registration log in and some other words automatically generated by django which is not correct how we should handle this part for example how i can access to this field in auto generated form registration. django registration field translation please help i have no iadea how i can change this tags. -
Pass variable to custom template loader
I want to make something like this work : context = { 'looking_for_this': '12345', } t = Template("Stuff {% include 'dynamic_template' %} stuff") c = Context(context) result = t.render(c) So I want 'dynamic_template' to be loaded by custom loader, I can make it, but I can't seem to find a way to pass a variable so i can use it in loader ("looking_for_this") . class CustomLoader(BaseLoader): is_usable = True def __init__(self, *args, **kwargs): self.looking_for_this = "????" super(CustomLoader, self).__init__(*args, **kwargs) def get_template_sources(self, template_name, template_dirs=None): yield Origin( name=template_name, template_name=template_name, loader=self, ) def get_contents(self, origin): return f"{self.looking_for_this}" I need it because i need to load 'dynamic_template_12345' template. It doesn't have to be context, I could pass it via reference, just can't find the place. Any hints ? Thanks -
How to set sass_path to node_modules when deploying on heroku
I am deploying my django-react app on heroku. I had this error before, that I solved by running this command SET SASS_PATH=.\node_modules. It worked fine locally. But when i deploy my project on heroku i get this error again. my index.scss files have nothing but scss for material web react components. index.scss @import "@material/react-card/index.scss"; @import "@material/react-button/index.scss"; @import "@material/react-icon-button/index.scss"; @import "@material/react-typography/index.scss"; @import "@material/react-drawer/index.scss"; @import '@material/react-list/index.scss'; @import '@material/react-menu-surface/index.scss'; @import '@material/react-menu/index.scss'; @import "@material/react-text-field/index.scss"; @import "@material/react-chips/index.scss"; @import "@material/react-layout-grid/index.scss"; @import "@material/react-list/index.scss"; @import '@material/react-line-ripple/index.scss'; @import '@material/react-floating-label/index.scss'; package.json "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "start": "./node_modules/.bin/webpack --config webpack.config.js", "watch": "npm run start -- --watch --mode development", "postinstall": "npm run start" }, "engines": { "npm": "6.12.0", "node": "12.13.0" }, "keywords": [], "author": "", "license": "ISC", "devDependencies": { "@babel/core": "^7.8.7", "@babel/preset-env": "^7.8.7", "@babel/preset-react": "^7.8.3", "babel-cli": "^6.26.0", "babel-loader": "^8.0.6", "babel-plugin-transform-class-properties": "^6.24.1", "babel-preset-es2015": "^6.24.1", "babel-register": "^6.26.0", "clean-webpack-plugin": "^3.0.0", "css-loader": "^3.4.2", "extract-text-webpack-plugin": "^4.0.0-beta.0", "node-sass": "^4.13.1", "style-loader": "^1.1.3", "sass-loader": "^8.0.2", "webpack": "^4.41.6", "webpack-bundle-tracker": "^0.4.3", "webpack-cli": "^3.3.11" }, "dependencies": { "@material-ui/core": "^4.9.3", "@material-ui/icons": "^4.9.1", "@material-ui/lab": "^4.0.0-alpha.44", "@material/react-button": "^0.15.0", "@material/react-card": "^0.15.0", "@material/react-checkbox": "^0.15.0", "@material/react-chips": "^0.15.0", "@material/react-drawer": "^0.15.0", "@material/react-floating-label": "^0.15.0", "@material/react-icon-button": "^0.15.0", "@material/react-layout-grid": "^0.15.0", "@material/react-line-ripple": "^0.15.0", "@material/react-list": "^0.15.0", "@material/react-material-icon": "^0.15.0", "@material/react-menu": "^0.15.0", "@material/react-text-field": "^0.15.0", "@material/react-typography": … -
Hello, I'm new to Django Rest_Framework. I am trying to implement a function-based view but facing problem with the put method
I want to know how we can access a particular object at id and then update it. I'm getting the 405 method not allowed error. Is it possible to do that or I have approach the problem in a different way? views.py from rest_framework import status from rest_framework.decorators import api_view from rest_framework.response import Response from home.models import example from home.serializers import exampleSerializer @api_view(['GET', ]) def exampleview(request): try: ex=example.objects.all() except example.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) if request.method=="GET": serializer=exampleSerializer(ex, many=True) return Response(serializer.data) @api_view(['PUT', ]) def exampleputview(request): try: ex1=example.objects.get(id=id) except example.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) if request.method=="PUT": serializer=exampleSerializer(ex1, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(status=status.HTTP_404_NOT_FOUND) urls.py from django.contrib import admin from django.conf.urls import url from home import views urlpatterns = [ url('admin/', admin.site.urls), url('home/',views.exampleview), url('home/<int:id>/',views.exampleputview), ] -
django admin site change the display label of field
I hope the title is enough to understand what my issue is, I just want to change the default label Fathers Lastname: into Lastname without changing the table field name in the models this is my models.py class ParentsProfile(models.Model): Fathers_Firstname = models.CharField(max_length=500,null=True,blank=True) Fathers_Middle_Initial = models.CharField("Middle Initial",max_length=500,null=True,blank=True, help_text="Father") Fathers_Lastname = models.CharField(max_length=500,null=True,blank=True)