Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django..db.utils.operationserror on port 5432
I am getting that error, along with message TCP/IP connections on port 5432. I HAVE installed psycopg2 2.8.4m, running Django 3.0 and python 3.6 I get that error, when I run my application firs ttimne.I am still unable to run my app first time. Is it because database not created yet? and I tried solutions posted here django.db.utils.OperationalError Could not connect to server but it did not help -
Django postbacks and browser history
Using Django, I want to perform a Form submit (postback) that returns the same page (e.g. /foo/1) without writing another entry in the browser's history for the same location. I do not want to make an API call from JavaScript to submit the data (trying to keep this app as simple as possible). This seems very basic and I feel like I'm just missing something obvious... -
Django: Letting user download PDF file from database
How can I allow users to download PDF files from database? The PDF file is stored as a longblob in the MySQL database. What I have so far: views.py: reports = Report.objects.all() However doing so throws the following expcetion: <method 'fetch_row' of '_mysql_connector.MySQL' objects> returned a result with an error set models.py: class Report(models.Model): studentid = models.IntegerField(db_column='studentId') # Field name made lowercase. studentname = models.TextField(db_column='studentName') # Field name made lowercase. year = models.CharField(max_length=4) term = models.CharField(max_length=6) report = models.TextField() #PDF should get stored here. What can I do to allow user to see the files to download? I've been looking for ways to solve this problem however can't quite seem to figure it out. Any help is appreciated! Thank you -
Starting an old Django 1.2 project from localhost
Hello i am having a problem where i cannot run an old Django project in local host. I cannot link to the django project because it is private. My few questions are: - what file do i run? my guess is the 'main.py' - should i be looking for a particular key work in a file - in side of the root there is a folder called 'Lib, how do i make use of it - i keep getting errors that a module cannot be loaded but that module is inside the 'Lib' folder - the project is deployed to google cloud and runs perfectly fine there -
Embed an image in Email content - Django
I am using Django's Email message module to trigger an email with an embedded image. Currently i have that image in my static folder.I tried using the html code directly in python to trigger the email. But the image is not getting embedded in the triggered email. I have tried by specifyjng the image source attribute as static path as well as a url. Could someone help? Below is the code that I have used. Code : recipient_list = ['a...@gmail.com'] from_email = 'a...@gmail.com' message = '' path = "{% static 'images/Welcome_image.jpg' %}" //Using this image in the below html also tried specifying the source as an url that points to the url path. Like https://abc/images/Welcome_imagr.jpg message += "<table border='1' cellpadding='1' cellspacing='0' width='800'>\ <tbody>\ <tr>\ <td height='506'>\ <table border='0' cellpadding='0' cellspacing='0' width='600'>\ <tbody>\ <tr>\ <td valign='top'>\ <img height='190' src=%s width='800' tabindex='0'>\ //Using this image here but it is not rendered properly. </td>\ </tr>\ <tr>\ <td height='306' valign='top'>\ <table cellpadding='0' cellspacing='20' width='800'>\ <tbody>\ <tr>\ <td align='left' height='804' style='font-family:arial,helvetica,sans-serif;font-size:13px' valign='top'>Hi User,<br><br>\ Welcome to the world.\ </td>\ </tr>\ </tbody>\ </table>\ </td>\ </tr>\ </tbody>\ </table>\ </td>\ </tr>\ </tbody>\ </table>"%(path) subject = "Welcome to the place!" try: msg = EmailMessage(subject, message, from_email, recipient_list) msg.content_subtype = "html" … -
Django rest framework how to create 3 nested-serializer objects?
I'm trying to create nested objects in Django Rest Framework according to the docs. this my models.py : from django.db import models class Request(models.Model): origin = models.CharField(max_length=255, blank=True) def __str__(self): return str(self.id) class RequestOrders(models.Model): request_id = models.ForeignKey(LoadingRequest, related_name='loading_request_orders', on_delete=models.DO_NOTHING, blank=True, null=True) position = models.CharField(max_length=255, blank=True) destination = models.CharField(max_length=255, blank=True) order_ref = models.CharField(max_length=255, blank=True) def __str__(self): return self.id class RequestOrderItemss(models.Model): request_order_id = models.ForeignKey(LoadingRequestOrders, related_name='loading_request_order_itemss', on_delete=models.DO_NOTHING, blank=True, null=True) product_id = models.ForeignKey('product.Product', on_delete=models.DO_NOTHING, blank=True, null=True) qty = models.CharField(max_length=255, blank=True) def __str__(self): return self.id Here's my serializers.py : from rest_framework import serializers from loading_request.models import Request, RequestOrders, RequestOrderItemss class RequestOrderItemssSerializer(serializers.ModelSerializer): class Meta: model = RequestOrderItemss fields = ('id', 'request_order_id', 'product_id', 'qty') class RequestOrdersSerializer(serializers.ModelSerializer): request_order_itemss = RequestOrderItemssSerializer(many=True) class Meta: model = RequestOrders fields = ('id', 'request_id', 'position', 'destination', 'order_ref', 'request_order_itemss') def create(self, validated_data): request_order_items_data = validated_data.pop('request_order_itemss') request_order = RequestOrders.objects.create(**validated_data) for request_order_item_data in request_order_items_data: RequestOrders.objects.create(request_order_id=request_order, **request_order_item_data) return request_order def update(self, instance, validated_data): request_order_items_data = validated_data.pop('request_order_itemss') items = (instance.request_order_itemss).all() items = list(items) instance.origin = validated_data.get('origin', instance.origin) instance.save() for request_order_item_data in request_order_items_data: item = items.pop(0) item.product_id = request_order_item_data.get('product_id', item.product_id) item.qty = request_order_item_data.get('qty', item.qty) item.save() return instance class RequestSerializer(serializers.ModelSerializer): request_orders = RequestOrdersSerializer(many=True) class Meta: model = Request fields = ('id', 'origin', 'request_orders') def create(self, validated_data): request_orders_data = validated_data.pop('request_orders') request … -
Loading css file in django allauth login page
I can't seem to be able to change the css of my allauth login page. I would like to add some custom css to change a few things. I created a base.css file div_id_login.form-group{ font-weight:200; } That is loaded in my login.html file {% extends "account/base.html" %} {% load i18n %} {% load account socialaccount %} {% load crispy_forms_tags %} {% load static %} {% block head_title %}{% trans "Sign In" %}{% endblock %} <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <head> <link rel="stylesheet" href="{% static 'css/base.css' %}"> </head> {% block content %} <h1 style = "text-align: center;">{% trans "Sign In" %}</h1> ... The div class mentioned in the base.css file should be this: -
How can I prevent Django from "forgetting" information whenever I make a Git commit?
I am working on a blog project in Django that I currently have a version running in production. I have been making changes to the Development version and as I push through the changes on Git I notice that every commit "clears" information I had stored in the production server. To be specific, a) certain blog posts that were written on the production server and b) user 'accounts' added on the production server seem to "disappear" whenever I push through new commits. I was told that this problem is potentially due to my usage of sqlite (I use sqlite3) and my local dev database getting "mixed in" with my repository. If this is the case, how can I fix this problem. If you suspect this is due to a different issue, what may be the cause? I am new to using both Django and Git though I have used Python for some time. I really appreciate any and all help. For ease of use, part of my "Articles" model is below - the articles represent blog posts. class Article(models.Model): title = models.CharField(max_length=255) #Body is the "body" of our entry - self explanatory. body = models.TextField() #date = models.DateTimeField(auto_now_add=True) author = … -
Passing dynamic "choices" into a formset unique for each form
I am working on what I thought was a simple college football confidence pool. The concept is as follows: Bowl Model: Model that stores information of each bowl game being played this season Team Model: Model for all the teams playing in a bowl with a foreign key to the bowl models.py from django.db import models from django.contrib.auth.models import Group, User class Bowl(models.Model): """Model for Bowl Game information""" name = models.CharField(max_length=200) b_date = models.DateField(null=True, blank=True) b_time = models.TimeField(null=True, blank=True) tv = models.CharField(max_length=10) location = models.CharField(max_length=200) def __str__(self): """String for representing the bowl object""" return self.name class Team(models.Model): name = models.CharField(max_length=200) bowl = models.ForeignKey(Bowl,on_delete=models.SET_NULL,null=True) def __str__(self): """String for representing the intermediate table""" return self.name I'm attempting to create a page has a formset which allows the user to pick the predicted winner of each game. Therefore I constructed the following view to call the form and formset. views.py def fs_test(request): bowl_list = Bowl.objects.all() bowl_len = len(bowl_list) bowl_data = [] TestFormSet = formset_factory(TestForm, extra=0) for bowl in bowl_list: bowl_data.append({ 't_bowl': bowl.name,'t_user':request.user,'t_weight':1, 't_winner':winner_data, }) if request.method == 'POST': pass else: formset = TestFormSet(initial=bowl_data) context = { 'formset':formset, 'bowl_data':bowl_data } return render(request, 'catalog/test_bowl.html',context) The following form inherits pre-populated data via passing "bowl_data" in the … -
Django.db.backends.postgresq_psycopg2 python 3 Django 3
I am trying to migrate an app from Django 1.8 and python 2, into python 3.6 and Django 3.0 version. Whenever I am adding Django.db.backends.postgresq_psycopg2 , and installing it via pip3 I am getting error _psycopg2 module not found. I look up at documentation, and see that in Django 3.0 _psycopg2 is removed. How to solve this issue? My previous app is running psycopg 2.6.1 -
Routing from Django to main Angular route
I have a Django APP. With button click on django template page I need to re-direct app to angular main page (app.component.html). How can i do it? -
Java Script Auto Populate Name in Drop down Field
Im trying to auto populate a students name in my drop down menu of students. Here is my code. I got it working for my classroom name but not students name. Here is also a screenshot of the html of the drop down menu. const student_name = "{{student_name}}"; var studentnamedropdown = document.getElementById('id_student_name'); for (i = 0; i < studentnamedropdown.options.length; i++) { // if(studentnamedropdown.options[i].text == "Bob Smith") if(studentnamedropdown.options[i].text == student_name) { console.log(studentnamedropdown.options[i].text) $("#id_student_name").val(studentnamedropdown.options[i].value) } } -
Django Adding Pagination To Search Form Page
How do I add pagination to this form's search functionality? By default on page refresh, the HTML template for loop shows all the results for all the courses. When the user types in criteria into the form, the form filters the course results template for loop based on what the user typed. Is there a way on page refresh to show only a set limit of course results on the page instead of all of them? Then when a user searches/filters, that pagination limit of X number of course results on a page will still need to show but still applied to the search criteria / filter. Code: https://dpaste.org/ZB3v I tried following some tutorials like the django docs one but not sure how to embed that pagination code to mine. https://docs.djangoproject.com/en/3.0/topics/pagination/ I would appreciate if anyone could help me with this. -
Not Found: /api/company_list/status='Pending' I want to filter by status, but i have an issue
@api_view(['GET']) def company_list(self): company_list = Company.objects.all() return Response(CompanySerializer(company_list, many=True).data) def get_queryset(self): queryset = Company.objects.all() statusa = self.request.query_params.get('status', '') if statusa: return Company.objects.filter(status=statusa) return queryset That is my Url : http://localhost:8000/api/company_list/status='Pending' -
Accessing user data in a Django form class
I have a form for which I'd like to use user data to filter the content of a choicefield. Following this solution, I added all references to user in the __init__ function of my Form class: class MyChoiceField(forms.Form): def __init__(self, *args, **kwargs): self.user = kwargs.pop('user') super(MyChoiceField, self).__init__(*args, **kwargs) user_id = self.user.id myobjects = forms.ModelChoiceField(label='',queryset = Myobject.objects.values_list('name', flat=True).exclude(name__isnull=True).filter(Q(person__isnull=True) | Q(person=user_id)).distinct(),empty_label=None) And in the view I call it as: def urbioapp_bootstrap(request): my_list = MyChoiceField(user = request.user) context = { 'my_list': my_list, } return render(request, 'foo/bar.html', context) Debugging the __init__ part indicates the queryset content is correct, but in the view, my_list contains the following:<MyChoiceField bound=False, valid=Unknown, fields=()>. Should I include something in the form class, outside of the __init__ part for this to work? -
How do I set up local files and production files in Django
I have created a simple web app that is now being hosted on Heroku. My secret key is set up as an environment variable so that it is not being pushed to a remote repository but when I try to push these changes to Heroku I get this error: raise KeyError(key) from None remote: KeyError: 'SECRET_KEY' I guess this is because it doesn't have access to my environment variable, so how do I set up a separate settings file for production that will hold this key? -
How to auto select an option in widget.SelectMultiple Django ModelForm
I created a ModelForm in Django which has set a widget.SelectMultiple, like this: 'groups': widgets.SelectMultiple(attrs={'placeholder': 'Rol', 'class' : 'form-control'}), That code is displaying a dropdown in my html with n available options, what I need is to set a default selected option. I don´t know if there is any attrs which helps me to do that. -
Combining querysets on two different models
I need to list objects of types Model1 and Model2 chronologically. The order fields are, correspondingly, created_at and created_datetime. In Python this would be straightforward: q1 = Model1.objects.order_by('-created_at') q2 = Model2.objects.order_by('-created_datetime') result = sorted(itertools.chain(q1, q2)) However that result is potentially large, so I need to introduce pagination. I don't want to query the whole thing, including related tables, preparing data, etc and then return the requested page. That wouldn't be efficient. I need to run the query only for the corresponding page. It would be something like this: combined_queryset[num_items*(page-1):num_items*page] Producing a SQL query with LIMIT and OFFSET. Is there any way I could do this with a custom QuerySet or a Manager? Any other ideas? -
Display on a map objects matching a queryset with Django
I have a Django app, where each user can add a product with multiple possible metrics (width, height and length combination). A user must also specify in which city this product is located. Users can also search within the database all products matching specific metrics. I use Django 1.11 and am seaching for a solution to display on an interactive map all the products matching a queryset. I am trying to do it with django-leaflet and django-geojson (as my db is not gis-oriented and I don't need heavy geo-computations), but I am facing some difficulties because my "PointField" is not in my product Model but in the Location Model and on the map I need to display Product properties, so I must serialize all these data together. If you prefer code rather than words, here is a simplified version of my relevant files. #models.py class Product(models.Model): name = models.CharField() owner = models.ForeignKey(User) photo = models.ImageField(...) dimensions = models.ManyToManyField(Metrics) location = models.ForeignKey(Location, related_name='products', related_query_name='product') class Metrics(models.Model): width = models.PositiveIntegerField() height = models.PositiveIntegerField() length = models.PositiveIntegerField() class Location(models.Model): zip_code = models.PositiveIntegerField() city_name = models.CharField() slug = models.SlugField(max_length=500, blank=True) geom = PointField(default={'type': 'Point', 'coordinates': [0, 0]}) #views.py class SearchResultListView(ListView): model = models.Product template_name='my_app/searchresult_list.html' … -
Adding product to cart - variable assignment django
I have the function of adding products to cart. However, it doesn't work as it should. The first time you add a product to cart, you always add 1 when you add the quantity of the product. After you add and add value again, everything works fine. product.html <div class="float-right"> <form action="{% url 'cart:add_cart' product.id %}" method="post"> {% csrf_token %} <div class="float-left"> <input type="number" value="1" name="quantity" class="form-control" style="width: 100px"> </div> <input class="btn send-click btn-md my-0 p" type="submit" value="Add to cart"> </form> </div> views.py def add_cart(request, product_id): product = Product.objects.get(id=product_id) try: cart = Cart.objects.get(cart_id=_cart_id(request)) except Cart.DoesNotExist: cart = Cart.objects.create( cart_id = _cart_id(request) ) cart.save() try: cart_item = CartItem.objects.get(product=product, cart=cart) if cart_item.quantity < cart_item.product.stock: if request.method == 'POST': quantity = request.POST['quantity'] cart_item.quantity += int(quantity) cart_item.save() except CartItem.DoesNotExist: cart_item = CartItem.objects.create( product = product, quantity = 1, cart = cart ) cart_item.save() return redirect('cart:cart_detail') There is error on this line quantity = 1 I have no idea what to assign instead of this 1. -
How to extract sub-image using mouse drag in Open Layers API?
I have an application similar to this example, where I have an OpenLayers Map object with an Image inside of the Map on my page, and I want to be able to extract some sub-image from this image using a mouse drag (to select some rectangular portion of the original image). This sub-image will then be processed by the page. I have done a fair amount of internet searching as to how to extract some portion of an OpenLayers Image, but have not been able to find a way to do the OpenLayers API. Is there a natural way to do this with this API? If not, is there existing software good for getting a portion of an image using the mouse? Below is essentially what my OpenLayers Object looks like currently (running on Django framework), any help is appreciated. <script type="text/javascript"> var extent = [0, 0, 3000, 4213]; var projection = new ol.proj.Projection({ code: 'image-code', units: 'pixels', extent: extent }); var map = new ol.Map({ controls: ol.control.defaults().extend([ new ol.control.FullScreen() ]), layers: [ new ol.layer.Image({ source: new ol.source.ImageStatic({ attributions: 'attribution info...', url: "{{record | img_url}}", projection: projection, imageExtent: extent }) }) ], target: 'map', view: new ol.View({ projection: projection, center: … -
GeoDjango: Inverted coordinates in drawn polygon
I need to draw a polygon using GeoDjango Admin. I can draw it but when I render it on my map I see the coordinates inverted. This polygon represent the Sicily, but is rendered on Eritrea and Ethiopia. models.py from django.contrib.auth.models import User from django.contrib.gis.db import models as geomodels from django.db import models class UserDetail(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE, related_name='user_details', ) name_surname = models.CharField( 'Nome e Cognome', max_length=50, blank=True, null=True, ) class UserTask(models.Model): owner = models.ForeignKey( UserDetail, verbose_name="User", on_delete=models.CASCADE, related_name='usertask_userdetails', ) geom = geomodels.PolygonField() admin.py from django.contrib.gis import admin from .models import UserDetail, UserTask admin.site.register(UserDetail) admin.site.register(UserTask, admin.OSMGeoAdmin) views.py from django.core.serializers import serialize from django.http import HttpResponse def usertask_geojson(request): vectors = serialize( 'geojson', UserTask.objects.all(), ) content_type = 'json' return HttpResponse(vectors, content_type) urls.py from django.urls import include, path from . import views urlpatterns = [ path('geojson/', views.usertask_geojson, name="usertask_geojson"), ] GeoJSON serialized { "type": "FeatureCollection", "crs": { "type": "name", "properties": { "name": "EPSG:4326" } }, "features": [ { "type": "Feature", "properties": { "pk": "1" }, "geometry": { "type": "Polygon", "coordinates": [ [ [ 38.34682590817893, 12.172851560804837 ], [ 38.68207914325214, 15.644531247821982 ], [ 36.620818174552944, 15.161132810389033 ], [ 36.620818174552944, 15.161132810389033 ], [ 38.34682590817893, 12.172851560804837 ] ] ] } } ] } I'm sure that I've … -
Django: session variables -> How to override logout without breaking the django authentification core
first I am newbie in Django (<3 months) I read the Djnago doc but it is hard sometime.... I use "from django.contrib.auth import views as auth_views" to authenticate so I did not write any login/logout views, only urls.py and it works well but I would like to override logout (and maybe login) views to initialise and set session variable more efficiently but do not understand how to proceed someone can explain me the easiest way to do this? -
Django Admin - formfield_for_foreignkey not working on custom User
I cannot find a way to get formfield_for_foreignkey from django.contrib.auth.admin import UserAdmin class MyUserAdmin(UserAdmin): UserAdmin.list_display = list(UserAdmin.list_display) + [ 'id', 'username', 'last_name', 'first_name', 'conflict', 'override_date_available', 'email', 'partner_leader', ] def __init__(self, *args, **kwargs): super(UserAdmin,self).__init__(*args, **kwargs) def formfield_for_foreignkey(self, db_field, request, **kwargs): print(db_field.name) if db_field.name == "partner_leader": kwargs["queryset"] = User.objects.filter(is_partner=True) return super().formfield_for_foreignkey(db_field, request, **kwargs) The admin list_display works fine but the formfield_for_foreignkey will not actually filter the field like it does on other admin classes. I'm assuming this has to do with the fact that I'm using a custom User model but cannot figure out for the life of me why this specific piece would not work while the other overrides do. Is there something additional I need to override in order for formfield_for_foreignkey to work? -
Menu problem in Divio app tutorial for base.html editing
So I was following this instruction and it was okay until this moment {% show_menu 0 100 100 100 "includes/menu.html" %} adding this line in base.html by instruction http://support.divio.com/en/articles/49026-6-configuring-content-and-navigation makes my page crash with errors is it okay if i skip this line? or there must be some changes. coz it makes everything crash with syntax error on test page https://imgur.com/PQlb3vT and without this line menu is not working in template so what I did is I added one "/" to the link and it changed error to this https://imgur.com/bhvSq97 More understandable error maybe I think it is about the menu.html file that I loaded to folder "template/includes" that i had to created manually following instruction and it makes conflict or something with another menu on the cloud repository file of how menu should be.