Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why django inspectdb skips some ids?
I was running inspectdb on my schema. At first, the defitions are very correct like these: class Diagnosis(models.Model): id = models.BigIntegerField(primary_key=True) code = models.CharField(max_length=255) starting_node = models.ForeignKey('Node', models.DO_NOTHING, blank=True, null=True) class Meta: managed = False db_table = 'diagnosis' class DiagnosisTranslation(models.Model): id = models.IntegerField(primary_key=True) language = models.CharField(max_length=10) title = models.CharField(max_length=255, blank=True, null=True) description = models.TextField(blank=True, null=True) diagnosis = models.ForeignKey(Diagnosis, models.DO_NOTHING, blank=True, null=True) class Meta: managed = False db_table = 'diagnosis_translation' Then, I added sequences and default values (postgresql) for Ids: CREATE SEQUENCE diagnosis_id_seq START WITH 100000 INCREMENT BY 1; ALTER TABLE diagnosis ALTER COLUMN id SET default nextval('diagnosis_id_seq'); CREATE SEQUENCE diagnosis_translation_id_seq START WITH 100000 INCREMENT BY 1; ALTER TABLE diagnosis_translation ALTER COLUMN id SET default nextval('diagnosis_translation_id_seq'); I reran again python manage.py inspect, and the outcome changes correctly for diagnosis, but not for the other table, it lacks the id attribute now: class Diagnosis(models.Model): id = models.BigAutoField(primary_key=True) code = models.CharField(max_length=255) starting_node = models.ForeignKey('Node', models.DO_NOTHING, blank=True, null=True) class Meta: managed = False db_table = 'diagnosis' class DiagnosisTranslation(models.Model): # Where's the ID ?? language = models.CharField(max_length=10) title = models.CharField(max_length=255, blank=True, null=True) description = models.TextField(blank=True, null=True) diagnosis = models.ForeignKey(Diagnosis, models.DO_NOTHING, blank=True, null=True) class Meta: managed = False db_table = 'diagnosis_translation' Why does Django omits the … -
Is there a method to populate a Django form field based on another field without using JavaScript?
I am trying to implement a booking system that simply consists of three drop menus. The first one is to choose the location, and the second one is to choose the date. The previous two fields are independent. However, the third one is the time, which is basically the time slots with fixed hours. I mean by fixed hours: 7:00 - 8:00, 8:00 - 9:00, ...etc. The problem is I want to populate the third one based on the first two fields. So for each location I want to check all of the slots for the given date. If it is empty, I will show the time slot. I read a lot of Stack Overflow questions and a lot of tutorials. However, all of them are based on JavaScript which I am trying to avoid. Is it impossible to do it without JavaScript? I am sorry for not providing a code sample because I have no idea about how to do it without JavaScript. -
HTTPS certificates, named servers, CORS
I am not a web dev by profession or education, so I apologize in advance if I am asking this question in a naive / ill-posed way. I have a Django server hosted on "Mom and Pop's Hosting Service TM". This server hosts a web API. It has some random IP address and it's not attached to a domain name. I also have a Vue.js frontend that talks to this API and sends data back and forth to/from it including user auth. (I am using the native Django auth). This Vue.js frontend is hosted in an S3 static hosting bucket and is bound to some domain name: http://www.mystaticfrontend.com (this is just an example, not my actual site). I realize that I need to setup HTTPS certificates in order to encrypt the user authentication that is embedded in all the API requests sent to the Django server as well as all the JSON responses that get sent back and forth. What is the path of least resistance to get this setup? I have been considering migrating my Django server to AWS EC2 because I have read that AWS will generate and manage HTTPS certificates for you. (Maybe there's a simpler way … -
How can I implement a verified field in django?
In Django I'd like to add a field "verified" of type BooleanField to my models which shall indicate if the current model instance has been reviewed by a staff user member or not. Whenever a model instance field other than the "verified" field changed the verified field value shall be reset to False. Whenever only the "verified" field has been changed it's value shall be taken as is (most of the time True but potentially False as well). Using signals to implement something like that seems to be considered an anti-pattern. Instead one should override the save() method. How can I implement something like this most easily. I'd prefer a solution using a third-party package w.o. custom hacks or a solution without any dependencies to other packages. However using django-model-utils monitorfield for a custom implementation or something equivalent would be ok as well. -
Why Django tries to use MySQL instead of sqlite3
My problem is this: When I try to do the migrations, it gives me the following error: python3 manage.py makemigrations Traceback (most recent call last): File "/home/jenifer/.local/lib/python3.7/site-packages/django/db/backends/mysql/base.py", line 16, in <module> import MySQLdb as Database ModuleNotFoundError: No module named 'MySQLdb' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/home/jenifer/.local/lib/python3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/home/jenifer/.local/lib/python3.7/site-packages/django/core/management/__init__.py", line 377, in execute django.setup() File "/home/jenifer/.local/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/jenifer/.local/lib/python3.7/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/home/jenifer/.local/lib/python3.7/site-packages/django/apps/config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/jenifer/.local/lib/python3.7/site-packages/django/contrib/auth/models.py", line 2, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "/home/jenifer/.local/lib/python3.7/site-packages/django/contrib/auth/base_user.py", line 47, in <module> class AbstractBaseUser(models.Model): File "/home/jenifer/.local/lib/python3.7/site-packages/django/db/models/base.py", line 121, in __new__ new_class.add_to_class('_meta', Options(meta, app_label)) File "/home/jenifer/.local/lib/python3.7/site-packages/django/db/models/base.py", line 325, in add_to_class value.contribute_to_class(cls, name) File "/home/jenifer/.local/lib/python3.7/site-packages/django/db/models/options.py", line 208, in … -
DRF import serializer during AppConfig gives incorrect result
i'm not sure how to start this but i try it like this.. Given the following situation: We have an Env-variable PROFILES_SERIALIZER in the form of myapp.serializers.SomeModelSerializer. This serializer should be, due to Env-variable, dynamically changable. (This is relevant for some reason unimportant to the problem). Now I want to have this serializer "imported/available" after the initialization of a certain app called "content" which is done via: class ContentConfig(AppConfig): name = "content" profiles_serializer = None def ready(self): module_ser_class = settings.PROFILES_SERIALIZER.rsplit(".", 1) if any(module_ser_class): self.profiles_serializer = getattr( import_module(module_ser_class[0]), module_ser_class[1] )(many=True) With that i can include this serializer dynamically in a different one for the purpose of nested serialization as follows class TreeNodeSerializer(serializers.ModelSerializer): profiles = django_apps.get_app_config("content").profiles_serializer ... # so one an so forth The resulting views are fine upon the point where we might have nested-serilization within SomeSerializer, for instance class SomeModelSerializer(serializers.ModelSerializer): model1 = ModelOneSerializer() model2 = ModelTwoSerializer() class Meta: model = SomeModel fields = "__all__" If this is the case, any View with serializerclass=TreeNodeSerializer will not show the entries for model1or model2. However if we assume that PROFILES_SERIALIZER = environ.Env("PROFILES_SERIALIZER").rsplit(".",1) This results in the expected behavior: class TreeNodeSerializer(serializers.ModelSerializer): profiles = getattr(import_module(settings.PROFILES_SERIALIZER[0]),settings.PROFILES_SERIALIZER[1])(many=True) ... # so one an so forth My Question is … -
Django-models aren't loaded yet after adding foreignkey
I have looked similar questions in stackoverflow everywhere but nothing helped. My code worked great until I added a foreignkey to one of my models. This is the newly added line: page = models.ForeignKey(Page, on_delete=models.CASCADE, default=Page.objects.get(pk=7).pk) My full models.py looks like this: class Page(Group): pagenumber = models.IntegerField() pagename = models.CharField() class Photo(models.Model): page = models.ForeignKey(Page, on_delete=models.CASCADE, default=Page.objects.get(pk=7)) file = models.FileField(upload_to='photos') After that, when I hit python manage.py makemigrations, The error comes up. Here is a full traceback(note, my code in this question is simplified version of the original one) : Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/home/abrar/.virtualenvs/djangodev/lib/python3.6/site- packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/home/abrar/.virtualenvs/djangodev/lib/python3.6/site- packages/django/core/management/__init__.py", line 377, in execute django.setup() File "/home/abrar/.virtualenvs/djangodev/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/abrar/.virtualenvs/djangodev/lib/python3.6/site- packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/home/abrar/.virtualenvs/djangodev/lib/python3.6/site-packages/django/apps/config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in … -
OperationalError could not connect to server: Connection refused
Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432? Trying to deploy my Django app to Heroku and keep getting the following error. I'm not really sure where to start here... I tried killing all processes on port 5432 and restarting Postgres but I'm not too familiar with how to configure the database on Heroku. Thanks for any help. I'm not quite sure where to start. I've been using the Heroku dev guide and googling the error. Most solutions seem to say to restart Postgres but not working for me. 2020-03-25T05:12:41.000000+00:00 app[api]: Build started by user leary.keegan@gmail.com 2020-03-25T05:13:20.394227+00:00 heroku[web.1]: Restarting 2020-03-25T05:13:20.397813+00:00 heroku[web.1]: State changed from up to starting 2020-03-25T05:13:20.175463+00:00 app[api]: Deploy a13facac by user leary.keegan@gmail.com 2020-03-25T05:13:20.175463+00:00 app[api]: Release v18 created by user leary.keegan@gmail.com 2020-03-25T05:13:21.365822+00:00 heroku[web.1]: Stopping all processes with SIGTERM 2020-03-25T05:13:21.584742+00:00 heroku[web.1]: Process exited with status 0 2020-03-25T05:13:21.376200+00:00 app[web.1]: [2020-03-25 05:13:21 +0000] [9] [INFO] Worker exiting (pid: 9) 2020-03-25T05:13:21.377965+00:00 app[web.1]: [2020-03-25 05:13:21 +0000] [4] [INFO] Handling signal: term 2020-03-25T05:13:21.377967+00:00 app[web.1]: [2020-03-25 05:13:21 +0000] [10] [INFO] Worker exiting (pid: 10) 2020-03-25T05:13:21.477875+00:00 app[web.1]: [2020-03-25 05:13:21 +0000] [4] [INFO] Shutting down: Master 2020-03-25T05:13:24.895930+00:00 heroku[web.1]: Starting process with command `gunicorn life_cal.wsgi --log-file -` 2020-03-25T05:13:28.209650+00:00 app[web.1]: [2020-03-25 05:13:28 +0000] … -
How to keep tweepy stream running from Django even after apache server restart?
I'm building a django-based twitter app that uses Tweepy streaming and I'm curious how to keep the stream running even after the server reboot? The server is Apache. Thank you. -
Creating a web server that uses postresql and python for securing some information
I am working on a project but at some point I had to make a webserver-ish thing. I use that -ish because I am not sure that's the correct way to describe it. Let me explain what I am trying to do: I want to create a library program that normal user installs, register to the system from it and adds a books which he/she owns. The program will do these with getting required information with variables and sending them to the server. Only sending to the server and no more. When server got this data; registers the user and adds the books to the user's inventory with postgresql. After that the user can display the books which she/he owns but user can not display the registered user list. And while user displaying the inventory he/she will be doing it via read-only psycopg2 commands those use same postgreqsl database. The method I thought to do this: Create postgresql database and tables in it. Write a program which can reach these tables with psycopg2. And set different permissions for each operation in user's program. After that I thought another method: Create postgresql database and tables in it. Create a website with … -
django ORM - Exclude on M2M with F-function not working
I have the following models: class Activity(models.Model): user = models.ForeignKey(User, related_name='activities') project = models.ForeignKey(Project, related_name='activities') class Project(models.Model): assignees = models.ManyToManyField(User, related_name='projects') Now I want to query for all the activities which belog to a user which is NOT in the projects assignees. My query: Activity.objects.exclude(project__assignees=F('user')) Problem is, I always get this error: django.db.utils.OperationalError: (1054, "Unknown column 'U2.id' in 'on clause'") Im working on django 2.2.11 and MySQL. I found a couple of old django bugs but they are supposed to be fixed since ages. Any ideas how I can solve my problem? My activity table is huge and I need an efficient way. And I'd be happy to not use raw queries. Thanks! -
How to make popup 'add' window in Django 3?
In django admin, when there is a ForeignKey or ManyToManyField, there is [+] button to add it like this : How can I make that [+] button with popup window using forms in templates ? -
django-revison: how to get Version objects created using RevisionMiddleware in a request
I'm using django-revision, it's a package for versioning the objects state. I'm using it's midddleware (RevisionMiddleware) that wraps all requests and upon catching any changes to a model makes Version objects that store the changes, and I want to catch all Version objects that will be created during the processing of a request. I want to add the id's of the created objects to the request object but after looking at the middleware code I can see that the function that is responsible for creating the Version object doesn't return anything after the creation. Is there an elegant way to do it? -
No module named 'settings_general' when module exists
When I run manage.py in my terminal, I am getting the error ModuleNotFoundError: No module named 'settings_general'. But, this module does exist in the project in a subfolder. I've ran this manage.py many times, but on mac. And now that the pandemic is occurring I am working from home and am working on a PC with Windows 10. I am using cmder for my terminal and conda for my virtual environment. Any suggestions on how to solve this issue would be greatly appreciated. Note: This is worked on with a team and there should not be changes made to the file hierarchy or the contents of the file. Here's my traceback for running "python manage.py migrate": C:\Users\user\work\urec (master -> origin) (urec) λ python manage.py migrate Traceback (most recent call last): File "C:\Users\user\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\core\management\base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\user\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\core\management\base.py", line 366, in execute self.check() File "C:\Users\user\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\core\management\base.py", line 392, in check all_issues = self._run_checks( File "C:\Users\user\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\core\management\commands\migrate.py", line 63, in _run_checks issues = run_checks(tags=[Tags.database]) File "C:\Users\user\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\core\checks\registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\user\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\core\checks\database.py", line 9, in check_database_backends for conn in connections.all(): File "C:\Users\user\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\db\utils.py", line 222, in all return [self[alias] for alias in self] File "C:\Users\user\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\db\utils.py", line 219, in __iter__ … -
Django REST API, after put/patch request, data cannot be seen in the get request anymore
My problem is after a put/patch request on api, I cannot see my products anymore at http://127.0.0.1:8000/api/products/ but I can still see them if i specify their id like so http://127.0.0.1:8000/api/products/1/ serializer.py class ProductSerializer(serializers.HyperlinkedModelSerializer): sku = serializers.SerializerMethodField() class Meta: model = Product fields = ['id', 'prodType', 'product_name', 'field1', 'field2', 'field3', 'sku', 'stock'] read_only_fields = ('id',) def get_sku(self, Product): fields = "" if(Product.id != ''): fields += str(Product.id).replace(" ","") + '/' if(Product.prodType != ''): fields += Product.prodType.replace(" ","") + '/' if(Product.product_name != ''): fields += Product.product_name.replace(" ","") + '/' if(Product.field1 != ''): fields += Product.field1.replace(" ","") + '/' if(Product.field2 != ''): fields += Product.field2.replace(" ","") + '/' if(Product.field3 != ''): fields += Product.field3.replace(" ","") + '/' return fields views.py class ProductViewSet(viewsets.ModelViewSet): """ API endpoint that allows product to be viewed """ queryset = Product.objects.all() serializer_class = ProductSerializer permission_classes = [permissions.AllowAny] -
"django-admin.py startproject" is not working
I am new to python and django framework. I am using python 3.7.2 and am using django version 2.1.4 When i use the command django-admin.py startproject hello it says tht file aldready exists But i had deleted the file long time back screenshot_1 when i tried to run django admin.py with a new project name(which is a project name i have not used), even though command was executed the project was not created screenshot 2 I tried using with path "C:\Users\mohit\AppData\Local\Programs\Python\Python37-32\Scripts\django-admin.py" too , but then also same above error was caused like the screenshots inserted above -
social_django returns the superuser instead of the current user when logging in
I've been trying to implement Facebook authentication using the social-auth-app-django library. Everything was working as expected --when logging in, a welcome message with the username would show up. The problem now is that when I create a superuser and login with Facebook the username of the superuser shows up instead of the current user (the one that I login in with Facebook). And when I delete the superuser and try to login again with Facebook the logging in stops. No errors appear but the signup page stays the same and nothing happens. So things go like this: 1- Logging in with Facebook for the first time works fine. "Welcome Hajar" shows up on the home page. 2- When creating a superuser with a username Admin and logging in with my Facebook account. "Welcome Admin" shows up on the home page. It doesn't show my Facebook username anymore. 3- When deleting the superuser and logging in again the application stops working. I keep clicking login with Facebook but nothing happens. Here is some of the code. # settings.py INSTALLED_APPS = [ ... 'core', 'social_django',] MIDDLEWARE = [ ... 'social_django.middleware.SocialAuthExceptionMiddleware',] AUTHENTICATION_BACKENDS = [ 'social_core.backends.facebook.FacebookOAuth2', 'django.contrib.auth.backends.ModelBackend',] LOGIN_URL = 'login' LOGIN_REDIRECT_URL = 'home' LOGOUT_URL … -
SAPB1 and django integration
im working on a new project where by i wish to be able to build a django project around an existing SAPB1 application that is in production. My goal of doing so is to be able to extract certain information from SAP database and sync them with my django database as well as write certain things into the SAP database from my django program. An example is , i would wish to generate a payment voucher from my program , and write it into the SAP data base. Is there a suitable API for such a task? I have done certain research and it seems like my client's SAPB1 does not have python RFC feature. A possible alternative would be the DI API , however most materials are written in c# which is not my expertise , therefore would love to hear your advise! thanks! -
App in docker container runs again and exits with message - fileds may not be blank
I have a django app which runs fine on local. But when I build the docker image and run the app from within the container, it runs fine and return status 200, but after some time it again returns status 400 with message, input fields are blank. Operations to perform: Apply all migrations: admin, auth, authtoken, contenttypes, sessions Running migrations: No migrations to apply. No changes detected Performing system checks... System check identified no issues (0 silenced). March 25, 2020 - 12:09:24 Django version 1.11.23, using settings 'TestSop.settings' Starting development server at http://0.0.0.0:8016/ Quit the server with CONTROL-C. [25/Mar/2020 12:09:35] "GET /TestSopApiView/ HTTP/1.1" 405 12315 [25/Mar/2020 12:09:41] "GET /TestSopApiView/ HTTP/1.1" 405 12315 [25/Mar/2020 12:10:03] "POST /TestSopApiView/ HTTP/1.1" 200 205 [25/Mar/2020 12:11:23] "POST /TestSopApiView/ HTTP/1.1" 400 189 {"field1":["This field may not be blank."],"field2":["This field may not be blank."],"field3":["This field may not be blank."],"field4":["This field may not be blank."]} This is my Dockerfile- FROM python:3.7 #Create Directory in Container ADD . /TestSop WORKDIR /TestSop COPY entrypoint.sh entrypoint.sh RUN pip install -r requirements.txt EXPOSE 8016 RUN apt-get -y update && apt-get -y upgrade && apt-get install -y curl && apt-get install -y jq RUN chmod +x /TestSop/entrypoint.sh RUN touch /TestSop/TestSop.log RUN chmod 777 … -
How to test functions that request data from external endpoints in django
I am trying to test my functions on my django api that perform external requests to external api. How can i test the following scenarios: success, failed, and exceptions like timeout The following is a simplified functionality def get_quote(*args): # log request try: response = requests.post(url, json=data) # parse this response except: # log file :) finally: # log_response(...) return parsed_response or None None: response can be success, failed, can timeout. I want to test those kind of scenarios -
Is there a way to trace only specific function?
I'm currently using patch_all with django web framework and it works fine. However, I would only like to log specific endpoints/traces based on some conditions. Is this possible? Or would I need to implement manual instrumentation across all my different endpoints for this? -
How do I populate db with Many-to-Many (with "through") Relationship?
I am new to Django and I am completely confused about how to add data to a db with a many-to-many relationship. What I'm working on is a small flashcard app that allows users to learn a list of words (language learning). But I'm not sure how I should add words for a particular Student Course combo. models.py class Language(Model): name = CharField(max_length=60) class Course(Model): name = CharField(max_length=60) description = TextField() language = ForeignKey(Language, on_delete=SET_NULL, null=True) class Word(Model): word = CharField(max_length=60) freq_rank = IntegerField() language = ForeignKey(Language, on_delete=PROTECT) class StudentCourse(Model): course = ForeignKey(Course, on_delete=CASCADE) student = ForeignKey(User, on_delete=CASCADE) words = ManyToManyField(Word, through='courses.WordProgress') class WordProgress(Model): student_course = ForeignKey(StudentCourse, on_delete=CASCADE) word = ForeignKey(Word, on_delete=CASCADE) last_review = DateTimeField(auto_now_add=True) next_review_sec = IntegerField(default=60) I have added data to Language, Course, Word, and User. But where I get stuck is how I can initialize a course with a set of words. How is ManyToManyField populated? I've seen some suggestions that it should be an array? In my case, should it be an array of words? i.e. {course: 1, user: 1, words: [1, 2, 3]} Or is this populated in some other way? Also, does through have an impact on any of this? Thanks for your help … -
Django - Do I need to check for IntegrityErrors when validating a ModelForm?
I"ve got a simple question: Do I need to listen for IntegrityErrors when I am already checking a submitted ModelForm's integrity with is_valid? My code looks like this at the moment and I am thinking about removing the try catch: def edit_object(request, object_id): o = get_object_or_404(ObjectModel, pk=object_id) if request.method == 'POST': form = ObjectForm(request.POST, instance=o) try: if form.is_valid(): form.save() return HttpResponseRedirect(reverse('namespace:startpage') else: return render(request, 'namespace/editpage.html', {'form': form,}) except IntegrityError: return render(request, 'namespace/editpage.html', {'form': form,}) return render(request, 'namespace/editpage.html', {'form': ObjectForm(instance=o),}) Since I never even save my object if the data is not valid, I should never be able to produce an IntegrityError-exception, right? Thanks in advance. -
Want to Set the footer in pdf on every page using pdfkit with python
I am using pdfkit with python to convert my html page to pdf with dynamic data, everything is working fine but i want to set the footer on every page if the length of the page exceeds the length of A4 size page, my content is dynamic so i cant hard code the length it will always change on runtime, so my concern is if the length of page exceeds than A4 length thne it places footer on both pages and same for more greater number of pages. Here is my code Where 'test' is my dictionary contains data to set in template html = render(request, 'pdf_template.html', {"test": test}) filename = test['product_name'] try: pdfkit.from_string(html.content.decode('utf-8'), filename, options=options) return render(request, 'pdf_template.html', {"test": test}) except Exception as e: return Response({"Status": False, "Message": e.__str__()}) These are my options options = { 'encoding': "UTF-8", 'margin-left': '0.50in', 'margin-top': '0.50in', 'margin-bottom': '0.50in', 'margin-right': '0.50in', 'orientation':'portrait', 'page-size':'A4' } -
Django: Add record to the database table if it is not present already
I am learning Django Rest Framework. I have been working on a small project where I am working on 4 models(database tables). The models are 1. Game 2. GameCategory 3. Player 4. PlayerScore. The table Game is having 5 columns in which category is the foreign key which links the tables Game and GameCategory. Below is the JSON payload for the API. "url": "http://127.0.0.1:8000/games/3/", "category": "Shooting", "name": "PUB G", "release_date": "2016-11-29", "played": true The table GameCategory has one column name. My current code is in such a way that if I am inserting a record into the table Game with a category which is not present in the table GameCategory I will get the following error message. "category": [ "Object with name=ABC does not exist." ] But I want it to be in a way that, when Game data is provided with the value for a category which does not exist in the GameCategory then that category should automatically be added to the GameCategory table, Sorry if it is a too basic question. I searched everywhere couldn't find the answer and also I am for this framework also to the web development. Thanks in advance.!