Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
background-image is not rendering on my local website
i have been struggling with rendering my background image on my local website. I was searching the forum and did everyhing I could but still issues. Would you please take a look? <link rel="stylesheet" type="text/css" href="{% static 'books/theme.css' %}" > <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> </head> <body> <nav class="navbar navbar-inverse"> <div class="container-fluid"> <a class="navbar-brand" href="{% url 'books:index' %}">The Bookstore</a> <div class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li class=""> <a href="{% url 'books:index' %}"> <span class="glyphicon glyphicon-book" aria-hidden="true"></span>&nbsp; Books </a> </li> </ul> </div> </div> </nav> </body> and CSS: body{ background-image: url("https://cdn.pixabay.com/photo/2016/04/15/04/02/water-1330252_1280.jpg"); } Thanks a lot for you help! -
How to apply python sytax highlighter to a django model TextField
I want to apply a sytax highlighter to a django TextField but unable to do so. Please suggest. I have tried using AceWidget to textfield but it end up with below error: TypeError: __init__() got an unexpected keyword argument 'widget' class CodeHiglighter(models.Model) name = models.CharField(max_length=50) h_code = models.TextField(widget=AceWidget) I need to apply python syntax highlighter to TextField -
How to output the port after the IP address in a resource URL in Django?
How do I add the host port to the URLs in my serialized responses? Django is currently providing them without port so the links are broken. Or, if adding the port is not the correct approach, how do I change my configuration such that I don't need to specify port in the URL while accessing the resource? Output (missing port ":1337" in image_url field) { "count": 1, "next": null, "previous": null, "results": [ { "id": 1, "user": 1, "title": "Post 1", "slug": "post1", "image_url": "http://0.0.0.0/mediafiles/publisher/sample-image4.jpg", "content": "First", "draft": false, "publish": "2019-04-26", "updated": "2019-04-26T22:28:35.034742Z", "timestamp": "2019-04-26T22:28:35.034795Z" } ] } "image_url" field will not link correctly unless it includes the port like this: "image_url": "http://0.0.0.0/mediafiles/publisher/sample-image4.jpg", More details Stack: Ubuntu Docker (compose) Nginx Gunicorn 19.9.0 Django 2.1.7 Django REST Framework 3.9.2 Python 3+ Postgres/psycopg2 I am using Django REST framework to return a list of serialized objects. The objects contain a FileField called "image" and I can output the URL of this image. The only thing is when I click that link in the output in my browser, I cannot access the resource without manually adding the server port in the address like http://0.0.0.0:1337/mediafiles/publisher/sample-image4.jpg I'm not sure if it's an nginx issue, a … -
How can I prevent duplicate db queries when using Django's inclusion tag?
So imagine if I have widget that I registered as an inclusion tag like this: @register.inclusion_tag('tags/widget.html', takes_context=True) def widget(context): return {'qs': Foo.objects.all(), 'request': context['request'],} In the widget template I loop over some entries in the Foo object. I include the widget in my Mega Menu and my Footer. These templates are obviously split up. And included in base.html However right now when I load the main page I hit the database twice for the same widget (Menu and Footer) so I get a duplicate query. How can I prevent something like this? I like the idea of the inclusion tag but I don't want duplicate queries. -
Is there a way to avoid django to upload same name file again by altering its name
I'm trying to develop a simple model form by Django to upload pdf files. The form is based on a model. Every time, user upload a file a database table entry would be created with the file path (including filename), uploaded user name and time Etc. when I upload the same file again, Django is uploading the same file by altering its name (poster-proposal.pdf ->poster-proposal_IomFZQM.pdf). It is also creating another entry in the database table. I want Django to give the user a warning when he is trying to upload an already existing file saying (a file with the same name is already existing) or something like that and not to upload the duplicate file. I followed this post,post 1 but it says it does not prevent Django from uploading the file. I followed this method post 2, but I'm new to Django and it seems complicated. I believe for newer Django versions there should be an easier way to address this issue. I added unique = True to FileField.It did not work models.py class files(models.Model): repo_id = models.ForeignKey(Repository, on_delete = models.CASCADE) username = models.CharField(db_column='username',max_length = 45) date = models.DateTimeField(auto_now_add=True, db_column = 'date') file = models.FileField(upload_to='documents/', db_column = 'file', unique … -
how to fetch data from many to many field objects?
I am getting stuck in many to many field objects in my model i want to retrieve the price of product from the order model objects but while fetching it gives sometime many related manager error or query set error models.py from django.db import models from django.contrib import admin from django.contrib.auth.models import User class Product(models.Model): name = models.CharField(max_length=100, db_index=True) slug = models.SlugField(max_length=100, db_index=True) description = models.TextField(blank=True) price = models.DecimalField(max_digits=10, decimal_places=2) available = models.BooleanField(default=True) stock = models.PositiveIntegerField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Order(models.Model): user = models.ForeignKey(User,on_delete= models.SET_NULL,null = True) product = models.ManyToManyField('Order.Product') is_ordered = models.BooleanField(default =False) date_ordered = models.DateTimeField(auto_now = True,null = True) views.py def get_product_price(request): if request.method=="GET": user=User.objects.get(username = "hemant") orders = user.order_set.all() order = orders[0] price = order.product.price return HttpResponse(price) -
How to convert base64 string to png image with django
I am working on a django application where the user can trigger the webcam and snap a photo using webrtc. This image is stored in a canvas. I wanted to save this image in the django server for further processing. this is my code so far html template <center> <button type="button" name="button" class='btn btn-outline-dark btn-lg' id='start'>Start Video Capture</button> <div class="container-fluid mt-2"> <video id="video" width="640" height="480" autoplay></video><br> <button type="button" data-toggle="modal" data-target="#image_model" class="btn btn-lg btn-dark" id="snap">Snap Photo</button> </div> </center> <center> <canvas id="canvas" width="640" height="480"></canvas> </center> <button type="button" class="btn btn-secondary" data-dismiss="modal">Retake</button> <form class="image_to_server" action="{% url 'img_submit' %}" method="post"> {% csrf_token %} <input type="text" name="base64Field" value="" id='base64'> <input type="submit" value="Use Image" class="btn btn-primary" id="use_image"> </form> js code // Grab elements, create settings, etc. var video = document.getElementById('video'); // Elements for taking the snapshot var canvas = document.getElementById('canvas'); var context = canvas.getContext('2d'); $('#start').click(function() { // Get access to the camera! if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) { navigator.mediaDevices.getUserMedia({ video: true }).then(function(stream) { //video.src = window.URL.createObjectURL(stream); video.srcObject = stream; video.play(); }); } $('#snap').fadeIn(); // Trigger photo take $('#snap').click(function() { context.drawImage(video, 0, 0, 640, 480); var dataURL = canvas.toDataURL(); $('#base64').val(dataURL) $("#use_image").click(function() { console.log('clicked'); }); }); }); django views.py def img_submit(request): if request.method == 'POST': data = request.POST.get('base64Field') format, imgstr … -
Is there some way to extend the created model fields another model in django?
Say, I want to create two models, out of which for the all the fields for the second model will remain same as the first model, with addition of a few more fields. Is there a good way to achieve this? One way is to use abstract class as the first model, but this will mean i wont be able to add instances of the first model. You can find examples in the code below: Say we have two models as: class Model1(models.Model): m1field1 = models.CharField(max_length=255,required=True) m1field2 = models.CharField(...) m1field3 = models.CharField(...) ... m1field8 = models.CharField(...) class Model2(models.Model): m1field1 = models.CharField(max_length=255,required=True) ... m1field8 = models.CharField(...) m2field1 = models.CharField(...) ... m2field5 = models.CharField(...) As you can see I have to redefine the m1field1 - m1field8 again in the Model2, if I have to reuse it. Is there some way, to not repeat it again. I tried the following: class Model2(Model1): m2field1 = models.CharField(...) ... m2field5 = models.CharField(...) But, this didnt work as in the hindsight, it creates a OneToOneField of Model2 to Model1, which obviously wont work, as I will have to first create a Model1 with the given fields and then Model2 with the fields and then link it to … -
How to stop an endless loop on model migration, 'models have changes that are not yet reflected' - makemigrations > migrate. Same message
Showmigrations: accounts [X] 0001_initial admin [X] 0001_initial [X] 0002_logentry_remove_auto_add [X] 0003_logentry_add_action_flag_choices auth [X] 0001_initial [X] 0002_auto_20190430_1129 blog [X] 0001_initial contenttypes [X] 0001_initial [X] 0002_remove_content_type_name core (no migrations) curate [X] 0001_initial [X] 0002_item_tags django_comments [X] 0001_initial podcast [X] 0001_initial [X] 0002_auto_20190430_1129 [X] 0003_auto_20190430_1132 sessions [X] 0001_initial sites [X] 0001_initial [X] 0002_alter_domain_unique taggit [X] 0001_initial If I run migrate (just to see if it says 'no migrations to apply') I get this: Operations to perform: Apply all migrations: accounts, admin, auth, blog, contenttypes, curate, django_comments , podcast, sessions, sites, taggit Running migrations: No migrations to apply. Your models have changes that are not yet reflected in a migration, and so won't be appl ied. Run 'manage.py makemigrations' to make new migrations, and then re-run 'manage.py migrat e' to apply them. So I run makemigrations: Migrations for 'podcast': podcast\migrations\0004_auto_20190430_1137.py - Alter field published_date on show Showmigrations: accounts [X] 0001_initial admin [X] 0001_initial [X] 0002_logentry_remove_auto_add [X] 0003_logentry_add_action_flag_choices auth [X] 0001_initial [X] 0002_auto_20190430_1129 blog [X] 0001_initial contenttypes [X] 0001_initial [X] 0002_remove_content_type_name core (no migrations) curate [X] 0001_initial [X] 0002_item_tags django_comments [X] 0001_initial podcast [X] 0001_initial [X] 0002_auto_20190430_1129 [X] 0003_auto_20190430_1132 [ ] 0004_auto_20190430_1137 sessions [X] 0001_initial sites [X] 0001_initial [X] 0002_alter_domain_unique taggit [X] 0001_initial I run … -
How do I incorporate SCA data into the Paypal DoDirectPayment API call for PDS2
Paypal are hounding me to change my current payment gateway that uses their API, and hand it over to a third party (that presumably will charge for the service) because of the PDS2 (Payment Service Directive - revised) which demands Strong Customer Authentication (SCA) unless a transaction is exempt. The extra info can be a password, fingerprint or phone, but details on how to use their API for this are missing. Paypal's documentation is close to useless, but Stripe's documentation have information as to what constitutes an exempt transaction, and in fact that the PDS2 only applies if the business AND the customer's bank is in the European Economic Area (ref: https://stripe.com/en-nl/guides/strong-customer-authentication) and that the bank deems the transaction as risky. The definition of a risky transaction is subjective and decided by the banks, so the implication is that we MUST enable SCA. I use django-paypal which provides helper functions and data structures for using paypal's API. Paypal are not too good at supporting developers, and communication with their technical staff is impossible. So I emailed the developer of django-paypal, but I have not received a response (https://github.com/appsumo/django-paypal-1). The deadline for this is September 2019, after which paypal warn of … -
Starting function after applying migrations
I have a function, that set users online to 0 on starting server (users online is int. Increment on connecting to websocket and decrementing on disconnect). def ready(self): from . import signals from .models import UserAccount UserAccount.objects.filter(online__gt=0).update(online=0) That starts on app ready, but I've got some troubles: when my remote mirror downloaded sources from repo, this function has been worked before migrations was applied, and column online doesn't exists this time, and server goes to perpetual reboot. I may have other functions, that should be run before after accepting migrations. How to run this code after migrations will be applied? -
Django) How to connect urls-views-models in ManyToMany, OneToMany relationship
I made some models which have ManyToMany, OneToMany relationships, and then I tried to make appropriate class in views.py, so that one can see sub models related to the chosen model. But in terms of connecting models-serializers-views-urls, I just couldn't figure out how to make it work... So, what I want to do is : (simplified) There are 3 models. Party People Food So Party has ManyToMany relationship with People, and OneToMany relationship with Food. When I reached url like /party_id/people_id, then I want to get specific person's information from given party id. Here goes my code. models.py class Party(models.Model): par_id = models.TextField() par_people = models.ManyToManyField(People) class People(models.Model): peo_id = models.TextField() peo_name = models.TextField() peo_type = models.TextField() class Food(models.Model): foo_id = models.TextField() foo_party = models.ForeignKey(Party, on_delete=models.CASCADE) serializers.py class PartySerializer(serializers.ModelSerializer): class Meta: model = Party fields = ('par_id', 'par_people') # People, Food has same structure... views.py class PartyList(generics.ListAPIView): queryset = Party.objects.all() serializer_class = PartySerializer # People, Food has same structure... urls.py Here's the part where I got lost #redundancy reduced...(e.g. import) urlpatterns = [ path('party/<int:par_id>/<int:peo_id>', views.PartyList.as_view()), path('party/<int:par_id>/<int:foo_id>', views.PartyList.as_view()), ] So If I reach website/party/par_id/peo_id, I want to see specific person's information of specific party. For food, It goes the same. Should … -
error in deploying on heroku in django app in postgresql
I am deploying my django project with SQLLite database on heroku,Heroku uses it's own data base postgresql. I am using autotask for my project but while deploying my project i am getting this error "relation "autotask_taskqueue" does not exist" he above exception was the direct cause of the following exception: Traceback (most recent call last): File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1097, in execute_sql cursor.execute(sql, params) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py", line 99, in execute return super().execute(sql, params) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py", line 67, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py", line 76, in _execute_with_wrappers return executor(sql, params, many, context) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/utils.py", line 89, in exit raise dj_exc_value.with_traceback(traceback) from exc_value File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) django.db.utils.ProgrammingError: relation "autotask_taskqueue" does not exist LINE 1: SELECT COUNT(*) AS "__count" FROM "autotask_taskqueue" WHERE... -
How to access Button onClick event in Python Django [duplicate]
This question already has an answer here: How do I call a Django function on button click? 2 answers I am new to Django. I am trying to access button onClick event in djano. I am struggling to write views for that. -
is there any way to import python output to php file
I'm working on a project in python and want my output of the .py file to be parsed to a php file as a variable.My program is about Automatic License Plate Recognition and i want to store output to database and short them by state vise. -
How to fix UnboundLocalError in Django views
I have been really struggling with this code for a while and I can't seem to see what is wrong with it. I have been trying to implement 2 model forms in one view here. So the ShoesForm only shows when the user wants to create or edit a shoe product. (I hide the form using javascript). The fields in the model Shoes is all blank=True so the field.cleaned_data is always confirmed. However, whenever I try to edit an existing non-shoe item, I got an error that says UnboundLocalError: local variable 'pid' referenced before assignment. I know this means that there is a case where pid is not assigned but I can't see it. Any suggestions? views.py def create_or_update_inventory(request, product_id=None): """Combined form view for BaseInventory and Shoes model The two available forms in the context are: 1. product_form: linked to BaseInventory model 2. shoes_form: linked to Shoes model If the form is submitted, it will first create the product for the BaseInventory model. If any of the forms inside the shoes_form is filled, it will take the product and link it to the inventory field in the Shoes model and then it will save the shoes_form. This vies uses the … -
Django Rest Framework - Displaying the User's Profile
My models.py file looks as below. class User(AbstractUser): is_customer = models.BooleanField(default=False) is_courier = models.BooleanField(default=False) is_merchant = models.BooleanField(default=False) class Profile(models.Model): contact_number = models.CharField(max_length=10, unique=True) rating = models.IntegerField(blank=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) My current serializers.py looks like below. class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = '__all__' My api.py looks like below. class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() permission_classes = [ permissions.AllowAny ] serializer_class = UserSerializer My urls.py has the below: router.register('api/users', UserViewSet, 'users') My current setup works well with the UserViewSet. http://127.0.0.1:8000/api/users/ displays all the users and http://127.0.0.1:8000/api/users/1/ displays the user according to the ID. My question is, How can I load up the user profile when I goto the below the URL http://127.0.0.1:8000/api/users/1/profile Any help is much appreciated. Thank you in advance. -
Create Dynamic URL in Django
I have a Django form that asks the user for a "URL" and content. I wish to create a page dynamically with the URL provided by the user in the "URL" field and show the content mentioned in the "Content" field. -
When I tried to run my python program, I encountered this Django import error
When I tried running a python program on my local machine, I encountered this error: Performing system checks... System check identified no issues (0 silenced). You have 2 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): auth. Run 'python manage.py migrate' to apply them. April 29, 2019 - 19:29:41 Django version 2.2, using settings 'mysite.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. Exception in thread Thread-1: Traceback (most recent call last): File "C:\Users\Thomas\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\servers\basehttp.py", line 45, in get_internal_wsgi_application return import_string(app_path) File "C:\Users\Thomas\AppData\Local\Programs\Python\Python37\lib\site-packages\django\utils\module_loading.py", line 17, in import_string module = import_module(module_path) File "C:\Users\Thomas\AppData\Local\Programs\Python\Python37\lib\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 "C:\Users\Thomas\Desktop\Intern\Diversity_Policy_Site\mysite\wsgi.py", line 12, in <module> from whitenoise.django import DjangoWhiteNoise File "C:\Users\Thomas\AppData\Local\Programs\Python\Python37\lib\site-packages\whitenoise\django.py", line 2, in <module> '\n\n' ImportError: Your WhiteNoise configuration is incompatible with WhiteNoise v4.0 This can be fixed by following the upgrade instructions at: http://whitenoise.evans.io/en/stable/changelog.html#v4-0 The above exception was the direct cause of the following exception: Traceback (most … -
How to remove trailing Slash in django URL?
How do you remove the ending slash in Django URLs so you can make href links to jump on sections of a webpage. If you have a href="#section1" And a url www.domain1.com/index, django makes it www.domain1.com/index/ so you get www.domain1.com/index/#secton1 when it should be www.domain1.com/index#section1. Anybody knows? -
Populate database table with import script - django
I'm new to Django and I'm not seeing any 'straightforward' way to do what I want. I have a fresh django app and I've created the initial migration of my database. It has one table. All seems good and I created a python script to import the data. I immediately get the below error after running it: django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. Model from django.db import models class Person(models.Model): playerID = models.TextField() birthYear = models.IntegerField() birthMonth = models.IntegerField() birthDay = models.IntegerField() birthCountry = models.TextField() birthState = models.TextField() birthCity = models.TextField() deathYear = models.IntegerField() deathMonth = models.IntegerField() deathDay = models.IntegerField() deathCountry = models.TextField() deathState = models.TextField() deathCity = models.TextField() nameFirst = models.TextField() nameLast = models.TextField() nameGiven = models.TextField() weight = models.IntegerField() height = models.IntegerField() bats = models.TextField() throws = models.TextField() debut = models.DateField() finalGame = models.DateField() retroID = models.TextField() bbrefID = models.TextField() Import Script import pandas as pd from api.models import Person people_csv = pd.read_csv('data/People.csv') people_objects = [] for p in people_csv.iterrows(): person = Person() person.playerID = p.playerID person.birthYear = p.birthYear person.birthMonth = p.birthMonth person.birthDay = p.birthDay person.birthCountry = p.birthCountry person.birthState = p.birthState … -
How to generate a random number for a model field using Factory Boy
I need to create some fake data using factory boy. I have the following model: class Fabric(models.Model): title = models.CharField(max_length=200, blank=True) description = models.CharField(max_length=200, blank=True) price = models.DecimalField(decimal_places=2, max_digits=10, null=True, blank=False) I need to create a factory based on this model, and I would like the price to have a random value between 1 and 100. class FabricFactory(DjangoModelFactory): class Meta: model = Fabric title = factory.Faker('name') description = factory.Faker('catch_phrase') price = random.randrange(MIN_PRICE, MAX_PRICE + 1) The problem with this is that I am always getting the same price for every instance. -
How can i use django's runscript?
I am trying to run a script using django's runscript. I followed everything in the documentation. Did i miss something? But when i tried running it from the command line. it says unknown command 'runscript' (env) C:\Users\MIS\hr system\hr_project>python manage.py runscript automail.py Unknown command: 'runscript' -
Images appear as broken links - summernote
I'm using django-summernote within my website. Within my local environment, I'm able to save images within the summernote widget and view these images successfully within my blog. On my production and live website, my static files are being served by AWS. All images that were saved to a summernote widget and are supposed to be displayed are appearing as broken links. I get the following error: This XML file does not appear to have any style information associated with it. The document tree is shown below. <Error> <Code>AccessDenied</Code> <Message>Request has expired</Message> <X-Amz-Expires>3600</X-Amz-Expires> <Expires>2019-04-29T07:58:01Z</Expires> <ServerTime>2019-04-30T01:14:17Z</ServerTime> <RequestId>CC3C79EBC6B9ED8E</RequestId> <HostId> ONtTmlKKYQ4lqY2yJR2A0GibkJgxThBoCMntMoZf2g6XCr2hVS5sPnPD9Fr2acR/nW/UeyQ0dOk= </HostId> </Error> Any thoughts on what might be the cause of this? Thanks! -
Send email via SES
Do I need an actual mailbox and verified email to send email with SES? I own the domain I am trying to send from, but I do not have an account or mailbox setup (this is just a test domain, and I don't want to setup a gmail mailbox) Is there a better way to be doing this in a test environment? I am using the django-ses package, and sending email like this: send_mail('Test subject', 'This is the body', 'mypersonalemail@yahoo.com',['info@mydomain.com']) I very well may have a fundamental misunderstanding of sending email, so any help is appreciated!