Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
why media queries is not working with django css styling?
Below is the HTML tag <div class="logo"> <img src="{% static 'img/sunil.png' %}" id="logo" alt=""> </div> STYLE.CSS what i have done in css file is below: #logo { height: 60px; width: 120px; } @media only screen and (max-width: 500px) { .logo { height: 20px; width: 60px; } } I tried to change the image size using media queries but it is not working. style.css is connected in main file because when I use #logo and changed height and width then its working but when I try in media queries then it's not working. -
Handling Exceptions in Python Django Crispy Forms
I'm new in Python 3.8.2/Django 3.1.1, and I'm trying to figure out the correct way to add rules to models so they can be called from forms and web services, the issue I have is that some errors are not properly caught and they are generating an 500 Error. This is my initial Model: class TotalPoints(TimeStampedModel): course = models.ForeignKey(Course, on_delete=models.CASCADE, related_name='TotalPoints_Course', null=False, blank=False, verbose_name='Curso') kit = models.ForeignKey(Kit, on_delete=models.CASCADE, related_name='TotalPoints_Kit', null=False, blank=False, verbose_name='Kit') bought = models.PositiveIntegerField(default=0, null=False, blank=False, verbose_name='Comprados') assigned = models.PositiveIntegerField(default=0, null=False, blank=False, verbose_name='Asignados') available = models.PositiveIntegerField(default=0, null=False, blank=False, verbose_name='Disponibles') class Meta: db_table = 'app_totalpoints' constraints = [ models.UniqueConstraint(fields=['course','kit'], name='app_totalpoints.course-kit') ] fields are declared PositiveIntegerField to avoid negative values this is my Form and CreateView class TotalPointsForm(forms.ModelForm): class Meta: model = TotalPoints fields = ['id', 'course', 'kit', 'available', 'bought', 'assigned'] class TotalPointsCreateView(CreateView): model = TotalPoints form_class = TotalPointsForm template_name = 'app/form_base.html' success_url='../list/' and this is my template: {# app/templates/app/form_base.html #} {% load crispy_forms_tags %} <!doctype html> <html lang="en"> <head lang="es"> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.22/css/jquery.dataTables.css"> <title>{% block page_title %}{% endblock %}</title> </head> <body> <div class="container-fluid"> <div class="jumbotron"> <h1 class="display-4">{% block form_title %}{% endblock %}</h1> <p class="lead">{% block form_subtitle %}{% … -
Django: How to save pdf file from PdfFileMerger
What wrongs this code? I want to save the file to the field's model 😭😭 obj = Document.object.first() merger = PdfFileMerger() for pdf in [page_1, page_2]: merger.append(pdf) merger.write(f'{str(uuid.uuid4())}.pdf') merger.close() obj.pdf = merger obj.save() -
Django admin list_display of different data types with null
I know I explained the title poorly, look I have a simple chat app where users can send text/audio/video/image and for me to render those messages I have a method that checks the type of the message and renders it accordingly if it was text then i will set safe to False in my template, else I will display what the function will give me which is an HTML code What I really want is: Admin panel giving me message text[:50] if it was text, if it was audio then i can have an audio preview for it, if it was image or video or file then it will give me the url. Is there anyway to do so? here are my files so you can get a better understanding of what I'm saying: models.py: class Message(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) room = models.ForeignKey(Room, on_delete=models.CASCADE) text = models.TextField(blank=True, null=True) video = models.FileField(upload_to="chat/room/vid", blank=True, null=True) image = models.FileField(upload_to="chat/room/img", blank=True, null=True) file = models.FileField(upload_to="chat/room/file", blank=True, null=True) audio = models.FileField(upload_to="chat/room/aud", blank=True, null=True) is_read = models.BooleanField(default=False) date = models.DateTimeField(auto_now_add=True) def content(self): if self.text: return self.text elif self.video: return f""" <video width="320" height="240" controls> <source src="{self.video.url}" type="video/mp4"> <source src="{self.video.url}" type="video/mov"> <source src="{self.video.url}" type="video/wmv"> <source src="{self.video.url}" … -
SendGrid Mail send is not working in my django rest-api view
I tried to add the send mail using sendgrid in my django & react project, but it is not working. My code in backend api view is like following: def send_invitation(request): if request.method == 'POST': TO_EMAILS = [('my email@gmail.com', 'My fullname'), ] FROM_EMAIL = 'my another email' TEMPLATE_ID = 'send-grid template id' message = Mail( from_email=FROM_EMAIL, to_emails=TO_EMAILS) message.dynamic_template_data = { 'subject': 'SendGrid Development', 'place': 'New York City', 'event': 'Twilio Signal' } # message.add_filter('templates', 'enable', '1') message.template_id = TEMPLATE_ID try: sg = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY')) response = sg.send(message) code, body, headers = response.status_code, response.body, response.headers print(f"Response code: {code}") print(f"Response headers: {headers}") print(f"Response body: {body}") print("Dynamic Messages Sent!") return Response({'message': 'Your Invitation is sent successfully!'}) except Exception as e: print("Error {0}".format(e)) return Response({'error': 'Your Invitation is failed to send!'}) I already add the SENDGRID_API_KEY in the .env file of my django backend, and installed the sendgrid using pipenv. The error is like this; Error HTTP Error 403: Forbidden Please let me know if the description is not enough. -
How to serve static_files in django?
Basically, I am practising an E-commerce project of Django. There are two ways of adding images. ( 1 ) - First is that someone adds the photos manually but I want users to add a photo of the product automatically via static files. models.py: from django.db import models # Create your models here. class Mobile(models.Model): brand = models.CharField(max_length=30) price = models.IntegerField(default=1) color = models.CharField(max_length=30) screen_size = models.IntegerField(default=5) os = models.CharField(max_length=30, default='Samsung') def __unicode__(self): return 'This is a mobile' def get_price(self): return self.price class MobileImage(models.Model): device = models.ForeignKey(Mobile, on_delete=models.CASCADE) image = models.ImageField(upload_to='media/images/') def __unicode__(self): return self.device class Laptop(models.Model): brand = models.CharField(max_length=30) price = models.IntegerField(default=1) color = models.CharField(max_length=30) screen_size = models.IntegerField(default=5) os = models.CharField(max_length=30, default='Dell') def __str__(self): return self.brand my views.py: def mobile(request): mobiles = Mobile.objects.all() context = { 'mobiles': mobiles } return render(request, 'device/mobile.html', context) def laptop(request): laptops = Laptop.objects.all() context = { 'laptops': laptops } return render(request, 'device/laptop.html', context) my mobile.html: {% extends 'device/base.html' %} {% load static %} {% block body %} <h1>Mobile!</h1> <!-- Table --> <table class=""> <tr> <h3>Phones:</h3> <th>ID</th> <th>Model</th> <th>Price</th> <th>Color</th> <th>Screen Size</th> <th>OS</th> <th>Image</th> </tr> <body> {% for mobile in mobiles %} <tr> <td>{{ forloop.id }}</td> <td>{{ mobile.brand }}</td> <td>${{ mobile.price }}</td> <td>{{ mobile.color }}</td> … -
Django Insert data or update
if the user inserted data with the same day his inserted his account the record will updated, and if the user insert data tomorrow or following day it will insert. I just want that only 1 data will insert everyday this is my views.py insert_1tab, created = TrCustomerEmployeeSupplierSubmittedRecords( fmCustomerID=company, fmCustomerLocationID = location, firstname=firstname, lastname=lastname, middleInitial=middlename, bodyTemperature=temperature, fmCustomerSectionID = sections, employee_number=employeno, contactNumber=cnumber, address=tirahan, ) if not created: insert_1tab.save() this is my models.py class TrCustomerEmployeeSupplierSubmittedRecords(models.Model): fmCustomerID = models.ForeignKey('FmCustomer', null=True, blank=True, verbose_name="Customer") fmCustomerLocationID = models.ForeignKey('FmCustomerLocation',null=True, blank=True, verbose_name="CustomerLocation") dateSubmitted = models.DateField(auto_now_add=True, null=True, blank=True) firstname = models.CharField(max_length=500, blank=True) middleInitial = models.CharField(max_length=500, blank=True) lastname = models.CharField(max_length=500, blank=True) bodyTemperature = models.FloatField() fmCustomerSectionID = models.ForeignKey('FmCustomerSection', null=True, blank=True, verbose_name="CustomerSection") employee_number = models.CharField(max_length=500, blank=True, null=True) contactNumber = models.CharField(max_length=500, blank=True, null=True) address = models.CharField(max_length=500, blank=True, null=True) email = models.CharField(max_length=500, blank=True, null=True) -
Django url error ( Redirecting to another url)
I have been learning django and i am having a problem with the url patterns. i have the project urls.py as follows: urlpatterns = [ path('', include('app.urls')), path('accounts/', include('accounts.urls')), path('data/',include('data.urls')), path('admin/', admin.site.urls), ] and i have "accounts app" urls.py as follows: urlpatterns = [ path("register", views.register, name="register") ] views.py of accounts app: def register(request): return render(request,'register.html', {'title' : 'User Registration | Django'}) Basically my data app contains country, state and district models. i have "data app" urls.py as follows: urlpatterns = [ path("country", views.country, name="country"), path("state" , views.state, name="state"), path("district", views.district, name="district") ] views.py of data app: def country(request): if request.method == "GET": if request.is_ajax(): obj_country_list = Country.objects.values("id" , "country") return HttpResponse(json.dumps(list(obj_country_list))) My error was when trying to access the "data/country url" inside the "register.html" page & the javascript function for fetching the is as follows: function Country(){ $.ajax({ type: "GET", contentType: "application/json; charset=utf-8", url: "data/country", //data: "{}", dataType: "json", success: function (Result) { $.each(Result.d, function (key, value) { $("#ddlcountry").append($("<option></option>").val(value.id).html(value.country)); }); }, error: function (Result) { alert("Error in invoking the function"); } }); } I tried to inspect the page & the url it was trying was accounts/data/country. When tried to change the url inside the header while inspecting the … -
Calling URL in Django and get output in Django screen
I am a beginner to Django and flask I want to invoke a URL from my flask and print the output in Django screen views.py def hello(request): your_name = request.GET.get('your_name') if not your_name: your_name =0 respons = requests.get('http://127.0.0.1:5000/' + str(your_name)).json( return render(request, 'hello/index.html', {'msg': respons['msg']}) index.html <form action ="/hello/" method="get"> <label for ="your_nname">Your number: </label> <input id="your_name" type="text" name="your_name" value="0"> <input type ="submit" value="OK">. in flask I want to create a get method with hello & 'name' I am getting error in my code -
How to add comments with ajax in django website?
How can I add comments in my Django website without refreshing the page? Here are my codes: VIEW.PY @login_required def comments(request, post_id): """Comment on post.""" post = get_object_or_404(Post, id=post_id) user = request.user comments = Comment.objects.filter(post=post).order_by('-date')#comment if request.method == 'POST':#Comments Form form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.post = post comment.user = user comment.save() messages.success(request, 'Comment has been added successfully.') return HttpResponseRedirect(reverse('core:comments',args=[post_id])) else: form = CommentForm() template = loader.get_template('post/comments.html') context = {'post':post,'form':form,'comments':comments,} return HttpResponse(template.render(context, request)) COMMENTS.HTMl Form section: <div class='commentsection' > <strong> <form action="{% url 'core:comments' post.id %}" method='post' id=comment-form > {% csrf_token %} {% bootstrap_form form %} </form> <br/> <br/> </strong> </div> Comments section: {% for comment in comments %} <div class="card mb-3" style="width: 30rem;"> <div class="row no-gutters"> <small> <a style="color: black;" href="{% url 'core:user_profile' comment.user %}"><img src="{{comment.user.profile.profile_pic.url}}" width=50 height=50 class="profile-image img-circle " style="object-fit: cover; float: auto; "><strong style="font-size: 18px;" > @{{comment.user}} </strong></a> </small> <small><span class="glyphicon glyphicon-time"></span> {{ comment.get_date }}</small> </div> <div class="card-body" style="width:100%; padding-left:20%; margin-top:-8%; word-break: break-all; color:black; " > <h5 class="card-text"> {{ comment.comment }}</h5> <small ><a href="{% url 'core:replies' comment.id %}"> Replies </a> [{{comment.total_replies}}] </small </div> </div> </div> <br/><br/> {% empty %} <center> No commnets </center> {% endfor %} My problems: 1] Add comments without refreshing … -
Write BaseSerializer to prevent Stored XSS in Djano
How can we prevent stored xss in Django API's, basically every Text/Char Field should be cleaned. Can we write a Base Serializer using DRF to prevent the attack. Does Django really need to use XSS safe mechanism or it does not effect anything as Django uses ORM for queries? We can use validate_<field_name> method in serializer but that is not a generic solution. Other than bleach can we have a built-in solution -
Can I dynamically place items in two-column template in Django?
The title might not be so clear, so let me elaborate more. I have a two-column template, and want to load some number of items in them. It would look like this: {{item1}} | {{item2}} {{item3}} | {{item4}} {{item5}} | {{item6}} {{item7}} | {{item8}} ... And this is the farthest I've got in my template : {% for a in answers %} <div class="row justify-content-center"> <div class="col-6 text-center"> <div class="row justify-content-center"> <div class="col"> <div class="answers">{{a.title}}</div> </div> </div> </div> <div class="col-6 text-center"> <div class="row justify-content-center"> <div class="col"> <div class="answers">{{a.title}}</div> </div> </div> </div> </div> {% endfor %} Apparently, it doesn't load item as I want to. How do I make this possible? Any help is very much appreciated! :) +Some other codes for further info: views.py def qandaSquare(request, pk): answers = Answer.objects.filter(authuser=request.user.id, question_number=pk) context = { 'answers' : answers, } return render(request, 'main/square.html', context) -
Overriding Django model's id
I have a user model and multiple user types that are related to the user model with a one to one relationship, a goer and a host. Whenever someone creates a goer or a host, an underlying user model is created and saved in the postgresql table. Currently, the goers' and the hosts' id are auto incrementing to the number of goers and hosts. Is there anyway I can override the goers' and hosts' id such that it matches the id of the underlying user that is created? -
Django: Dynamic Annotation and Filtering
I think this should not be complicated but i can't get it right. How can i conditionally count the number of brands in a specific category within a queryset? views.py def get_brands(request): all_brands = brand.objects.values('brand_name','brand_category').\ annotate(brand_proportion=Count('brand_name')/Count('brand_name', filter=Q(brand_category="brand_category"))#I'm stuck here return JsonResponse(list(all_brands), safe=False) I am not sure to filter the brand category and count the number of brands in that category. For example: brand_category 'A' might have: Brand 1,Brand 1 ,Brand 1,Brand 2,Brand 2 Here, the proportion of Brand 1 in category A would be 3/5 = 0.6 or 60% I can calculate the 3 using Count('brand_name') within the queryset, but how can i calculate the 5? brand_category 'B' might have: Brand 1,Brand 2,Brand 3,Brand 4,Brand 5 Here, the proportion of Brand 1 in category B would be 1/5 = 0.2 or 20% Please help.Thanks. -
I want members +1
I am currently trying to create a many to many field that will allow a user to create an organization with a name and a description. I would like to show how the name of the different users in the org as well as the creator. Is there a way for me to automatically count the creator of the org as a member without rewriting too much of my code? ATM even if the user is the admin of the org the member count remains 0. -
NoReverseMatch error when using reverse function
I am trying to redirect from one view to another and I get the following error: NoReverseMatch at /challenges/1/answer/ Reverse for 'results' with arguments '(1,'test')' not found. 1 pattern(s) tried: ['challenges\/(?P<challenge_id>[0-9]+)\/results\/$'] I have the following code in models.py: def answer(request, challenge_id): challenge = ... result = "test" return HttpResponseRedirect(reverse('challenges:results', args=(challenge.id, result))) def results(request, challenge_id, result): My understanding is that 'reverse' in an HttpResponseRedirect would redirect to results if I pass the 'result' in args? Thanks in advance! -
Query for Intermediate table in Django
Hello how are you? I want to ask you a query on intermediate tables, with a problem that I cannot solve and that I thought was not that difficult. I have a "many to many" relationship between two tables (Sample, Test) using the classes: class Sample (models.Model): tests = ChainedManyToManyField ( 'Test', horizontal = True, chained_field = 'matrix', chained_model_field = 'matrix', through = 'SampleTests' ) class Test (models.Model): test = models.CharField (max_length = 255, blank = True, null = True) class SampleTests (models.Model): test = models.ForeignKey ('Test', models.DO_NOTHING) sample = models.ForeignKey ('Sample', models.DO_NOTHING) class Meta: verbose_name = "Result" verbose_name_plural = "Results" In the Class SampleTests, I put the "verbose_name_plural =" Results "" because I plan to put one more field to put the result of each test in it. As I want to work everything in the Django admin, I configured the admin.py adding: admin.site.register (SampleTest), so in this way I can enter from the menu to this area of "Results" (SampleTest class). But when I click, it throws me this error: "django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: ERRORS: <class 'applications.lab.admin.SampleAdmin'>: (admin.E013) The value of 'fields' cannot include the ManyToManyField 'tests', because that field manually specifies a relationship model. … -
How do I make custom filters work in django_filters?
So I've made this custom filter in filters.py with Django-filters and when I'm submitting the "YEARCHOICE" from templates, the page refreshes but it doesn't work. I think I'm having a problem with my "year_filter_method" also I want my pagination and filter system to work together. Any help would be really appreciated. Cheers! *Note it doesn't work with or without pagination. models.py from django.db import models import datetime YEAR_CHOICES = [] for r in range(2000, (datetime.datetime.now().year + 1)): YEAR_CHOICES.append((r, r)) class Music(models.Model): Song = models.CharField(max_length=100, blank=False) Year = models.IntegerField(('year'), choices=YEAR_CHOICES, default=datetime.datetime.now().year) def __str__(self): return self.Song filters.py import django_filters import datetime class MusicFilter(django_filters.FilterSet): YEARCHOICES = [] for r in range(2010, (datetime.datetime.now().year + 1)): YEARCHOICES.append((r, r)) year_filter = django_filters.ChoiceFilter(label="Year", choices=YEARCHOICES, method="year_filter_method") def year_filter_method(self, queryset): expression = YEARCHOICES return queryset.filter(expression) views.py def music_page(request): #pagination & filter music = Music.objects.all().order_by('-id') music_filter = MusicFilter(request.GET, queryset=music) paginator = Paginator(music, 6) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) try: music = paginator.page(page_number) except PageNotAnInteger: music = paginator.page(1) except EmptyPage: music.paginator.page(paginator.num_pages) return render(request, template_name='main/music.html', context={'music': music, 'page_obj': page_obj, 'filter': music_filter}) filters.html {% load static %} <link rel="stylesheet" href="{% static 'main/filter.css' %}" type="text/css"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <div class="container"> <form method="get"> <span class="label">{{filter.form}}</span> <span class="btn-search-handler"><button id="search_btn_id" type="submit">Search</button></span> </form> </div> music.html {% … -
Specify __str__() Representation in Django Admin list_display
Not sure if this is a good way to do things (this is more of a technical question), but what if I have a Django model with __str__ function that combines several fields: def __str__(self): return f'{self.field0} {self.field1} {self.field2}' In the admin, I might have the list_display like so: list_display = ['field0', 'field1'] How do I specify this to use the object representation returned by the __str__ function? list_display = [<__str__() representation>, 'field0', 'field1'] By default, if you don't specify list_display in the admin, it'll give me what I want. Can't I have both? -
Save the data of current logged user in django
I am a newbie in django and I have a question about how I can save and show only the data of logged user - since my application is multi-tenant. my view class ProjetoCreate(CreateView): model = Projeto fields = ['nomeProjeto', 'descricao', 'dtInicio', 'deadline', 'nomeSprint', 'status', ] def get_queryset(self): logged_user = self.request.user return Projeto.objects.filter(User=logged_user) my model class Projeto(models.Model): nomeProjeto = models.CharField(max_length=20) descricao = HTMLField() dtInicio = models.DateField(auto_now=False, auto_now_add=False) deadline = models.DateField(auto_now=False, auto_now_add=False) nomeSprint = models.CharField(max_length=30) status = models.CharField(max_length=20) Thank you very much! -
Django: Uploading a CSV file to AWS S3
We have a Django application that needs to create a csv file on user demand and upload it to AWS S3. We have a function that creates an HttpResponse object response with content_type="text/csv" We have tried a number of things: boto3: s3 = boto3.client("s3") s3.put_object(Body=response.content, Bucket="my-bucket", Key="file_path_and_name.csv") This worked in my local machine, but when deployed to Google App Environment, we got an error that said boto3 could not find credentials. The AWS credentials are in our app settings file. (How would it work on my local machine if we didn't?) django-storages: We have successfully used storages to allow users to download files from this same s3 bucket, within the same app (both locally and deployed). So I thought I would give it a try: storage = S3Boto3Storage() storage.save("file_path_and_name.csv", response.content) This produced the error: AttributeError: 'bytes' object has no attribute 'seek' This is because the save method in S3Boto3Storage calls content.seek(0, os.SEEK_SET) So... Does that mean S3Boto3Storage cannot take a bytestring input file, like boto3 does? (I thought the S3Boto3Storage backend was built right on top of boto3?) I tried io.StringIO(response.content.decode("utf-8")) but I got another error that said the string needed to be encoded before it was hashed. At that … -
Trying to "pip install reportlab==3.0" and I get a crazy long error with include header <string.h>
I am trying to pip install reportlab==3.0 and I am not having any luck getting past this error. Can someone tell me what I am missing? The latest version of reportlab installs okay but I can't use that. I have tried easy_install and all versions. It seems that < 3.0 I will get the same error but with > 3.0 I am okay. I have also made sure my headers are linked. It looks like towards the end there is even some javascript errors? This has had me stumped #Attempting install of _rl_accel & pyHnj #extensions from '/private/var/folders/x6/wyq9wg250c7d7s933sp1fgtw0000gn/T/pip-build-L1Xdbd/reportlab/src/rl_addons/rl_accel' ################################################ ################################################ #Attempting install of _renderPM #extensions from '/private/var/folders/x6/wyq9wg250c7d7s933sp1fgtw0000gn/T/pip-build-L1Xdbd/reportlab/src/rl_addons/renderPM' will use package libart 2.3.12 # installing without freetype no ttf, sorry! # You need to install a static library version of the freetype2 software # If you need truetype support in renderPM # You may need to edit setup.cfg (win32) # or edit this file to access the library if it is installed ################################################ Standard T1 font curves already downloaded running install running build running build_py creating build creating build/lib.macosx-10.15-x86_64-2.7 creating build/lib.macosx-10.15-x86_64-2.7/reportlab copying src/reportlab/rl_config.py -> build/lib.macosx-10.15-x86_64-2.7/reportlab copying src/reportlab/__init__.py -> build/lib.macosx-10.15-x86_64-2.7/reportlab copying src/reportlab/rl_settings.py -> build/lib.macosx-10.15-x86_64-2.7/reportlab creating build/lib.macosx-10.15-x86_64-2.7/reportlab/graphics creating build/lib.macosx-10.15-x86_64-2.7/reportlab/graphics/charts copying src/reportlab/graphics/charts/slidebox.py -> build/lib.macosx-10.15-x86_64-2.7/reportlab/graphics/charts … -
Paramiko stdout.readlines() is too slow
I am using Paramiko in my Python & Django code to execute command. Here is my code: client = SSHClient() client.set_missing_host_key_policy(AutoAddPolicy()) client.connect(<host>, username=<username>, password=<password>) stdin, stdout, stderr = client.exec_command("curl -X POST http://127.0.0.1:8080/predictions -T image.jpg") lines = stdout.readlines() The execution time of stdout.readlines() is 0.59 for each command. This is not acceptable time for my close-to-real time system. Could anyone give any suggestion to make reading process faster? Best. -
Python Flask and Ajax forms
trying to post a flask-wtf form through ajax. I believe I have narrowed it down to the error being in the data variable but not sure. I would like to ideally send the whole form through ajax using flask-wtf. Ajax Call <script > $(document).on('click', '#click-btn-post-comment-{{ post.id }}', function(event) { var csrf_token = "{{ csrf_token() }}"; event.preventDefault(); $.ajax({ url: "{{ url_for('create.createcommentquick', postid=post.id) }}", type: "POST", contentType: 'application/json;charset=UTF-8', data: $('subpostcommentform-{{ post.id }}').serialize() , headers: { "X-CSRFToken": csrf_token, }, success: function(data) { if (data.result == 'success') { $('div#success_post_' + data.thepostid).append(data.commentbody); return data; } else { console.log(data) } }, error: function() { }, }); event.preventDefault(); }); </script> My Form - Please note its in a loop! {% if subpostcommentform %} {% include 'common/js/post/quick_post.html' %} <div class="col-12 p-0 m-0 border-top border-dark pt-1"> <form class="p-0 m-0" method="POST" id="selectDevice" action="{{ url_for('create.createcommentquick',postid=post.id) }}" id="subpostcommentform-{{ post.id }}"> {{ subpostcommentform.csrf_token }} <div class="form-group row w-100 p-0 m-0 "> <div class="col-1 p-0 m-0"> {% if current_user.profileimage %} {% if current_user.profileimage == '' %} <img src="{{ url_for('static', filename='images/noprofile.png') }}" style="width:30px;height: 30px" > {% else %} <a href="{{ url_for('profile.main', user_name=current_user.user_name) }}"> <img alt="{{ url_for('static', filename='images/noprofile.png') }}" class="img-responsive" src="{{ url_for('common.profile_image', filename=current_user.profileimage) }}" style="width:30px;height: 30px"> </a> {% endif %} {% endif %} </div> <div class="col-9 … -
Why do I get an IntegrityError when calling Django's create_user helper function?
The current Django doc on Creating users says that the following helper function can be used to create a user: >>> from django.contrib.auth.models import User >>> user = User.objects.create_user('john', 'lennon@thebeatles.com', 'johnpassword') But when I run this code in the Python shell I get this error: django.db.utils.IntegrityError: null value in column "last_login" violates no-null constraint DETAIL: Failing row contains (7, <hashed password>, null, f, john, ... Is the documentation incorrect? I understand that the User object contains a required last_login field but the documentation seems to imply that this helper function will take care of populating it.