Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Field Error (Unknown Fileds) even though field is already included in models.py
I keep getting the error, FieldError at /admin/products/variant/add/ Unknown field(s) (default) specified for Variant. Check fields/fieldsets/exclude attributes of class VariantAdmin. Even though the field default is included in my Variant Model models.py file class Variant(models.Model): COLOR_CHOICES = [ ('black', 'Black'), ('grey', 'Grey'), ('white', 'White'), ('blue', 'Blue'), ('green', 'Green'), ('yellow', 'Yellow'), ('orange', 'Orange'), ('red', 'Red'), ('purple', 'Purple'), ('gold', 'Gold'), ('silver', 'Silver'), ('brown', 'Brown'), ('pink', 'Pink'), ('colorless', 'Colorless'), ] CLOTH_SIZE_CHOICES = [ ('xxs', 'XXS'), ('xs', 'XS'), ('s', 'S'), ('m', 'M'), ('l', 'L'), ('xl', 'XL'), ('xxl', 'XXL'), ('xxxl', 'XXXL')] product = models.ForeignKey( Product, on_delete=models.CASCADE, related_name='variants') default = models.BooleanField(default=False), price = models.FloatField() old_price = models.FloatField(blank=True, null=True) quantity = models.IntegerField() # Dimensions in cm height = models.FloatField(blank=True, null=True) width = models.FloatField(blank=True, null=True) length = models.FloatField(blank=True, null=True) # in kg weight = models.FloatField(blank=True, null=True) # Colors color_family = models.CharField(max_length=20, choices=COLOR_CHOICES) specific_color = models.CharField(max_length=50, blank=True, null=True) # Clothing and Shoes cloth_size = models.CharField( max_length=20, choices=CLOTH_SIZE_CHOICES, blank=True, null=True) shoe_size = models.IntegerField(blank=True, null=True) # Computing ram = models.IntegerField(blank=True, null=True) rom = models.IntegerField(blank=True, null=True) # in cm screen_size = models.FloatField(blank=True, null=True) def __str__(self): return f"{self.product} Variant" def in_stock(self): return self.quantity > 0 def discount(self): if (self.old_price == self.price) or (self.old_price < self.price): return 0 return (100 - ((self.price / self.old_price) … -
Error 500 deploying a DJANGO app on heroku, in everything except the index
The view with the index works perfect even with statics, but the other views show the error 500 The code of my urls.py is next: from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('',include("home.urls",namespace="home")), path('api/',include("api.urls",namespace = "api")), ] +static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) and that one in my urls home folder (app folder) from django.urls import path from django.contrib.auth import views as auth_views from home import views from django.conf import settings from django.conf.urls.static import static app_name="home" urlpatterns=[ path('VerItems/',views.VerItems, name="VerItems"), path('VerAutores/',views.VerAutores, name="VerAutores"), path('AgregarAutor/',views.AgregarAutor, name="AgregarAutor"), path('AgregarItem/',views.AgregarItem, name="AgregarItem"), path('',views.Index.as_view(), name="index"), ] And finally. settings file, I know that BASEDIR is not what every web shows it should be, but if I change it, the index does not work anymore from pathlib import Path import os.path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'ke-7l!7r!e$f#8+e=bv9(&wu_1@purto!^#ut948t8)od+@te(' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', … -
Django: How to make it such that I can submit interest to any blogpost, not just 1 blog post?
Django: How to make it such that I can submit interest to any blogpost, not just 1 blog post? Currently, now after I submit interest to a blogpost, I can no longer submit interest to any other blog post. I will receive this message saying that 'You have already submitted your interest to this post.' Even though i haven't. Judging by the nature of my model. Is there a way for me to filter the 'user' field in my interest model such that I am only checking through to see if the particular user in that particular blog post has already submitted the interest? Cause i understand that right now, they are filtering it based on all the blogpost, and as long as I have already submitted 1, it definitely exists. Please let me know if you need my forms.py , urls.py too if it helps. views.py def submit_interest_view(request, slug): form = SubmitInterestForm() user = request.user blog_post = get_object_or_404(BlogPost, slug=slug) num_blogpost = BlogPost.objects.filter(author=user).count() if blog_post.author.email == user.email: return HttpResponse('You cannot submit interest to your own post.') if Interest.objects.filter(user=request.user).exists() and request.method=="POST": return HttpResponse('You have already submitted your interest to this post.') if request.method == 'POST': form = SubmitInterestForm(request.POST, request.FILES) if form.is_valid(): … -
How Mediafire (file Hosting) works or how to develope a Medifire like clone?
Actually, I was learning Django So I want to make a project for my own curiosity and also want to learn more about scalability and load. -
Django: Can't access static files in python script
i have deployed a django project with mod wsgi on an apache server. Everything works so far. In one python script I'd like to open a file in static files. Therefore I have tried something like this: mycode.py import cv2 class Foo(): def __init__(self): ... def openImg(self): self.myimg = cv2.imread('static/myapp/img/picture.jpg',0) return self.myimg .. just for testing However it can't find this file. Whether in path ('static/myapp/img/picture.jpg'), nor path ('myapp/static/myapp/img/picture.jpg') nor in path ('../static/myapp/img/picture.jpg') and some other which I have already forgot. It always returns "None". If I try the same on my "undeployed" local project it works without any problem. I have already collected all staticfiles to /myproject/static and given enough rights to access them. By the way, the access to the static files in the html works in production. What's the problem? Can you give me any advice? Thank you. Some additional information: views.py from django.shortcuts import render from .mycode import Foo def index(request): # New Instance for class Foo bar = Foo() # Return img array to put it in html for whatever imagearray = bar.openImg() context = {'imgarray': imgarray} return render(request, 'electreeksspy/index.html', context) Thats an example of my directory /home/myuser/MyProject /static/myapp/img/picture.jpg (collected) / /myapp /static/myapp/img/picture.jpg /mycode.py /views.py … -
Django: simple_tag not rendering simple string
I am trying to create dynamic menus list under one mega menu.The menus will be fetched from database.I am using Django simeple_tag feature to achieve this but some how does not render the simple test string which I am giving although I want to render HTML tags at the end.Here is my code, my_app/home/templatetags/menus.py from django import template register = template.Library() @register.simple_tag(name='downloadable_menus') def downloadable_menus(a): """ Generate the downloadable menus under the free resources mega menu """ return 'Hello' This is how I am using in template. {% load menus %} <div class="content"> <ul class="menu-col"> {{ downloadable_menus }} </ul> </div> So the above code should display the "Hello" string in the menu but it is not.Any help would be appreciated. -
How to import a value inside another class model in Django?
shope/models.py from django.db import models class Product(models.Model): PN = models.CharField(max_length=100, default = "AAAA") Ship/models.py from shop.models import Product class OrderItem(models.Model): product = models.ForeignKey(Product, related_name='ship_items', on_delete=models.CASCADE) PN = models.ForeignKey(Product.PN, related_name='ship_items', on_delete=models.CASCADE) print(PN) All I want to do is to get PN from shope/models.py into Ship/models.py then print it. -
PLEASE HELP: assert not cls._meta.auto_field, ( AssertionError: Model shop.Product can't have more than one auto-generated field
I GOT MORE THAN ONE AUTO-GENERATED FIELD ERROR product_id = models.AutoField(primary_key=True) product_name = models.CharField(max_length=50) category = models.CharField(max_length=50, default="") subcategory = models.CharField(max_length=50, default="") price = models.IntegerField(default=0) desc = models.CharField(max_length=300) pub_date = models.DateField() image = models.ImageField(upload_to="shop/images", default="") def __str__(self): return self.product_name``` -
How to store file in django session and get that file in another view and store in database
I created form where user upload their photo and other details before they submit the form i want to redirect somewhere because of payment gateway so how can i handle it. this is in my views #this is for order creation def form_submit(request): white_bg_photo = request.FILES['white_bg_photo'] front_page = request.FILES['front_page'] request.session['file1'] = white_bg_photo request.session['file2'] = front_page if order_status == 'created': context['data'] = data #all other stuff i am sending to order confirmation return render(request, 'order_confirmation.html',context) else: return(request,'error.html') #this is for order confirmation def payment_status(request): response = request.POST data = request.POST.get('data') params_dict = { 'razorpay_payment_id' : response['razorpay_payment_id'], 'razorpay_order_id' : response['razorpay_order_id'], 'razorpay_signature' : response['razorpay_signature'] } # VERIFYING SIGNATURE try: status = client.utility.verify_payment_signature(params_dict) booking = Booking() booking.white_bg_photo = request.session['file1'] booking.front_page = request.session['file2'] booking.data = data booking.save() return render(request, 'order_summary.html', {'status': 'Payment Successful'}) except: return render(request, 'order_summary.html', {'status': 'Payment Faliure!!!'}) -
Adding Button in Django Admin Panel
In my main Django Project, I have an app called "Argentina" where I have registered model "PowerPlantMix". The model will have list of PowerPlants in Argentina with their respective capacities. Goal: What I am trying to do is to have an extra button by name of "Button" (as given in image) in which a URL would be embedded that would take me to respective URL(already registered in url.py). Is there a way I can add a button in models. As I have multiple apps I cannnot use the view site button. Thanks -
Django, Next.JS: CORS header ‘Access-Control-Allow-Origin’ missing, CORS request did not succeed even though django-cors-headers is defined
I am stuck with the old and confusing issue of CORS with Django and Next.JS. My setup: OS: Windows 10, Browser: Mozilla: 84.0.2 (64-bit), Django: 3.1, Next.JS: 10. My Django settings: INSTALLED_APPS = [ ... 'corsheaders', 'rest_framework', 'my_app', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.AllowAny', ], 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework_simplejwt.authentication.JWTAuthentication', ], } CORS_ALLOWED_ORIGINS = [ 'http://localhost:3000', ] CORS_ORIGIN_ALLOW_ALL = False CORS_ALLOW_CREDENTIALS = True urls.py: from rest_framework_simplejwt.views import ( TokenObtainPairView, TokenRefreshView, ) urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('my_app.urls')), path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'), path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), ] My Next.js page: import { useState } from 'react'; import axios from 'axios'; export default function loginForm() { const [username, setUsername] = useState(''); const [password, setPassword] = useState(''); const handleSubmit = () => { const headers = { "Content-Type": "application/json", "Accept": "application/json" } return axios({ method: "POST", url: "http://127.0.0.1:8000/api/token/", data: { username: username, password: password }, headers: headers }) .then(function (response) { console.log(response); }) .catch(function (response) { console.log(response); }); }; return ( <div className="loginBox"> <div className="lblBox"> <label className="label" htmlFor="loginbox"> Enter Username and Password <div className="unameInput"> <input type="text" name="username" placeholder='Enter username' onChange={e => setUsername(e.target.value)} /> </div> <div className="passwordInput"> <input type='password' name='password' placeholder='Enter password' onChange={e => … -
Making nested queries using the Django ORM
Assuming I have a model like below: class Region(models.Model): info = JSONField() number = models.IntegerField() I want to write a ORM query which translates into a nested SQL query similar to the below one: SELECT result, COUNT(number) FROM (SELECT jsonb_object_keys("region_table"."info") as result, number from region_table) pp group by number; Is there any way to perform the above nested SQL query? -
Using python-decouple, how do I pass a variable with a carriage return (rsa key)?
I have a rsa key in my .env file like this: MY_KEY=-----BEGIN PRIVATE KEY-----\n********my key**********\n-----END PRIVATE KEY-----\n When using from decoule import config and "private_key": config("MY_KEY"), the following is the result I get. MY_KEY=-----BEGIN PRIVATE KEY-----\\n********my key**********\\n-----END PRIVATE KEY-----\\n The extra slash in \\n is causing a problem in that my google.oauth2 can't recognize the key. Is there a way to import the key so that only one slash is returned and not two? -
check if exist on postgres array django
i have this zone like east west north south and i have added states in all 4 zone.every states stored in array type like this ids: {cd26ddeb-04cb-4d9a-8c7f-51d5d389f475,bc44618d-3a21-475b-8d74-c0542abb173b,18695611-256e-4506-a087-596f8914551d} what i'm trying to do is whenever i have any new state it should check on all zone if it exist then do nothing otherwise add this. Issue is i'm passing new states that need to add with previous added states. then i'm checking with all zone states if not exist then add this to new_state list and pass to data but this part not working: if state not in all_state: #its not filtering states returning all new_state.append(state) @api_view(['POST']) @login_required_message def zoneEdit(request): data = decode_data(request.data.copy()) new_state = [] try: try: zone_queryset = Zone.objects.get(uid=data['uid']) all_state = Zone.objects.values_list('state',flat=True) print(all_state, "all_state") data["created_by"] = request.user.uid for state in data['state']: if state not in all_state: #its not filtering states returning all new_state.append(state) print(new_state, "to be added") zone_serializer_obj = ZoneSerializer(zone_queryset, data=new_state) if zone_serializer_obj.is_valid(): try: city_save = zone_serializer_obj.save() return CustomeResponse(request=request, comment=ZONE_NAME_UPDATE, data=json.dumps(zone_serializer_obj.data, cls=UUIDEncoder), status=status.HTTP_200_OK, message=ZONE_NAME_UPDATE) except Exception as e: return CustomeResponse(request=request, log_data=json.dumps(str(e), cls=UUIDEncoder), message=SOMETHING_WENT_WRONG+" mv54 "+str(e), data=json.dumps({}, cls=UUIDEncoder), status=status.HTTP_400_BAD_REQUEST, validate_errors=1) else: return CustomeResponse(request=request, comment=FIELDS_NOT_VALID, data=json.dumps(zone_serializer_obj.errors, cls=UUIDEncoder), status=status.HTTP_400_BAD_REQUEST, validate_errors=1) else: return CustomeResponse(request=request, comment=FIELDS_NOT_VALID, data=json.dumps({}, cls=UUIDEncoder), status=status.HTTP_400_BAD_REQUEST, validate_errors=1) except City.DoesNotExist: return CustomeResponse(request=request, … -
Django template progress bar upload to AWS s3
I have a form where the user can upload multiple files and I am using jquery ajax to submit the files and other fields in the form. when uploading large files.. the site looks unresponsive so I wanted to add a progress bar. so inside the xhr parameter, I wrote... xhr: function () { var xhr = new window.XMLHttpRequest(); xhr.upload.addEventListener('progress', function (e){ if (e.lengthComputable) { console.log('Bytes Loaded: '+e.loaded) console.log('Total Size: '+e.total) console.log('Percentage Uploaded: '+(e.loaded/e.total)) } }); return xhr; } but this does not work properly because almost instantly the percentage uploaded shows 1 i.e. 100% while the actual file takes its own time to upload and after that, the success message is shown. What am I doing wrong? -
AWS Lightsail 'Exception occurred processing WSGI script'
I followed the amazon tutorial EXACTLY for deploying a Django app on lightsail: Deploy Django-based application onto Amazon Lightsail. But when I visit my IP address (http://52.41.70.195/) I get Internal server error. When I check the apache error logs I see these errors: Failed to parse Python script file '/opt/bitnami/projects/Django-E -Commerce/perfectcushion/wsgi.py'. Exception occurred processing WSGI script '/opt/bitnami/projects/Django-E-Commerce/perfectcushion/wsgi.py'. My wsgi.py file looks like the one amazon provides: import os import sys sys.path.append('/opt/bitnami/projects/Django-E-Commerce’) os.environ.setdefault("PYTHON_EGG_CACHE", "/opt/bitnami/projects/Django-E-Commerce/egg_cache") os.environ.setdefault("DJANGO_SETTINGS_MODULE", “Django-E-Commerce.settings") from django.core.wsgi import get_wsgi_application application = get_wsgi_application() Any suggestions? -
Cannot publish Django Rest API on heroku
I'm trying to publish my Django rest framework application to Heroku. I'm following all the procedures accordingly to publish from Github repository but don't know where is my mistake. In Heroku deploy tab it says deployed successfully but while i go to visit the page it show the following error. My folder structure is as follows where my API is in api folder and the project is in config folder: I've specified the file name in Heroku procfile as follows (adding asgi file since my project is using asgi instade of wsgi for Django channels): web: gunicorn config.asgi --log-file - When I check the error from the terminal it cannot find module config but also show build success. The error is as follows: 2021-01-14T07:10:10.612461+00:00 heroku[web.1]: State changed from crashed to starting 2021-01-14T07:10:25.885018+00:00 heroku[web.1]: Starting process with command `gunicorn config.asgi --log-file -` 2021-01-14T07:10:30.278347+00:00 app[web.1]: [2021-01-14 07:10:30 +0000] [4] [INFO] Starting gunicorn 20.0.4 2021-01-14T07:10:30.279496+00:00 app[web.1]: [2021-01-14 07:10:30 +0000] [4] [INFO] Listening at: http://0.0.0.0:36267 (4) 2021-01-14T07:10:30.279664+00:00 app[web.1]: [2021-01-14 07:10:30 +0000] [4] [INFO] Using worker: sync 2021-01-14T07:10:30.296521+00:00 app[web.1]: [2021-01-14 07:10:30 +0000] [9] [INFO] Booting worker with pid: 9 2021-01-14T07:10:30.305338+00:00 heroku[web.1]: State changed from starting to up 2021-01-14T07:10:30.310836+00:00 app[web.1]: [2021-01-14 07:10:30 +0000] [9] [ERROR] Exception … -
How do I add Pagination to a table (Django)
I am trying to add pagination to one of the tables for my project, but I can't find any good resources to refer to, all of the docs use some kind of URL query, but I don't want to do that, since it is on the user page. Background --- I am making a mock website for trading for a project and I need the user to be able to see their trade history, and as you can imagine, after any more than 10, the page starts to look very long, so I am trying to find a way to make the table have pages, but I just can't figure it out. Aim -- To add pages to a bootstrap table. The table should be able to go back and forth using buttons. My "solution" - after going through stuff for about an hour, I found this but I don't know if it is good/safe. Code : VIEW - def userPage(request): user = request.user user_info = user.info trades = user_info.trade_set.all().order_by('-time_bought_at') ###I want this queryset to be paginated total_trades = trades.count() balance = round(user_info.balance) context = { "user" : user, "user_info" : user_info, "trades" : trades, "total_trades" : total_trades, "balance" : … -
python django database information to html template
i am trying to fetch information from a psql database and i would like to export it to a html template, however i get a list, not an object or dict, so i can not call the properties of the information in the tempalte def myview(request): conn = psycopg2.connect(user="bogarr",password="Testing321",host="localhost",port="5432",database="LoginDatabase") try: cursor = conn.cursor() cursor.execute("select * from blog_post") rows = cursor.fetchall() finally: conn.close() context = { 'rows': rows } for row in rows: print("kecske: ", row[1]) return render(request,"blog/mytemplate.html", context) -
Django: Passing 'name' to Client.post()
I want to pass 'name' variable to request.POST.get() from Client in test in Django to be further processed by post function in view. Something like that(product is ChoiceField in form): response = c.post('/ordersys/orders/create/', {'product':product, 'amount':3}, name="Add") I want that if to be True when posting from Client: if request.POST.get("Add"): self.add_to_order(product, amount) In form, submit like that works: <input type="submit" name="Add" value="Add item to order"> -
Chart.js not working after Django deployment on Heroku
My Django site was working fine at localhost:8000 but when I uploaded to Heroku, the charts no longer show up. Is there any typical reason why this would be? The errors I received in the console were Uncaught Error: Chart.js - Moment.js could not be found! You must include it before Chart.js to use the time scale. Download at https://momentjs.com and The page at 'https://...com/' was loaded over HTTPS, but requested an insecure script 'http://cdnjs.cloudflare.com/ajax/libs/moment.js/2.13.0/moment.min.js'. This request has been blocked; the content must be served over HTTPS. -
how do i debug or add a relation
The above exception (relation "blog_blog" does not exist LINE 1: INSERT INTO "blog_blog" ("title", "pub_date", "body", "image... ^ ) was the direct cause of the following exception: /usr/local/lib/python3.9/site-packages/django/core/handlers/exception.py, line 47, in inner response = get_response(request) … ▶ Local vars /usr/local/lib/python3.9/site-packages/django/core/handlers/base.py, line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) … ▶ Local vars /usr/local/lib/python3.9/site-packages/django/contrib/admin/options.py, line 614, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) … ▶ Local vars /usr/local/lib/python3.9/site-packages/django/utils/decorators.py, line 130, in _wrapped_view response = view_func(request, *args, **kwargs) … ▶ Local vars /usr/local/lib/python3.9/site-packages/django/views/decorators/cache.py, line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) … ▶ Local vars /usr/local/lib/python3.9/site-packages/django/contrib/admin/sites.py, line 233, in inner return view(request, *args, **kwargs) … ▶ Local vars /usr/local/lib/python3.9/site-packages/django/contrib/admin/options.py, line 1653, in add_view return self.changeform_view(request, None, form_url, extra_context) … ▶ Local vars /usr/local/lib/python3.9/site-packages/django/utils/decorators.py, line 43, in _wrapper return bound_method(*args, **kwargs) … ▶ Local vars /usr/local/lib/python3.9/site-packages/django/utils/decorators.py, line 130, in _wrapped_view response = view_func(request, *args, **kwargs) … ▶ Local vars /usr/local/lib/python3.9/site-packages/django/contrib/admin/options.py, line 1534, in changeform_view return self._changeform_view(request, object_id, form_url, extra_context) … ▶ Local vars /usr/local/lib/python3.9/site-packages/django/contrib/admin/options.py, line 1580, in _changeform_view self.save_model(request, new_object, form, not add) … ▶ Local vars /usr/local/lib/python3.9/site-packages/django/contrib/admin/options.py, line 1093, in save_model obj.save() … ▶ Local vars /usr/local/lib/python3.9/site-packages/django/db/models/base.py, line 753, in save self.save_base(using=using, force_insert=force_insert, … ▶ Local vars /usr/local/lib/python3.9/site-packages/django/db/models/base.py, line 790, in save_base … -
success url does not work in my class based DeleteView
My success_url for my class based delete view does not work for some reason. in views.py # allows a user to delete a project class DeletePost(DeleteView): template_name = 'user_posts/post_delete.html' model = Post # return to the all posts list success_url = reverse_lazy('posts_list') # make sure the user is looking at its own post def dispatch(self, request, *args, **kwargs): obj = self.get_object() if not obj.user == self.request.user: raise Http404("You are not allowed to Delete this Post") return super(DeletePost, self).dispatch(request, *args, **kwargs) in urls.py: path('list/', PostsListView.as_view(), name="posts_list"), path('create-post/', CreatePostView.as_view(), name="post_create"), path('update-post/<int:pk>', UpdatePost.as_view(), name="post_update" ), path('delete-post/<int:pk>', DeletePost.as_view(), name="post_delete") in the HTML file: {% extends 'base.html' %} {% block content %} <form action="." method="POST" style="width:80%;"> {% csrf_token %} <h3>Do You want to delete this post: "{{ object.title }}"</h3> <input class="btn btn-primary" type="submit" value="Confirm"/> <a href="{% url 'posts_list' %}">Cancel</a> </form> {% endblock content %} whenever I click ok to delete a specific project, it doesn't return to the list of posts for: image of the error on the webpage -
TypeError at /api/register/ 'module' object is not callable
I am trying to register users using django rest framework but this is the error i am getting, Please help Identify the issue TypeError at /api/register/ 'module' object is not callable Request Method: POST Request URL: http://127.0.0.1:8000/api/register/ Django Version: 3.1.5 Exception Type: TypeError Exception Value: 'module' object is not callable Exception Location: C:\Users\ben\PycharmProjects\buddyroo\lib\site-packages\rest_framework\generics.py, line 110, in get_serializer Python Executable: C:\Users\ben\PycharmProjects\buddyroo\Scripts\python.exe Python Version: 3.8.5 below is RegisterSerializer from django.contrib.auth.password_validation import validate_password from rest_framework import serializers from django.contrib.auth.models import User from rest_framework.validators import UniqueValidator class RegisterSerializer(serializers.ModelSerializer): email = serializers.EmailField( required=True, validators=[UniqueValidator(queryset=User.objects.all())] ) password = serializers.CharField(write_only=True, required=True, validators=[validate_password]) password2 = serializers.CharField(write_only=True, required=True) class Meta: model = User fields = ('username', 'password', 'password2', 'email', 'first_name', 'last_name') extra_kwargs = { 'first_name': {'required': True}, 'last_name': {'required': True} } def validate(self, attrs): if attrs['password'] != attrs['password2']: raise serializers.ValidationError({"password": "Password fields didn't match."}) return attrs def create(self, validated_data): user = User.objects.create( username=validated_data['username'], email=validated_data['email'], first_name=validated_data['first_name'], last_name=validated_data['last_name'] ) user.set_password(validated_data['password']) user.save() return user and RegisterView.py from django.contrib.auth.models import User from rest_framework import generics from rest_framework.permissions import IsAuthenticated, AllowAny # <-- Here from rest_framework.response import Response from rest_framework.views import APIView from api import UsersSerializer, RegisterSerializer class RegisterView(generics.CreateAPIView): queryset = User.objects.all() serializer_class = RegisterSerializer permission_classes = (AllowAny,) -
how to write serializer and view for this type output data format and save in database drf,mysql
{ "user_name": "admin", "raw_data_column": [ "UPC Code", "Label or Sublabel", "Server Wise" ] }