Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can't connect to mysqldb in Django "ImportError: cannot import name 'CLIENT' from 'MySQLdb.constants' (unknown location)"
I have been fought all day, but i fail. I have problem with connection to MYSQL database. I using Linux Debian and i try connect to local database, but something went wrong :/. Bellow attached settings.py # settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'dbDjango', 'USER': 'user', 'PASSWORD': '*******', 'HOST': '127.0.0.1', 'PORT': '3306', } But, when i run server using python3.7 manage.py runserver the program call back me error like this: File "/usr/local/lib/python3.7/dist-packages/django/contrib/auth/models.py", line 2, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "/usr/local/lib/python3.7/dist-packages/django/contrib/auth/base_user.py", line 47, in <module> class AbstractBaseUser(models.Model): File "/usr/local/lib/python3.7/dist-packages/django/db/models/base.py", line 117, in __new__ new_class.add_to_class('_meta', Options(meta, app_label)) File "/usr/local/lib/python3.7/dist-packages/django/db/models/base.py", line 321, in add_to_class value.contribute_to_class(cls, name) File "/usr/local/lib/python3.7/dist-packages/django/db/models/options.py", line 204, in contribute_to_class self.db_table = truncate_name(self.db_table, connection.ops.max_name_length()) File "/usr/local/lib/python3.7/dist-packages/django/db/__init__.py", line 28, in __getattr__ return getattr(connections[DEFAULT_DB_ALIAS], item) File "/usr/local/lib/python3.7/dist-packages/django/db/utils.py", line 201, in __getitem__ backend = load_backend(db['ENGINE']) File "/usr/local/lib/python3.7/dist-packages/django/db/utils.py", line 110, in load_backend return import_module('%s.base' % backend_name) File "/usr/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "/usr/local/lib/python3.7/dist-packages/django/db/backends/mysql/base.py", line 22, in <module> from MySQLdb.constants import CLIENT, FIELD_TYPE # isort:skip ImportError: cannot import name 'CLIENT' from 'MySQLdb.constants' (unknown location) Mysql as service is runing: ervice mysql status ● mysql.service - MySQL Community Server Loaded: loaded (/lib/systemd/system/mysql.service; disabled; vendor preset: disabled) … -
ModelChoiceField causing decimal.invalidoperation, even with def __str__ on model set to return the name
I have a forms.py and this little nugget here: from mainpage.models import Institution institution = forms.ModelChoiceField(queryset=Institution.objects.all(), empty_label="(Select One)", to_field_name="institution_name", widget=forms.Select( attrs={ 'tabindex':'7','class':'form-control' } ) ) It causes that decimal.invalidoperation once I have this piece of code in it, even though my InstitutionModel is as such (in another app) class Institution(models.Model): objects = models.Manager() institution_id = models.CharField(max_length=10) institution_name = models.CharField(max_length=100) institution_precentages = models.DecimalField(max_digits = 4, decimal_places=2) #might have to change this def __str__(self): return self.institution_name I even tested in the view trying to render all this a quick little p = Institution.objects.first() print(p) Worked fine, not sure what else to try or what I am missing. -
Implementing one to many between and article and page models
I'm trying to setup a wagtail site with an article to pages structure but I'm struggling. A review article for example may have an introduction page, a benchmark page and a conclusion page. I can't work out how to allow this relationship in wagtail and have it so that editors can add multiple pages to the same article on the same page. I imagine the pages interface looking a bit like how you have content, promote and settings on pages but with the ability to add, rename and reorder pages. I've tried using a foreign key on a page model that links to an article but I can't get it to be shown in the admin the way I want. -
Duplicated values after select related field
I have simple forum application: # models class Topic(models.Model): title = models.CharField(max_length=255) class Message(models.Model): text = models.TextField() topic = models.ForeignKey(Topic, related_name='messages') # views class SearchView(ListView): ... def get_queryset(self): search_vector = SearchVector('messages__text') search_query = SearchQuery(self.request.GET.get('query')) topics = Topic.objects.annotate( rank=SearchRank(search_vector, search_query) ).filter(rank__gte=0.0).order_by('-rank') return topics I want have full text search in my forum. Everything works but in topic query results I got duplicated objects. <QuerySet [<Topic: 1>, <Topic 1>, <Topic 2>, <Topic 1>, ...]> I think that it happens because of multiple messages in one topic that gives me different rank values. How can I remove duplicated topics but keep rank ordering? -
How to pass json dictionary from javascript .get to django template?
In the head of my django template I currently have: <script> $.get('get_students/', function (dict) { alert(dict) }) </script> This alerts me of a json dictionary corresponding to dict, which comes from the following django view: def get_students(request): students = Student.objects.all() students_json = serializers.serialize('json', students) return HttpResponse(json.dumps(students_json), content_type='application/json') Is it possible to "escape" dict from the script tag into the normal Django template so that I can iterate over it with something like: {% for d in dict%} <p>d.username</p> {% endfor %} Thanks! -
AJAX loading gif before showing the page for a certain time ,, how to do it?
i want to make an ajax or javascript loading gif image for a certain time before showing any contents of the page in a django project ,, searched alot but still have no idea how to make it .. '''function readText () { var value1 = document.getElementById("trcode").value; var value2 = document.getElementById("trfcode").value; if (value1 === value2) { location.href="trfresultdetails"; } else { alert("You Typed: " + "Wrong Passord");} }''' -
Model inheritance: benefits of explicit OneToOneField vs implicit multi-table inheritance OneToOneField
I read here that multi-table inheritance can cause performance issues, and instead explicit OneToOneField is recommended. Here is my situation: class Product(models.Model): title = models.CharField(max_length=200) description = models.TextField() price = models.DecimalField(decimal_places=2, max_digits=10) category = models.ForeignKey('Category', on_delete=models.CASCADE, blank=False) class Book(Product): publisher = models.CharField(max_length=50) author = models.CharField(max_length=50) isbn = models.CharField(max_length=50) class Shoes(Product): size = models.PositiveSmallIntegerField() colour = models.CharField(max_length=20, choices=[('black', 'Black'), ('white', 'White')]) I don't understand why would explicit OneToOneField bring performance gains, when multi-table inheritance is implemented in exactly the same way: place_ptr = models.OneToOneField( Place, on_delete=models.CASCADE, parent_link=True, ) If this is true despite everything, I would like to know how could I alter my models so they use explicit OneToOneField. So, if I create a Book instance, Product.objects.all() should retrieve that instance of Book, too. -
Django - How to link the current authenticated user with the data provided by a form
Sorry if the question is too basic but I've read the documentation and many articles and none of them seem to answer my question. I want to link a posted form by an user with that user into the DB, so I can query the data provided for each particular user and use delete on CASCADE in the event the user is deleted. I tried creating a Model, then a ModelForm based on that Model. I add a field named "user" in the Model as a ForeignKey, so in the ModelForm is translated to ModelChoiceField which by the way is hidden, since the user shouldn't change that value. But when I try to update the user field in the views.py, nothing happens, the form is saved into the database, but the user field remains as None or Null in the DB. models.py class Foo(models.Model): user = models.ForeignKey(User, related_name='+', on_delete=models.CASCADE) forms.py class FooForm(ModelForm): class Meta: model = Foo fields = ['user', 'field1', 'field2'] exclude = ['user'] views.py def index(request): if request.user.is_authenticated: if request.method == 'POST': foo = FooForm(request.POST) if foo.is_valid(): foo.save(commit=False) foo.user = request.user foo.save() I got the posted Form saved into the DB but the user field is NULL. Of … -
Django: is this data migration going to blow the server memory?
I'm trying to migrate the data from an old table to a new table and I'm not sure what the best way would be. There's the simple solution of creating every object: def migrate_data(apps, schema_editor): UserPreferences = apps.get_model("authentication", "UserPreferences") UserPreferencesOld = apps.get_model("authentication", "UserPreferencesOld") for user_preferences_old in UserPreferencesOld.objects.all(): user_preferences = UserPreferences( date_modified=user_preferences_old.date_modified, email_notifications=user_preferences_old.email_notifications, show_message_deadline_summary=( user_preferences_old.show_message_deadline_summary ), user=user_preferences_old.user, ) user_preferences.save() And the bulk create solution: def migrate_data(apps, schema_editor): UserPreferences = apps.get_model("authentication", "UserPreferences") UserPreferencesOld = apps.get_model("authentication", "UserPreferencesOld") UserPreferences.objects.bulk_create( [ UserPreferences( date_modified=user_preferences_old.date_modified, email_notifications=user_preferences_old.email_notifications, show_message_deadline_summary=( user_preferences_old.show_message_deadline_summary ), user=user_preferences_old.user, ) for user_preferences_old in UserPreferencesOld.objects.all() ] ) The table I need to migrate has tens of thousands of entries and I'm afraid that the first option will take forever, making tens of thousands of requests to the database, while the second option will blow the memory on the server. Any suggestions on what would be the better option? Thanks! -
How do you get the current cursor with CursorPagination?
By default, CursorPagination gives you the next and previous cursors. Is there a way to get the current cursor? -
How can you customize object creation in django?
In django rest framework, it's possible to make a function to customize the process of creating an object inside the serializer of that respective model, but I can't figure out how to do that in "vanilla" django, so to speak. What I need to do is take one field and do a bunch of stuff with it. encode it into a 256 character hash is all I have to worry about now. How can I go about doing what I need? I've been basing myself off of an online course and Django's documentation, but I either couldn't interpret it well enough or I just straight up haven't found it there. Here is the code I have so far, at least what I judge is relevant to the question. It's all in models.py: class SpedFile(models.Model): json_file = models.FileField(max_length=100) sped_file = models.FileField(max_length=100) integrity_hash = models.CharField(max_length=256) line_counter = models.CharField(max_length=150000) created_at = models.DateField(auto_now_add=True) @classmethod def create(cls, json_file): file_bearer = json_file m = hashlib.sha256() m.update(file_bearer.encode('utf-8')) integrity_hash = m.hexdigest() new_object = cls(json_file=file_bearer, integrity_hash=integrity_hash) return new_object -
How to write subquery in django
Is it possible to make following sql query in django select * from ( select * from users ) order by id It is just minimal example. I have a long subquery instead of select * from users. But I can't understand how insert it into subquery. -
Django Jinja2 How to get form data on a different view
I am loading my registration form on the base url (localhost:8000/). It's a Jinja2 template and running on top of Django. Let's FrontEnd app is frontend <form class="registration_form" style="display: none" method="POST" action="/"> <div class="form-group"> <input type="text" class="form-control" id="InputFirst" placeholder="First Name"> </div> <div class="form-group"> <input type="text" class="form-control" id="InputLast" placeholder="Last Name"> </div> <div class="form-group"> <input type="email" class="form-control" id="InputEmail" aria-describedby="emailHelp" placeholder="Enter email"> <small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small> </div> <div class="form-group"> <input type="password" class="form-control" id="InputPassword" placeholder="Password"> </div> <button type="submit" class="btn btn-primary btn-lg btn-block actions"> Registration</button> </form> Now, I have written my Registration API, on user app and it's accessed via /user/registration/. How can I send the form data on that VIew instead of the front_end view? I am using APIView of DRF for registration API. I have tried to add {{ url_for('user/registration/') }} on actions. It doesn't work For some reason, I can't use any other front-end framework, I have to make do with jinja2. Thanks in Advance. -
celery task in multiple queues not start
i use django with celery and redis to work with asynchronous tasks. I have three task defined which should run in your own queue. My project structure looks like this: django-project |- api |- task.py |- view.py |- django-project |- settings.py |- celery.py |- __init__.py My tasks defined in the task.py in my api app: @shared_task def manually_task(website_id): print("manually_task"); website = Website.objects.get(pk=website_id) x = Proxy(website, "49152") x.startproxy() x = None @periodic_task(run_every=(crontab(hour=19, minute=15)), ignore_result=True) def periodically_task(): websites = Website.objects.all() for website in websites: x = Proxy(website, "49153") x.startproxy() x = None @shared_task def firsttime_task(website_id): website = Website.objects.get(pk=website_id) x = Proxy(website, "49154") x.startproxy() x = None Now here is my init.py __all__ = ('celery_app',) and the celery settings in the settings.py: CELERY_BROKER_URL = 'redis://localhost:6379' CELERY_RESULT_BACKEND = 'redis://localhost:6379' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_RESULT_SERIALIZER = 'json' CELERY_TASK_SERIALIZER = 'json' CELERY_TIMEZONE = 'Europe/Berlin' CELERY_DEFAULT_QUEUE = 'red' CELERY_TASK_QUEUES = ( Queue('red', Exchange('red'), routing_key='red'), ) CELERY_ROUTES = { 'api.tasks.manually_task': {'queue': 'red'}, } My celery.py looks like this: os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'django-project.settings') app = Celery('django-project') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() This was my settings. Now i start all the needed stuff (every line in own terminal): redis-server celery -A django-project worker -Q red python3 manage.py runserver 0.0.0.0:8000 All starts without problems. In the … -
Struggling with connection between Django and Postgres within Docker containers
I've been hitting the following error for awhile now and can't seem to fix it... django.db.utils.OperationalError: could not connect to server: Connection refused Is the server running on host "127.0.0.1" and accepting TCP/IP connections on port 5432? Multiple resources stated it was simply due to the HOST setting within my DATABASES, but the following is what I am working with and still can't get it to work: DATABASES = { 'default': { 'HOST': 'db', 'ENGINE': 'django_postgrespool2', 'NAME': os.environ.get('PROJECT_HEARSAY_DB_NAME'), 'USER': os.environ.get('PROJECT_HEARSAY_DB_USER'), 'PASSWORD': os.environ.get('PROJECT_HEARSAY_DB_PASSWORD'), 'PORT': os.environ.get('PROJECT_HEARSAY_DB_PORT'), } } Here is the Dockerfile for my Django app: FROM python:3 ENV PYTHONUNBUFFERED 1 COPY . /app WORKDIR /app RUN pip install --upgrade pip RUN pip install -r requirements.txt Here is the Dockerfile for my Postgresql DB: FROM postgres And here is the docker-compose.yml that I am working with: version: "3" services: postgresql: build: context: ./db container_name: db.postgresql ports: - 5432:5432 environment: POSTGRES_DB: "db_name" POSTGRES_USER: "username" POSTGRES_PASSWORD: "password" django: restart: always build: context: ./api command: bash -c "./manage.py migrate && ./manage.py runserver 0.0.0.0:8000" container_name: api.django ports: - 8000:8000 depends_on: - postgresql I'm curious if anyone here could shed some light on what I am doing wrong. Thank you. -
How to create multiple datetimepickers in django template (for loop) and jquery
I am having trouble getting django to display multiple datetimepickers in tabs on a html page. I can get them to work if I specify each element in the jquery outside of a loop, but when I put it in a loop, they don't show (only shows an empty input text box). As this has to be done on an array of varying sizes (min length of 1 and no max), I can't hard code each individual datetimepicker. The for loop on the django template html page works, and each tab and the sections where the datetimepickers go is made, but the jquery won't work. I have tried to make the 4 datetimepickers via a loop (4 per tab, can have 1+ tabs), and they don't create the datetimepicker object. Just creates a input text box. I have also tried putting them all into a class=datetimepicker, which does work, but then I can't add in default data from the array to fill in each datetimepicker, as the only function in jquery is a single one calling the class .datetimepicker. Tried $('#date1').datetimepicker({ defaultDate: array[counter][0] }) in an array to fill in each tab for the date1 datetimepicker, and that does not … -
MySql errors while executing queries on a Django project on AWS Lambda function
I have a Django project hosted on AWS Lambda function. This microservice uses pymysql to connect to AWS Aurora RDS database. This service executes one and only one query over and over again. 1 in 200 times the query fails with EOF packet error. In order to investigate this issue i have implemented a "repeater" which would repeat the same query if one fails (maximum 2 repeats with 0.25 seconds delay). Once again, in a rare ocasion, a query has failed and I expected to see a successful query after the first reattempt. However it failed in all 3 consecutive calls with all DIFFERENT error messages. Error messages (in order): AssertionError: Protocol error, expecting EOF django.db.utils.InternalError: Packet sequence number wrong - got 24 expected 1 django.db.utils.InterfaceError: (0, '') These are errors from 3 separate queries executed against MySql Aurora RDS database. (I just wanted to ephesize that indeed it is not a stack trace but rather different query errors). More useful info: The microservice uses Django ORM to create queries. The database is in Master-Slave configuration and those queries go against a Slave database. The parameters observed in Master and Slave databases (such as CPU usage, free RAM space, various … -
Submit a form, force download a pdf, after that redirect to another page, can we do this without using frontend/js?
I have a post form, I want to download a pdf receipt after submitting form, and then redirect to another page. form.submit >> force downlaod pdf >>> redirect. and I want to do this only at the server-side, is there any idea to do this without using js. -
Serialize related object before primary key is created
So I have a serializer which I have added a custom create method for, because I am using it to insert objects for a many-to-many relationship and am using nested serializers for this. As it stands, when I try to create and object using the DocumentSerializer, I get a "document":["This field is required."] error, because when the documentdomain_set variable is declared, the associated document has yet to be created, and therefore there is no id to be used in the relation. I obviously know how to capture this document_id after saving the new document object, but I am not sure what the best practice is to handle the variable initiation as it stands. Thanks! class DocumentDomainSerializer(serializers.ModelSerializer): domain = serializers.SerializerMethodField('get_domain_id') class Meta: model = DocumentDomain fields = ('document_id', 'domain_id') class DocumentSerializer(serializers.ModelSerializer): documentdomain_set = DocumentDomainSerializer(many=True, required=False) class Meta: model = Document fields = ( 'documentdomain_set', 'id', 'text', 'uploaded_at') extra_kwargs = { 'id': {'read_only': True}, 'uploaded_at': {'read_only': True} } def create(self, validated_data): documentdomain_set = documentdomain_set.pop('documentdomain_set', []) # create document first document = Document.objects.create(**validated_data) # serialize associated domains for documentdomain in documentdomain_set: # get ID of newly-created document, use for relation documentdomain['document_id'] = document DocumentDomain.objects.create(**documentdomain) return document -
Getting "Bad Request" on the post request to Django Rest-Api using serializers
I am trying to save data into a model using django-rest framework. I have already written the api, it works fine when i access it directly using the url to api. But I get a bad-request error when i try to post data using ajax. If it is working fine when data is inserted using the api interface, it should work fine when data is inserted using ajax....but instead i am getting a bad request. here is the AJAX request method(Jquery): $("form").submit(function(event){ event.preventDefault(); var this_ = $(this); var formData =this_.serialize(); $.ajax({ url: "/api/forum/posts/{{ post_question.thread_id.id }}/create", data: formData, method: "POST", success: function (data) { console.log("successfully returned"); console.log(data); displayPosts(); }, }) Serializers are as follow, in api/serializers.py : class ThreadModelSerializer(serializers.ModelSerializer): created_by = UserDisplaySerializer(read_only=True) class Meta: model = Thread fields = '__all__' class PostModelSerializer(serializers.ModelSerializer): posted_by = UserDisplaySerializer(read_only=True) class Meta: model = Post fields = '__all__' Models for the Post and Thread are as follow in models.py: class Thread(models.Model): thread_subject = models.CharField(max_length=250) posted_on = models.DateTimeField(auto_now=True) category = models.CharField(max_length=250) forum_id = models.ForeignKey(Forum, on_delete=models.CASCADE) created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) class Post(models.Model): post_message = models.TextField() thread_id = models.ForeignKey(Thread, on_delete=models.CASCADE) parent_id = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True) posted_on = models.DateTimeField(auto_now=True) posted_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) and finally the API view is … -
Python django TypeError at /cart/update/ 'NoneType' object is not iterable
enter image description here Hello I have the following error on my browser: TypeError at /cart/update/ 'NoneType' object is not iterable Exception Location: C:\Users\Gijs Machielsen\dev\ecommerce\src\carts\views.py in cart_update, line 19 ########## my views.py contains the following code: from django.shortcuts import render, redirect from products.models import Product from .models import Cart def cart_home(request): cart_obj, new_obj = Cart.objects.new_or_get(request) return render(request, "carts/home.html", {"cart": cart_obj}) def cart_update(request): product_id = request.POST.get('product_id') if product_id is not None: try: product_obj = Product.objects.get(id=product_id) except Product.DoesNotExist: print("Show message, product is gone ") return redirect("cart:home") cart_obj, new_obj = Cart.objects.new_or_get(request) !!!! line 19 if product_obj in cart_obj.products.all(): cart_obj.products.remove(product_obj) else: cart_obj.products.add(product_obj) return redirect("cart:home") ## models.py is the following: from decimal import Decimal from django.conf import settings from django.db import models from django.db.models.signals import pre_save, post_save, m2m_changed from products.models import Product User = settings.AUTH_USER_MODEL class CartManager(models.Manager): def new_or_get(self, request): cart_id = request.session.get("cart_id", None) qs = self.get_queryset().filter(id=cart_id) if qs.count() == 1: new_obj = False cart_obj = qs.first() if request.user.is_authenticated() and cart_obj.user is None: cart_obj.user = request.user cart_obj.save() else: cart_obj = Cart.objects.new(user=request.user) new_obj = True request.session['cart_id'] = cart_obj.id return cart_obj, new_obj def new(self, user=None): user_obj = None if user is not None: if user.is_authenticated(): user_obj = user return self.model.objects.create(user=user_obj) Create your models here. class Cart(models.Model): user … -
Page not found after trying to add a new path to the urlpatterns of main urls.py file? (Mosh Python Tutorial)
I'm following Mosh's tutorial video on Python. He begins the django section (https://youtu.be/_uQrJ0TkZlc?t=18085) by installing django 2.1. I am able to open a development server the first time as he does: pip install django==2.1 django-admin startproject pyshop . python manage.py runserver #server works Here are the steps he goes through to add a "products" app/path: python manage.py startapp products Opens views.py from this new products folder and modifies code to this: from django.http import HttpResponse from django.shortcuts import render def index(request): return HttpResponse('Hello World') Creates urls.py inside the products app/folder and adds this code: from django.urls import path from . import views urlpatterns = [ path(' ', views.index) ] Opens the main urls.py in the pyshop folder and adds/modifies the end of the file like this: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('products/', include('products.urls')) ] Mosh goes back to the server and adds /python to the url to get a page with "Hello World" (https://youtu.be/_uQrJ0TkZlc?t=19220) Upon trying to run the server again, I get Page not found error. Is there something I'm missing? I didn't figure it'd be a version issue since I made sure and installed the same 2.1 version. -
Adding a profile to user in django
Following this : https://simpleisbetterthancomplex.com/tutorial/2016/07/22/how-to-extend-django-user-model.html#onetoone I am having some trouble with this call: @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) In their example I am guessing this works as is on the signup of a new account because the Profile in their example has all fields that can be blank and null. In my case my profile I am trying to maintain here is called: class APOUser(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) institution = models.ForeignKey("mainpage.InstitutionMember", on_delete=models.PROTECT) gender = models.ForeignKey("mainpage.GenderTable", on_delete=models.PROTECT) on_site_status = models.ForeignKey("mainpage.SiteStatus", on_delete=models.PROTECT) refer_to_as = models.TextField(max_length = 30, blank=True) #if the above is custom room_preference = models.ForeignKey("housing.Room", on_delete=models.PROTECT) Which has references to ultimately what will be drop downs to select form a form (populated by another table with defaults). So do I remove the @reciever and then just have the users fill out the profile separately somehow after they signup and confirm their account? I tried to mix my signup form with the profile form... but kept getting an anonmyous user object had no attribute object apouser in the views.py when I try to mix the signup forms and profile forms: def signup(request): if request.method == 'POST': form = SignUpForm(request.POST) profile_form = ProfileForm(request.POST, instance=request.user.apouser) if form.is_valid() and profile_form.is_valid(): … -
convert page to pdf and render on screen
I can convert a page to pdf perfectly, however, I need to render a graphic that is made with javascript, in this case I first need to render the page to be able to compile to pdf and render on screen, could someone help me? I am using lib django-weasyprint -
How to change default image in Django
I have a django app that allows users to fill out a form, and attach an image if they like. If they decide not to attach an image, I want a default image in it's place. The problem is that when the user tries to attach an image during the post creation, it doesn't save. It only saves when the post is edited. model field: image = models.ImageField(upload_to='images/', default = 'noImageAttached.png') This works as expected when a user creates a new post and does not add a new image. The default image 'noImageAttached.png' is used. However, when someone wants to attach an image in theCreateView it will not throw any errors, it just will simply not save the image. When this same post is edited with UpdateView, you can upload an image, and it works. Something in my CreateView is causing it to not work? Or maybe there is a different way of using default in models.py? views.py class assetCreateView(LoginRequiredMixin,CreateView): model = Assets form_class = Asset_Creation_Form template_name = 'addAsset.html' login_url = 'login' success_url = reverse_lazy('home') #these fields are hidden from user, and filled out automatically def form_valid(self, form): form.instance.createdBy = (self.request.user.first_name)+ " "+ (self.request.user.last_name) return super().form_valid(form)