Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can we keep unique id, if me make primary key any other column
I want to use default generation ID as well and make another field a primary key.. Can I do that with django ?. this is my object:: { "platform_subscriber_id": "XXXXXXXXXXXXXXX",#this is custom primary key. "platform_subscriber_entity": "loop", "platform_subscriber_secret_key": "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "is_remove": false, "update_time": "2022-02-09T09:18:28.991032Z", "create_time": "2022-02-09T09:18:28.991038Z", "platform_subscriber_owner": 1 }, i want old one unique ID too.. { "id":1,#this is default one i want back "platform_subscriber_id": "XXXXXXXXXXXXXXX",#this is custom primary key. "platform_subscriber_entity": "loop", "platform_subscriber_secret_key": "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "is_remove": false, "update_time": "2022-02-09T09:18:28.991032Z", "create_time": "2022-02-09T09:18:28.991038Z", "platform_subscriber_owner": 1 } this is how my model looks like: class Project(models.Model): platform_subscriber_owner = models.ForeignKey(User, verbose_name=_("project owner"),db_column="platform_user_id", on_delete=models.CASCADE,null=True,blank=True) platform_subscriber_id = models.CharField(_("Project Key"), db_column="platform_subscriber_key", max_length=64,primary_key=True, blank=True) platform_subscriber_entity = models.CharField(_("Project Names"), max_length=64,blank=True) platform_subscriber_secret_key = models.CharField(_("Project Secret Key"), max_length=64,blank=True) is_remove = models.BooleanField(_("Remove"),default=False) update_time = models.DateTimeField(_("Updated Time"), default = timezone.now) create_time = models.DateTimeField(_("Created Time"), default = timezone.now) -
how to use multi-threading for optimizing face detection in django view?
this is my code and I want to optimize the performance how can I do this stuff parallel thread in python? any idea? i am useing this models : "DEEPFACE_MODELS": "VGG-Face;DeepFace", "DEEPFACE_BACKENDS": "opencv;ssd;dlib" any suggestion about optimizing performance would be great import os from logging import getLogger from os import listdir from deepface import DeepFace from rest_framework import status from rest_framework.response import Response from rest_framework.views import APIView from project import settings from project.apps.recognition.serializers import RecognizeSerializer from project.settings import VALUES logger = getLogger(__name__) def build_models(): model_names = VALUES["DEEPFACE_MODELS"].split(';') backends = VALUES["DEEPFACE_BACKENDS"].split(';') metric = VALUES["DEEPFACE_METRIC"] models = {} for model_name in model_names: models[model_name] = DeepFace.build_model(model_name) return models, backends, metric models, backends, metric = build_models() class RecognitionAPI(APIView): def post(self, request, *args, **kwargs): serializer = RecognizeSerializer(data=request.data) serializer.is_valid(raise_exception=True) validated_data = serializer.validated_data filename = serializer.save() user_directory = os.path.join(settings.MEDIA_ROOT, validated_data.get('user_id')) pairs = [] for user_pic in listdir(user_directory): pic_path = os.path.join(user_directory, user_pic) if os.path.exists(pic_path): pairs.append([filename, pic_path]) number_of_recognition = 0 number_of_not_recognition = 0 for backend in backends: try: for model_name in models.keys(): verification = DeepFace.verify(pairs, model=models[model_name], model_name=model_name, detector_backend=backend, distance_metric=metric, enforce_detection=False) for info in verification.values(): if info['verified']: number_of_recognition += 1 else: number_of_not_recognition += 1 except ValueError: continue if (number_of_recognition / (number_of_recognition + number_of_not_recognition)) >= \ VALUES["RECOGNITION_THRESHOLD"]: return Response(status=status.HTTP_200_OK) return Response(status=status.HTTP_403_FORBIDDEN) -
Remove * from label in forms.py file
My forms.py file: class AdForm(forms.ModelForm): title = forms.CharField( required=True, label='Title:', widget=forms.Textarea( attrs={ "rows": "1", "placeholder": "Add a title", "style": "resize:none;", } ) ) class Meta: model = Ad fields = ['title'] Next to label, * is automaticaly added. I want to remove it. -
changing image in different div on hover
I have a page that contains 6 elements, 3 elements in each row. My goal is to change the image in div with id=b in the second row when hovering div with id=a in the first row. Below is my HTML. homepage.html {% block body %} <div class="container-fluid"> <!--ROW 1--> <div class="row w-100"> <div class="card col-4 mobile-fly-me-section sidebar-color"> <div class="text-uppercase home-fly">Lorem Ipsum</div> </div> <div class="card col-4 hal-section justify-content-between p-3" id="a" onmouseover="chbg('red')" onmouseout="chbg('white')"> <h5 class="card-title home text-uppercase">header</h5> <a href="{% url 'main' %}" class="border-0 text-uppercase home stretched-link text-decoration-none">GO <img class="arrow" src="{% static 'assets/main/arrow.svg' %}"></a> </div> <div class="col-4 border d-flex flex-column min-vh-25 justify-content-end align-items-bottom p-3 home">Lorem ipsum</div> </div> <!--END ROW 1--> <!--ROW 2--> <div class="row w-100"> <div class="card col-4 mobile-fly-me-section text-uppercase home" id="b"> <img src="{% static 'assets/graphics/graphic 01.svg' %}" width="75%"> <!-- before hover--> <img src="{% static 'assets/graphics/graphic 02.svg' %}" width="75%"> <!-- after hover--> </div> <div class="col-4 border d-flex flex-column min-vh-25 justify-content-end align-items-bottom p-3 home">Lorem ipsum</div> <div class="col-4 border d-flex flex-column min-vh-25 justify-content-between align-items-top p-3 text-uppercase home"><b>Lorem ipsum</b> <div> <img class="arrow" src="{% static 'assets/main/arrow.svg' %}"> </div> </div> <!--END ROW 2--> </div> {% endblock body %} {% block js %} <script async src="//jsfiddle.net/YShs2/embed/"></script> <script> function chbg(color) { document.getElementById('b').style.backgroundColor = color; } </script> {% endblock js … -
Django Rest Framework Manipulating Serialize.pop
I'm trying a view function that does the necessary operation depending on the data coming from the body. There is a registration model serializer that takes an additional variable group and if the group is student, the institute ID will have "ST22" at the beginning. I couldn't find a way to pop 'group' from serializer before sending it to the database. The data is saved but since it sends group as well and It does not have a field, it throws an error. post function: def post(self, request, format='json'): serializer = RegistrationSerializer(data=request.data) if serializer.is_valid(): if (serializer.validated_data["group"].lower() == "student"): serializer.validated_data["institute_id"]= "ST22" + serializer.validated_data["institute_id"] user = serializer.save() if user: return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status= status.HTTP_418_IM_A_TEAPOT) serializer class: class StudentRegistrationSerializer(serializers.ModelSerializer): group = serializers.CharField() class Meta: model= CustomUser fields= ("id", "username", "password", "institute_id", "group") extra_kwargs = { 'password': { 'write_only': True } } def create(self, validated_data): password = validated_data.pop('password') password = validated_data.pop('group') user = CustomUser(**validated_data) user.set_password(password) user.save() return user -
Uppy redirect after uploading (Django)
I would like to redirect after a successful file upload with Uppy and Django. .use(Uppy.XHRUpload, { endpoint: '{% url "acct:first_add_excel" a.slug %}', headers: {'X-CSRFToken': "{{ csrf_token }}"}, method: 'POST', }) Nothing I do inside Django View seems to redirect such as: return HttpResponseRedirect(reverse('acct:index', kwargs={ })) So I assume it has to be done back in Uppy. I am guessing somewhere like this? uppy.on('complete', (result) => { console.log('Upload complete! We’ve uploaded these files:', result.successful) }) What is the best approach here? Thank you. -
Validating and processing DjangoAdminForm FileField
In a Django project I would like to use the admin form to upload and process files. If something in the file is not valid, a validation error should be shown to the user. My question is: How can this be done in "one step"? I currently only see the possibility of doing it in calling _validate_or_process_data to times. models.py def _validate_or_process_data(data): sheets = pd.read_excel(data.file, sheet_name = None, dtype = object) sheet_sums = sheets['Sums'] df = sheet_sums[(sheet_sums['text']=="Sum of foo")] if len(df.index) > 1: raise ValueError('foo') # further quite complicated processing, which could also lead to an Exception return df class InvoiceFile(models.Model): data = models.FileField(validators=[_validate_or_process_data]) def save(self, *args, **kwargs): uploaded_file = self.data.file super(InvoiceFile, self).save(*args, **kwargs) # processing after calling super() to upload the orginal file processed_data = _validate_or_process_data(uploaded_file) # processed_data is then used to fill child-elements of InvoiceData -
Add fields in Serializer dynamically
I have a View in which I receive the request and it returns the serialized data views.py class AllotmentReportsView(APIView): permission_classes = (permissions.IsAuthenticated,) def get(self, request): sfields = request.GET['sfields'] #I can get the fields in params serializer = AllotReportSerializer(items, many=True) return Response(serializer.data, status=status.HTTP_201_CREATED) serializer.py class AllotReportSerializer(serializers.ModelSerializer): send_from_warehouse = serializers.SlugRelatedField(read_only=True, slug_field='name') transport_by = serializers.SlugRelatedField(read_only=True, slug_field='name') sales_order = AllotSOSerializer(many=False) flows = AllotFlowsSerializer(many=True) class Meta: model = Allotment fields = ( 'transaction_no', 'dispatch_date', 'sales_order', 'is_delivered', 'send_from_warehouse', 'transport_by', 'flows', ) Instead of defining the fields in serializer can I pass the fields dynamically from the view sfields and pass them to the serializer ? -
html table too wide on iPhone devices
First of all let me say that this is my first web application, I'm not familiar with html and css so be patient if I write nonsense. Using Django, I created a web application to manage the reservations for tennis courts. For each court, there is a page that show the days of current month into a "calendar" created using a table element. In each cell there is a button that allow to see the reservations registered for that day. Everything works perfectly on PC and Android devices, but the problem cums when I browse my website on Apple devices (I tried 2 different models of IPhone). In the pictures below you can see that the table resizes perfectly on the Android device, while it is too large on the iPhone. Searching on internet for some tips I see that someone suggest to properly manage the "viewport" into the html of the page, and this is what I've done: <meta name="viewport" content="height=device-height, width=device-width, initial-scale=1"> Someone suggest to apply different scale transformations to resize the objects in page for small screens. I tried also this solution, it works perfectly on Android devices but nothing to do on IPhone. Below what I've … -
Get data from django database model
I have a django model, PhoneNumberVerification. It has two columns: phone number, and code. I want to be able to get the code if I am given a phone number. Essentially, search the table for which row has the phone number as my phone number, and fetch the code for that given row. I could write SQL for this, but I do not know how to execute that to fetch data in django models, and I was wondering if there was a better non-sql way to do this. My model: class PhoneNumberVerification(models.Model): phone_number = models.TextField(max_length = 20, blank = False, unique = True) code = models.CharField(max_length = 8, blank = False) What I want: from .models import PhoneNumberVerification def get_code(phone_number): # do some stuff return code -
What django/python tools should I use to draw objects [closed]
I want to create a django app that will use user input to draw objects. The idea is it will look like a very basic furniture planner. User provides room dimensions -> app displays simple rectangle. User inputs location of window -> app displays small rectangle at the location inside the room. User chooses furniture from the list and writes where should it be placed -> another rectangle shows on the graph. It should be very simple, no bells and whistles. I'm trying to figure out what technologies should I use. I am familiar with Django well enough to stick to it but what tools should I utilize for drawing? For now I'm thinking about matplotlib, what do you think? -
AWS Stepfunction GET Request 404's for object just created by POST
I have a webapp that has a POST request to create an object in the DB. After this, a post_save signal is used to kickoff an AWS step function. This stepfunction then tries to do a GET for the object that was just created. Every single time it seems to fail, and I'm having a hell of a time debugging since I can't just use pdb for something that only runs when deployed onto AWS. Is there something I'm missing here? Why am I getting this race condition or eventual consistency issue? What is the best way to ensure that the GET will find the object that was created by the POST? The FileRequest View contains the post_save hook that kicks off the AWS Step function from django.db import transaction from django.db.models.signals import post_save from core_api.models.file_request import FileRequest import boto3 ... ... ... @receiver(post_save, sender=FileRequest, dispatch_uid="file_request_unique_id") def _stepfunction_handler(sender: Type=FileRequest], instance:=FileRequest, created: bool, **kwargs) -> None: arn = "blablabla" file_id = instance.id client = boto3.client("stepfunctions") payload = { "input": json.dumps( {"input": {"file_request_id": file_id}} ), "stateMachineArn": arn } def execute_sfn(): client.start_execution(**payload) transaction.on_commit(execute_sfn) # I figured this would start the sfn only after the object is saved, but it does not seem to … -
Is there a way to selected field to search in Django admin?
Is there a good way to have a tick list under the search field which would allow user to select which field specifically to search? Or do I have to manually implement it? -
Overriding the get_queryset method in Django Admin
Please tell me why this design might not work: class FastCountQuerySet(QuerySet): def count(self): pass @admin.register(ItemOOSLog) class ItemOOSLogAdmin(ImportExportModelAdmin): def get_queryset(self, request): qs = super(ItemOOSLogAdmin, self).get_queryset(request) return qs._chain(__class__=FastCountQuerySet) I need to use my FastCountQuerySet class instead of QuerySet when using the get_queryset method. I found that this can be implemented through qs._chain(__class__=FastCountQuerySet), but it doesn't work, the regular QuerySet is used. -
how to Show like exist or not in serializer based on request.data in django
i have a post model and like model with ForeignKey. in API user will give the user session id . i want to show the user liked a post or not based on the session id in when i list all post . for example . when we open instagram we can as user which post we liked or not in the heart icon . models.py class Post(models.Model): title = models.CharField(max_length=150) image = models.FileField( upload_to="post/",) class PostLike(models.Model): like = models.CharField(max_length=10) user = models.ForeignKey(Customer,on_delete=models.CASCADE,related_name='post_likes') post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='likes') views.py @api_view(["POST"]) def post(request): if request.data != {}: session_id = request.data["session_id"] user = Customer.objects.filter(session_id=session_id) if user.count() != 0: posts = Post.objects.all() like_exist = PostLike.objects.filter(user = user).exists() serializer = PostSerializer(posts, many=True,context= {"like_exist":like_exist) return Custom_Response(request, news_serializer.data) serializer.py class PostSerializer(serializers.ModelSerializer): like_exist = serializers.SerializerMethodField("like_exist_") class Meta: model = News fields = ["title","image","like_exist"] def like_exist_(self,obj): is_liked = self.context.get("like_exist") return is_liked db post id title image 1 1st "" 2 2nd "" post_like id like post_id user_id 1 1 1 1 2 1 2 1 3 1 1 2 if api input session_id 10000 ,it's customer 1 so i want to show like this API "data": [ { "id": 1, "title": "trend post 1", "like_exist":true , }, { … -
Django save() method doesn't save in upload_to function
I have a issue in my code. I have a user model and it has a profile_image field with ImageField. I defined a profileImageRoot() function and equalized it to upload_to argument of ImageField. I have profile_image_count IntegerField and it increases 1 unit when image is uploaded in profileImageRoot(). I try save the value of profile_image_count on my database but save() method doesn't save. My source code: User model: class User(AbstractBaseUser): username = models.CharField(max_length=20, unique=True, verbose_name="Username") email = models.EmailField(unique=True, verbose_name="Email", help_text="Email you actively use") first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) date_of_birth = models.DateField(blank=False) date_created = models.DateTimeField(auto_now_add=True) last_login = models.DateTimeField(auto_now=True) profile_image = models.ImageField(upload_to=profileImageRoot) profile_image_count = models.IntegerField(default=0) spent_money = models.FloatField(default=0) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_verified = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ('username', 'first_name', 'last_name', 'date_of_birth') def has_perm(self, perm, obj=None): return self.is_admin def has_module_perms(self, app_label): return True def get_full_name(self): return f"{self.first_name} {self.last_name}" def is_birthday(self): if timesince(self.date_of_birth, datetime.today()) == datetime(day=0, month=0): return True else: return False def verify(self): self.is_verified = True def __str__(self): return self.get_full_name() profileImageRoot(): def profileImageRoot(instance, filename): user = User.objects.get(pk=instance.pk) ext = filename.split(".")[-1] user.profile_image_count += 1 print(user.profile_image_count) user.save() return f"{user.username}/profile_image/{user.profile_image_count}.{ext}" -
how to access the json data sended as a response in django on the frontend
I have a contact page I want the person can send me contact request if he is validating email first so for that i disable the submit button and added a button to send otp that works fine def contact_otp(request): if request.method=="POST": body = json.loads(request.body) email = body['email'] otp = OTP.objects.create() otp.save() body = f"The Otp To conferm your email is {otp.token}" send_mail( 'verification', body, f'{EMAIL_HOST_USER}', [f'{email}'], fail_silently=False ) data = { "data":f"{otp.token}" } return JsonResponse(data) after sending the opt i want to verify the otp in frontend and enable the submit button once it is very but sadly when i try access the data it says undefined .then((response) => response.json()) .then((data) => { console.log(data) }) i have used this same kind of script in payment where after success payment it get redirected now i had to access the data in the frontend so that i can verifyy it -
request.GET.get(' ') returns None
I have the following URL: http://127.0.0.1:8000/application_form/Network%20Adminstrator/ The URL is generated with: path('application_form/<str:job_title>/', views.ApplicationForm.as_view(), name='application_form') I keep on trying get_data = self.request.GET.get('job_title') and am expecting to get Network Adminstrator but instead it returns None My urls.py: urlpatterns = [ path('application_form/<str:job_title>/', views.ApplicationForm.as_view(), name='application_form'), ] views.py: class ApplicationForm(CreateView): model = Requirements form_class = ApplicationForm template_name = 'requirements/job_specs.html' # Passes the request object to forms def get_form_kwargs(self): kwargs = super(ApplicationForm, self).get_form_kwargs() kwargs['request'] = self.request return kwargs forms.py: class ApplicationForm(forms.ModelForm): def __init__(self, *args, **kwargs): self.request = kwargs.pop('request') super(ApplicationForm, self).__init__(*args, **kwargs) get_data = self.request.GET.get('job_title') print(get_data) dic = {'job_title__job_title': get_data} self.fields['qualifications'].queryset = Requirements.objects.get(**dic) class Meta: model = Applicants fields = ['email', 'qualifications'] email = forms.EmailField(label='', max_length=100, required=True, widget=forms.TextInput( attrs={'class': 'form-group form-control input-lg ', 'placeholder': 'Email'}), ) qualifications = forms.ModelMultipleChoiceField(queryset=None, widget=forms.CheckboxSelectMultiple) Any thoughts or ideas? I am still a bit new to programing in Django and I would really appreciate your time and knowledge. -
django.request logger to find "Synchronous middleware … adapted" for Django async
I've set up a trial async view in my Django app but the view continues to render in sync. As per Django docs, I'm checking that my Middleware isn't causing the issue: Middleware can be built to support both sync and async contexts. Some of Django’s middleware is built like this, but not all. To see what middleware Django has to adapt, you can turn on debug logging for the django.request logger and look for log messages about “Synchronous middleware … adapted”. There's already been a Stack Overflow question to elaborate on using the logger to find which middleware is prevent async from working, but the answer is incomplete. This is what I have in my settings, as per the above Stack Overflow answer: settings.py LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console': { 'class': 'logging.StreamHandler', }, }, 'loggers': { 'django.request': { 'handlers': ['console'], 'level': os.getenv('DJANGO_LOG_LEVEL', 'DEBUG'), 'propagate': False, }, }, } And my view: views.py from time import sleep import asyncio import logging logger = logging.getLogger("info") # --- Views from django.db import transaction @transaction.non_atomic_requests async def async0(request): #loop = asyncio.get_event_loop() #loop.create_task(lets_sleep()) await asyncio.sleep(1) logger.debug('in index') logger.info('something') return HttpResponse("Hello, async Django!") I've restarted the built in Django server, … -
Using RabbitMQ with Celery in Django post_save
I am applying asynchronous task handling using Celery on my Django Project. My project's logic:, from frontend side, there is a table with rows each having an upload button. User clicks on it and a payload is sent to backend containing a url that contains a file. File is recieved in django views. And saved into database, table Run. Immediately object is saved a post_save signal is triggered to run a celery task. The task to be performed is, fetch a list of runs with specific status. For each run, perform a task of downloading the file. I would like to perform this asynchronously in case there is more than one run. Keeping in mind user can click upload for more than one row from frontend. I am setting up RabbitMQ as my broker. I have rabbitMQ installed and running. I have set the CELERY_BROKER_URL='amqp://localhost' too in settings.py. I am a little lost on what I should do next in my configurations, could I get some guidance. I think I need to configure celery worker on my tasks. Below is my code so far : views.py #view that saves to database class RunsUploadView(APIView): serializer_class = RunsURLSerializer def post(self, request, *args, … -
Error: djdt is not defined how to solve this?
I just upgraded django 2.1 to django 3.0.14: then I got this error ModuleNotFoundError: No module named 'django.utils.lru_cache' in django-debug-toolbar, so I upgraded my django-debug-toolbar 1.9.1 to django-debug-toolbar 2.0 and run python manage.py collectstatic and clear cache from browser after that above error is resolved but debug-toolbar is not showing and in console got the error: toolbar.js:306 Uncaught ReferenceError: djdt is not defined how to resolve this error? I already have:: INSTALLED_APPS = [ # ... "debug_toolbar", # ... ] STATIC_URL = "static/" from django.urls import include, path INTERNAL_IPS = [ # ... "127.0.0.1", # ... ] urlpatterns = [ # ... path('__debug__/', include('debug_toolbar.urls')), ] -
Django: TemplateSyntaxError-Could not parse the remainder
My template gets a queryset named qs.value sent from the views.py, I can display the value using {{qs.value}} anywhere in the template, but using it in an if statement raises an error. {% if {{qs.value}} > 0 %} <!--do something--> <h3 class="text-success">{{qs.value}}</h3> {% else %} <!--do something else--> <a href=""><button class="btn btn-primary">Else</button></a> {% endif %} The error: Could not parse the remainder: '{{qs.value}}' from '{{qs.value}}' What am I doing wrong? -
How can add auto complte filter django?
adding auto complte filter for django models using django filter? django-admin-autocomplete-filter installed, and may i know how to write code ? my filter class PlayerFilter(django_filters.FilterSet): name = django_filters.ModelChoiceFilter(label='Name' ,queryset=Player.objects.all()) team__name = django_filters.ModelChoiceFilter(label='Team',queryset=Team.objects.all() ) team__game__name = django_filters.ModelChoiceFilter(label='Game',queryset=Game.objects.all() ) team__company__name = django_filters.ModelChoiceFilter(label='Company',queryset=Company.objects.all()) class Meta: model = Player fields =['name','team__name','team__game__name','team__company__name'] -
TypeError: django.db.models.manager.BaseManager._get_queryset_methods.<locals>.create_method.<locals>.manager_method() got multiple values
I am facing a problem while giving PUT request. url is : http://127.0.0.1:8000/api/v1/products/products/product-slug-9/ the error is :TypeError: django.db.models.manager.BaseManager._get_queryset_methods..create_method..manager_method() got multiple values for keyword argument 'product' models.py class Product(models.Model): """ This is The Product table contining all product items. """ name = models.CharField(max_length=255) title = models.CharField(max_length=255) slug = models.SlugField(max_length=255, unique=True) brand = models.ForeignKey(to='brands.BrandProfile', on_delete=models.DO_NOTHING, related_name='brand_product') # brand=models.CharField(max_length=30) category = models.ForeignKey( to='products.Category', on_delete=models.DO_NOTHING) # sizes = ArrayField( # models.CharField(max_length=10), # ) # colors = ArrayField( # models.CharField(max_length=56) # ) is_available = models.BooleanField(default=True) market_price = models.IntegerField() selling_price = models.IntegerField() description = models.TextField() # stock_status , visibility_status # product won't delete if category deleted, we have to do it manually. visiblity = models.BooleanField(default=True) created_at = models.DateTimeField(auto_now_add=True, editable=False) updated_at = models.DateTimeField(auto_now=True) class Meta: ordering = ('-created_at',) verbose_name = "Product" verbose_name_plural = "Products" def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(str(self.name.lower()) + str(uuid.uuid4())) return super().save(*args, **kwargs) def __str__(self): return str(self.title) @property def discount_percent(self): if self.selling_price: discount_percent = 100 - \ (self.selling_price * 100) / self.market_price return int(discount_percent) return 0 class ProductImage(models.Model): """ The Product Image Table """ product = models.ForeignKey( Product, on_delete=models.CASCADE, related_name='product_images') image = models.ImageField( upload_to=brand_product_image_file_path, blank=False, null=False) product_color = models.CharField(max_length=56) alt_text = models.CharField(max_length=24) is_featured = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True, editable=False) updated_at = … -
Form not posting data to database in django
I have a django model form to register a new user into Users table in Django. I have selected fields which I want to use. The form is showing correctly on the html page but the problem is when I submit the form, the data is not saved in the database. I tried to get the field values using name = request.POST['field'] and use print(name) all the data is being printed on the console. Below is my code forms.py class UserForm(UserCreationForm): first_name = forms.CharField(required=False, label='First Name', widget=forms.TextInput( attrs={'style': 'font-size:medium', 'class': 'form-control form-control-sm'})) last_name = forms.CharField(required=False, label='Last Name', widget=forms.TextInput( attrs={'style': 'font-size:medium', 'class': 'form-control form-control-sm'})) email = forms.EmailField(required=False, label='Email Address', widget=forms.TextInput( attrs={'style': 'font-size:medium', 'class': 'form-control form-control-sm'})) username = forms.EmailField(required=False, label='Username', widget=forms.TextInput( attrs={'style': 'font-size:medium', 'class': 'form-control form-control-sm'})) password = forms.EmailField(required=False, label='Password', widget=forms.PasswordInput( attrs={'style': 'font-size:medium', 'class': 'form-control form-control-sm'})) password1 = forms.EmailField(required=False, label='Confirm password', widget=forms.PasswordInput( attrs={'style': 'font-size:medium', 'class': 'form-control form-control-sm'})) class Meta: model = User fields = ('first_name', 'last_name', 'email', 'username', 'password','password1') My UserForm(): class is implementing UserCreationForm in the forms.py class UserForm(UserCreationForm): . views.py def reg(request): if request.method=='POST': form= UserForm(request.POST) if form.is_valid(): user = form.save() group = Group.objects.get(name="patient") user.groups.add(group) return redirect('profile') else: form=UserForm() head = 'Create user account' title = 'Consultation | create account' …