Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do i set url for django view above the view function using decorator?
I used Flask a lot and love setting the url above view function using decorator how do I do that with Django? -
Using MAKEFILE for an existing Django project
I have an existing project with Django, and I have been using paver to run/test and install requirements for it. I am thinking to switch to MAKEFILE as most of the other projects are now using a makefile. How to install make in the console? maybe using pip? What are the prereqs for start using makefile. Any other help or tutorials that may help. -
Gracefully handle SQL Disconnect in Django
Is there anyway to gracefully handle a unexpected database disconnect in Django? Such as showing a specific view to my users? Currently django will just 500 error. -
How strict is the Setting SECURE_HSTS_SECONDS setting?
From the docs For sites that should only be accessed over HTTPS, you can instruct modern browsers to refuse to connect to your domain name via an insecure connection (for a given period of time) I have a URLField where a user can paste a URL (may be HTTP), which gets analysed to extract an image. When I paste a HTTP URL in the field, my Chrome browser removes the green 'Secure' badge next to the address. Would this breach the conditions for SECURE_HSTS_SECONDS? -
Django 1.10.7 ORM annotate query with conditional count over many to many field
Im having a problem using the annnotate function of django to get a conditional count from a many to many field. I have these 3 models: class Answer(models.Model): """ This model represents an answer to an open question. It just contains the answer text and the question it answers. """ answer_description = models.CharField(max_length=1500, blank=True, null=True) question = models.ForeignKey(Question) instrument_submission = models.ForeignKey(InstrumentSubmission) class MultipleChoiceAnswer(Answer): choices = models.ManyToManyField(QuestionChoice) class QuestionChoice(models.Model): name = models.CharField(max_length=300) question = models.ForeignKey(MultipleChoiceQuestion) explanation_needed = models.BooleanField(default=False) is_correct = models.BooleanField(default=False) ordinal = models.IntegerField(blank=True, null=True) select_all = models.BooleanField(default=False) no_answer = models.BooleanField(default=False) What I want to do is get all the MultipleChoiceAnswers with the total count of the choices field, and an additional count for the correct choices (the ones that have the attribute is_correct=True) As an example, I have one MultipleChoiceAnswer that has 2 choices related. One with is_correct=True, The other one with is_correct=False Then I ran the following test: In [4]: x=MultipleChoiceAnswer.objects.filter(pk=33420 ...: ) In [11]: for ans in x: ...: for c in ans.choices.all(): ...: print c.is_correct ...: True False In [7]: x=x.annotate(c=Count('choices'), ...: ...: correct=Count('choices',filter=Q(is_correct=True))) In [8]: for a in x: ...: print a.c ...: print a.correct ...: 2 2 I would expect to see 2 and then … -
Django 1.11 on passenger_wsgi not routing POST request
I'm trying to setup python on A2 shared hosting via passenger_wsgi. The app is working fine when I run it via 'runserver'. I tested this both in my local PC, and via SSH tunnel. However, when I try to set this up on passenger_wsgi, it can't seem to be able to route POST request. 1 import os 2 import sys 3 4 sys.path.insert(0, "/home/<username>/app") 5 6 import APP_CORE 7 8 # where is the python interpreter 9 INTERP = "/home/<username>/app/.virtualenv/bin/python" 10 if sys.executable != INTERP: os.execl(INTERP, INTERP, *sys.argv) 11 12 13 os.environ['DJANGO_SETTINGS_MODULE'] = "APP_CORE.settings" 14 15 import APP_CORE.wsgi 16 application = APP_CORE.wsgi.application Example, when I load the admin page (/admin/login), it can load the login page, but when submitting the credentials, it says that POST to /admin/login is not found - returning HTTP 404. The SAME flow when I run via runserver works - I feel that I could be missing something in the django WSGI configuration. Any help would be appreciated !! -
Static File Issues With Heroku and Django
My site was working fine, but then i started having problems with images i was uploading to Heroku. I was using whitenoise with Django but decided to move my image store and static files to AWS. I was following along with this tutorial, and was able to get the files in my static folder up to S3. But now I'm having problems when trying to deploy to Heroku. Note I have a static folder inside of my app folder ..inside of root Getting this error when pushing--which includes a collectstatic FileNotFoundError: [Errno 2] No such file or directory: '/tmp/build_f05a3a5f9e4b6ad44dfdf0b62dd16e9e/static' I'm pretty sure that it is a temporary storage area for Heroku (?) but i'm guessing that /static shouldn't be on the end. I'll copy my relevant settings.py variables here--hopefully someone can advise on this--i've been stuck in Static File hell for the last four plus hours! BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) DEFAULT_FILE_STORAGE = 'dealmazing.storage_backends.MediaStorage' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) STATIC_ROOT = os.path.join(PROJECT_ROOT, 'staticfiles') # Additional locations of static files STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] #This will make sure that the file URL does not have unnecessary parameters like your access key. AWS_ACCESS_KEY_ID = config('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = config('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = config('AWS_STORAGE_BUCKET_NAME') … -
Django How to display 2 objects in one list by subscript
After running a query on two tables not related by primary key, I was able to 'join' the resultant objects into a list containing 2 different objects. I used the list because the objects are related but I have no other way of relating them other than adding them both to a list once a certain condition was true. I am now trying to display them in the html as they have different fields and I'd like to choose the ones to display. I initially tried something like this: {% for record in results %} {{ record[0].field_name }} {{ record[1].field_name }} I've also tried some of the filters like below with no luck. {{ record |first|attr('field_name') }} Please advise on how I can use these 2 objects and display the relevant fields from both. -
Checking uploaded files
My django application uploads all files to my Amazon s3 storage bucket. So is there any reason for me to write code that cross-checks uploaded files to make sure they are not malicious? As an uploaded script in my s3 bucket can't really do any damage. The uploads are done via URLField or FileField (integrated with AJAX). -
Django: Resizing an Image before Upload
I'm trying to resize & reduce the quality of an image before saving it into the database. Here's what I did, class MyModel(models.Model): profile = models.ImageField(upload_to='profile_image/', blank=True) def save(self, *args, **kwargs): if self.profile: img = Image.open(self.profile) resize = img.resize((240, 240), Image.ANTIALIAS) new_image = BytesIO() resize.save(new_image, format=img.format, quality=75, save=False) temp_name = os.path.split(self.profile.name)[1] self.profile.save(temp_name, content=ContentFile(new_image.getvalue()), save=False) super(MyModel, self).save(*args, **kwargs) But the problem is that it's not renaming the images properly. For example I added an image named info_6 several times then here's what it named the image every time, first time: `info_6` second: `info_6_C6lbUVW` third: `info_6_C6lbUVW_lqFL4qR` forth: `info_6_C6lbUVW_lqFL4qR_PnbFGay` fifth: `info_6_C6lbUVW_lqFL4qR_PnbFGay_aHH3Xzq` sixth: `info_6_C6lbUVW_lqFL4qR_PnbFGay_aHH3Xzq_Tly9Xnj` Even there's an image I found in database named as, info_6_C6lbUVW_lqFL4qR_PnbFGay_aHH3Xzq_Tly9Xnj_TArZwyS_mrXfzug_ZC8AtTQ_rV5dwx4 I was worrying if it will break down at some point & stop saving images into database anymore. So, How can we prevent it from appending the new name behind the previous name? Thank You! -
django rest framework: can we directly use Serializers class rather than extending
I have a class as below and later use serializer to get the python datatypes: from datetime import datetime from rest_framework import serializers class Comment(object): def __init__(self, email, content, created=None): self.email = email self.content = content self.created = created or datetime.now() and created an object: comment = Comment(email='leila@example.com', content='foo bar') serializer = serializers.Serializer(comment).data returns empty ReturnDict: ReturnDict() whereas: if i define a class which extends serializers.Serializer class CommentSerializer(serializers.Serializer): pass and then serializer = CommentSerializer(comment).data ReturnDict([('email', 'leila@example.com'), ('content', 'foo bar'), ('created', '2018-04-01T03:33:58.627773Z')]) Why serializers.Serializer works only when we extend it -
DoesNotExists Error with django and celery
Following is a basic celery code @app.task def t_select(booking_id, seat_id, user_id): with transaction.atomic(): booking = Booking.objects.get(id=booking_id) booking.seats.add(Seat.objects.get(pk=seat_id)) return booking.save() Which gives the following error: [2018-04-01 02:25:55,893: INFO/MainProcess] Received task: functors.booker.t_select[cec7f2ca-bca0-4f3e-9865-102f3528ce3a] [2018-04-01 02:25:55,894: ERROR/ForkPoolWorker-4] Task functors.booker.t_select[e3a69d6b-1fc9-44cb-96ce-bfe18a1c96a9] raised unexpected: DoesNotExist('Booking matching query does not exist.',) Traceback (most recent call last): File "/usr/local/lib/python3.5/dist-packages/celery/app/trace.py", line 374, in trace_task R = retval = fun(*args, **kwargs) File "/usr/local/lib/python3.5/dist-packages/celery/app/trace.py", line 629, in __protected_call__ return self.run(*args, **kwargs) File "/home/harshil/Courses/SE/movie_recommender/functors/booker.py", line 9, in t_select try: File "/usr/local/lib/python3.5/dist-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/usr/local/lib/python3.5/dist-packages/django/db/models/query.py", line 403, in get self.model._meta.object_name booking_system.models.DoesNotExist: Booking matching query does not exist. On printing Booking.object.all(), I get 3 objects, which is what i use to call the above function. Hence there shouldn't be DoesNotExist error. Could anyone help me figure out the problem? -
Django: How to get values from my model field and use it to search for an online image, then store the image url in the model in?
I have a Django project with an anime app. The anime app has a model as follows: class Anime(models.Model): id = UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = CharField(max_length=100, blank=False) genre = CharField(max_length=1000, blank=False) TV = "TV/Series" MOVIE = "Movie" SPECIAL = "Special" OVA = "OVA" UNKNOWN = "Unknown" MUSIC = "Music" ONA = "ONA" typeChoices = ( (TV, "TV/Series"), (MOVIE, "Movie"), (SPECIAL, "Special"), (OVA, "OVA"), (ONA, "ONA"), (MUSIC, "Music"), (UNKNOWN, "Unknown") ) animeType = CharField(max_length=10, choices=typeChoices, default=TV, blank="False") episodes = IntegerField() rating = FloatField() members = IntegerField() photoCover = ImageField(null=True, upload_to="img/covers", verbose_name="cover photo", blank=True) I'd like to get the name of the anime (data is inputted by a csv or a form input) and use it in a google search and get the first image of the search. I have this code that may help me do that. import urllib from bs4 import BeautifulSoup searchName = searchName.replace(" ", "%20") searchName = searchName.replace("-", "%2D") searchName = searchName.replace("&", "%26") html = urllib.urlopen("http://www.google.com/search?q="+searchName+"&tbm=isch") soup = BeautifulSoup(html) img_links = soup.findAll("img", {"class":"rg_ic"}) for img_link in img_links: print(img_link.img['src']) What I don't know is if this would work and if it would work, I don't know where to apply the code. I'd want to use img_link.img['src'] as the … -
How to annotate Count
I have a Book model with two m2m fields, both related to the same model Person (authors and editors). I need a list of Persons annotated by number of Volumes related to this Person with any (or both) of this fields. If Person is an author and an editor of the Book simultaneously, it should counts as one hit. How can I do this? class Books(models.Model): authors = models.ManyToManyField('persons.Person' ...) editors = models.ManyToManyField('persons.Person' ...) -
Dealing with versioning using URLPathVersioning in Django 2
I've been having some troubles lately trying to set my REST API to use path versioning. I have the code in my_app/urls.py with: def ping(): return "pong" API_PREFIX = r'^v(?P<version>(v1))' urlpatterns = [ url(r'^admin/', admin.site.urls), url(f'^{API_PREFIX}/ping/$', get_json(ping))) # assume that get_json returns the right thing ] I added this lines to settings.py in the same directory: REST_FRAMEWORK = { 'DEFAULT_VERSIONING_CLASS': 'rest_framework.versioning.URLPathVersioning' } This doesn't work if I do a GET localhost:8000/v1/ping/. Is a f string able to include regex syntax or is the problem somewhere else? I tried fr'^{(API_PREFIX}}/ping/$' and that didn't work either. Bonus question: In the ping function, how can I access and check the version number passed in the path (1 in that case, but will change over time)? -
Filtering a queryset across a foreign key, using a parameter e.g. as argument from the view
I'm trying to build a flexible queryset that gives a result size based on parameters I use, but currently I'm only accessing that data from across a foreign key. Here's the setup. My first table is a set of "blog posts" - the model is pretty self explanatory: class BlogPost(models.Model): title = models.CharField(max_length=100) dateStamp = models.DateTimeField(auto_now_add=True) post = models.TextField() The second is a table that holds all the images for all the posts in a one-to-many relationship: class BlogImageSeqFilter(models.Manager): def get_querySet(self): ## slice the first three images with sequence between 1 and 3 return self.filter(sequence__gte=1, sequence__lte=3)[:3] class BlogImage(models.Model): blog = models.ForeignKey(BlogPost, null=True, on_delete=models.SET_NULL) img = models.ImageField(upload_to=imgFolder, blank=True) sequence = models.IntegerField(null=False, blank=False, default=0) objects = BlogImageSeqFilter() ## Custom Manager class BlogImageSeqFilter (The manager method comes in a little later in my question - I don't even know if using it has been the right approach so far...) In my view, the set of blog posts is included contextually in the rendering of the html tmeplate: def blogPage(request, proj): ## Limit to the newest 5 posts blogs = project.blogpost_set.all().order_by("-dateStamp")[:5] return render(request, 'blog/blogPage.html', {"blogs":blogs}) So in my template, I am displaying each blog post in a separate container, and including the set of … -
Django Rest Framework Save Data from Serializer to Model
How to Save Data from Serializer to Model Database. Following is an example Code but Not Saving Data to Database! For Example I am using a Sample Example View: @api_view(['GET', 'POST', ]) def login(request): if(request.method == "POST"): s = LoginSerializer(data=request.data) if(s.is_valid()): s.save() return Response(s.data, status=201) else: return Response(s.data, status=203) else: return Response("", status=404)`enter code here` from django.db.models import Model from django.db import models Create your models here. class UserDetails(Model): userid = models.AutoField(primary_key=True) first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) phone = models.CharField(max_length=15) class UserLogin(Model): userid = models.ForeignKey(UserDetails,on_delete=None) email = models.CharField(max_length=20) password = models.CharField(max_length=30) from rest_framework import serializers from api.models import UserLogin,UserDetails class LoginSerializer(serializers.Serializer): userid = serializers.Field() email = serializers.EmailField() password = serializers.CharField(max_length=20) def create(self, validated_data): return UserLogin.objects.create(**validated_data) -
How to use Angular 5 with Django REST Social Auth?
I do not really understand angulyar, there is a back-end on django, uses https://github.com/st4lk/django-rest-social-auth, there is also an example on AngularJS, but how to recreate it on Angular 5, there is a module ng2-ui -auth, but I could hardly use it. function set_user(response){ var source; if (response){ source = response.data; } else { source = { 'username': null, 'first_name': null, 'last_name': null, 'email': null, 'social_thumb': '{% static "anonymous.png" %}' }; } self.user.username = source.username; self.user.first_name = source.first_name; self.user.last_name = source.last_name; self.user.email = source.email; self.user.thumb = source.social_thumb; }; angular.module('SessionApp', ['satellizer']) .config(function($authProvider) { $authProvider.linkedin({ url: "{% url 'login_social_session' provider='linkedin-oauth2' %}", clientId: '86cpqssmi7ej5j', redirectUri: window.location.origin + '/' }); }).config(function($httpProvider) { $httpProvider.defaults.xsrfCookieName = 'csrftoken'; $httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken'; }).controller('LoginCtrl', function($scope, $auth, $http) { self = this; self.user = {}; set_user(); var req = { method: "GET", url: '{% url "current_user_session" %}', skipAuthorization: true // in case of session auth don't send token header } $http(req).then(function(response){ console.log("Got user from session cookies"); set_user(response); console.log(response); }); $scope.authenticate = function(provider) { $auth.authenticate(provider).then(set_user); }; $scope.logout = function(){ var req = { method: "POST", url: '{% url "logout_session" %}', skipAuthorization: true // in case of session auth don't send token header } $http(req).then(function(response){ set_user(); }); }; }); -
Create Django sessions
I'm currently facing with a problem, in my web app if 2 users log in and then each one wants to make an operation(e.g. add a review) these 2 reviews will appear in the database as being from the same person(last logged in user). I have documented and know that sessions have to be made, but I can't figure it out how. From the examples found I understand that something like that is needed user = authenticate(username=username, password=password) if user is not None: login(request, user) request.session['username'] = username return redirect('index') else: return render(request, 'library/login.html') and then in profile if I want to print the username always, to all users, will show the last logged in user class Profil(View): template_name = 'library/profil.html' def get(self, request): print(request.session['username']) # the rest of the code Can anyone please explain to me where I am wrong and how can i correct it? An example would be perfect. P.S.: Apologize in advance if you think it's a stupid question. -
Cookiecutter-django shell doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS
My first try on Django. Read the book "Two scoops of Django 1.11". Great read. With only scripting experience and new with Python, I'm using best efforts to follow the books standards. Initiated project with "cookiecutter-django" Made a simple Address app with a TimeStampedModel to experiment. Works great with makemigrations, migrate, admin and runserver. No issues and it works like a charm. However trying the book example on a csv import and bind to a form, I wanted to run it from the shell to test. The following may be overly verbose, but I'm not sure how to proceed. python manage.py shell --settings=config.settings.local The error occurs when required code is imported(any other form or model gets the same results): In [1]: from address.forms import add_csv_postarea --------------------------------------------------------------------------- RuntimeError Traceback (most recent call last) <ipython-input-1-f253686866ed> in <module>() ----> 1 from address.forms import add_csv_postarea ~/projects/myproject/myproject/address/forms.py in <module>() 5 from django import forms 6 ----> 7 from .models import PostArea, Address 8 9 ~/projects/myproject/myproject/address/models.py in <module>() 7 8 ----> 9 class Country(TimeStampedModel): 10 """ ISO 3166 Country codes 11 https://en.wikipedia.org/wiki/ISO_3166-1 ~/.virtualenvs/myproject/lib/python3.6/site-packages/django/db/models/base.py in __new__(cls, name, bases, attrs) 116 "Model class %s.%s doesn't declare an explicit " 117 "app_label and isn't in an application in " … -
SQLite Django Model for Inventory of Seeds
I'm trying to build an Inventory Model for a Django App that handles the sale of seeds. Seeds are stored and sold in packs of 3, 5, or 10 seeds of a single variety (for example: 3 pack of mustard seeds). I want to add x amount of products to inventory with a price for each entry, and sell that product at that price for as long as that entry has items left(quantity field > 0) even if later entries have been made for the same product and presentation but at a different price, so i have the following model: class Product(models.Model): name = models.CharField(max_length=100) class Presentation(models.Model): seed_qty = models.IntegerField() class Stock(models.Model): date = models.DateField(auto_now=True) quantity = models.IntegerField() product = models.ForeignKey(Product, on_delete=models.CASCADE) presentation = models.ForeignKey(Presentation, on_delete=models.CASCADE) cost = models.FloatField(null=True, blank=True) sell_price = models.FloatField(null=True, blank=True) I'm wondering if I should actually relate Product and Stock with a ManyToMany field through a GeneralEntry intermediate model in which I'd store date_added, presentation and cost/price. My issue is that when I add multiple Stock entries for the same product and presentation, I can't seem to query the earliest prices for each available (quantity>0) stock entry for each product. What I've tried so far has … -
Reverse for 'update' with arguments '('',)' not found. 1 pattern(s) tried: ['vehicles_app/(?P<post_id>[0-9]+)/update_post/$']
i have searched a lot ,but couldn't find the solution,there are a lot of related questions being asked before and i think there's no mistake but there's still an error,please help me i'm stuck from a week on this issue here is my index.html {% for obj in context %} <div class="container" style="padding-left:240px; padding-right:0px; width: 78%; margin-bottom:30px;"> <div class="well" style=" background-color: rgb(220, 220, 220);"> <div class="media"> <div class="media-body"> <div class="list-group"> <div class="d-flex w-100 justify-content-between"> <h1 class="media-heading" style="margin-top:20px; margin-bottom:20px; color: black;">{{ obj.title }}</h1> {% for img in obj.postpicture_set.filter %} <div class="w3-content" style="max-width:800px"> {% if img.image %} <img style="margin-bottom:30px; float: right" class="mySlides" src="{{ img.image.url }}" width="200" height="180"> {% endif %} </div> {% endfor %} <p> {{ obj.details }} </p> <ul class="list-inline list-unstyled"> <li><span><i class="glyphicon glyphicon-calendar"></i> {{ obj.date }} </span></li> <li>|</li> <span><i></i> {{ obj.brand }} </span> <li>|</li> <span><i></i> {{ obj.city }} </span><br> <form action="{% url 'vehicles_app:data' obj.id %}" method="post">{% csrf_token %} <input type="hidden" name="post_id" value="{{ obj.id }}"> <input type="hidden" name="usr_id" value="{{ obj.user_id }}"> <td><input style="margin-top:70px; margin-bottom:20px; margin-left:10px;" type="submit" class="btn btn-primary" value="Details"</td></form> {% if request.user == obj.user or request.user.is_superuser %} <form action="{% url 'vehicles_app:file-delete' obj.id %}" method="post" style="display: inline;">{% csrf_token %} <input type="hidden" name="post_id" value="{{ obj.id }}"> <td><input style="margin-top:70px; margin-bottom:20px; margin-left:10px;" type="submit" value="Delete" class="btn … -
Serving static files from Python alpine image: no /etc/mine.types file found
I have an Python Django application that I want to deploy through docker-compose, I used the blogpost called A Production-ready Dockerfile for Your Python/Django App to setup my files. This blogpost, however, assumes you use a third party to host your static files. Since this isn't the case, I changed the CMD command from: CMD ["/venv/bin/uwsgi", "--http-auto-chunked", "--http-keepalive"] to: CMD ["/venv/bin/uwsgi", "--http-auto-chunked", "--http-keepalive", "--static-map", "/static=/code/base/static"] This works more or less, I now however receive the following warning when I start my docker file: backend_1 | !!! no /etc/mime.types file found !!! This makes my solution not workable, since files are all interpreted as text/plain. Is there a simple solution to fix this? -
How do I render a Django object (form) from Javascript?
I have loaded Django form elements to localStorage for persistence of changes using localStorage.setItem("Key", JSON.stringify(obj)). That seems to be working. Now I want to retrieve the object and render it into my HTML page from Javascript. My script looks like this: // This script retrieves the Django form object that was stored as a JSON // from localStorage, parses it and posts it on the html page // Get label from document var myLabel = document.getElementById("currLabelID" + id_suffix).value.replace(/ /g,""); //alert("CurrLabel = " + myLabel); // Retrieve the form object from localStorage var yummy = JSON.parse(localStorage.getItem(myLabel)); // Put form object into page //var myDiv = document.getElementByName("theFieldPostDiv"); //$( myDiv ).append( yummy ); //var form = document.createElement('form'); //form.appendChild(yummy); //document.write( yummy ); //{{ yummy }} //$(document).ready(function() { // // $( "theFieldPostDiv" ).append( yummy ); // //}); //$( "theFieldPostDiv" ).append( $(yummy) ); //document.body.appendChild(yummy); //$.append(yummy); //yummy.post(); $(function() { $(".theFieldPostDiv").hide(); $("#form_id").submit(function(event) { event.preventDefault(); var posting = $.post(".theFieldPostDiv", yummy); posting.done(function(data) { $(".theFieldPostDiv").show(); }); posting.fail(function(data) { alert("Fail") }); }); }); Note: The "theFieldPostDiv" is where I want to render the form object in the page. The commented code shows several ways I attempted to accomplish this. Any help is appreciated. -
Saving data into model with Django onetoone field inbuilt user
I am able to save the data but the data is not getting stored into database Can you please tell me why I want to insert the credit card info with onetoone field with user as primary key When i click the submit button, am not getting any erros But in admin no data is getting stored in the table Can you please help me in just saving a dummy credit card details to Django user Here's my forms.py from django import forms from django.contrib.auth.models import User from .models import CardDetails class UserForm(forms.ModelForm): class Meta: model = User fields = ('first_name', 'last_name', 'email') class ProfileForm(forms.ModelForm): class Meta: model = CardDetails fields = ['name_on_card', 'card_number', 'expiry_date','card_code'] Models.py: class CardDetails(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) name_on_card = models.CharField(max_length=30, blank=True) card_number = models.CharField(max_length=16, blank=True) expiry_date = models.DateField( blank=True) card_code = models.CharField(max_length=3, blank=True) def __str__(self): return self.user.username # @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) # @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() Views.py: @login_required def update_profile(request): if request.method == 'POST': profile_form = ProfileForm(request.POST, instance=request.user.profile) if profile_form.is_valid(): profile_form.save() messages.success(request, ('Your profile was successfully updated!')) return redirect('home') else: messages.error(request, ('Please correct the error below.')) else: profile_form = ProfileForm(instance=request.user.profile) return render(request, 'wallet.html', { 'profile_form': …