Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django calculate 2 values from model
Im fairly new to Django. Im using Django 2. My model: # Create your models here. class Trade(models.Model): quantity = models.IntegerField() open_price = models.FloatField() commision = models.FloatField() exchange_rate_usdsek = models.FloatField() stock = models.ForeignKey(Stock, on_delete=models.CASCADE) user = models.ForeignKey(User, related_name='trades', on_delete=models.PROTECT) open_date = models.DateTimeField(auto_now_add=True, null=True) def get_absolute_url(self): return reverse('trade:detail',kwargs={'pk': self.pk}) def __str__(self): return self.stock.name My view class IndexView(generic.ListView): template_name = 'trade/index.html' context_object_name = 'all_trades' # def get_queryset(self): return Trade.objects.all() #return Order.objects.all().prefetch_related('items') def get_context_data(self, **kwargs): context = super(IndexView, self).get_context_data(**kwargs) return context index.html <h3>All stocks</h3> <table class="table"> <thead> <tr> <th>Stock</th> <th>Amount</th> <th>Open Price</th> <th>Commision</th> <th>USD/SEK</th> <th>Total sek</th> </tr> </thead> {% for trade in all_trades %} <tr> <td>{{trade.stock.name}}</td> <td>{{trade.quantity}}</td> <td>{{trade.open_price}} USD</td> <td>{{trade.commision}} SEK</td> <td>{{trade.exchange_rate_usdsek}}</td> <td>{{open_price * quantity * exchange_rate_usdsek}}</td> </tr> {% endfor %} </table> Now on my index.html I want to calculate and display a value. I make a calculation like this: total_sek = open_price * quantity * exchange_rate_usdsek Do I have to calculate this in the views.py or in the index.html? Also how would I do this? I searched around and found something about filters but im not sure if that is the right way to do it -
Error in set ForeignKey in django models
i want to make a three table and connect them to reach other like : from __future__ import unicode_literals from django.db import models class Author(models.Model): name = models.CharField(max_length=50) class BlogPost(models.Model): title=models.CharField(max_length=250) body=models.TextField() author=models.ForeignKey(Author, on_delete=models.CASCADE) date_create = models.DateTimeField() class Comment(models.Model): blog_post=models.ForeignKey(BlogPost, on_delete=models.CASCADE) text=models.CharField(max_length=500) But when i delete a author in database(sqlite) there is an error!! Is there any way to solve that ??? -
How to overwrite route function of wagtail Page model
I am using Wagtail CMS for managing content in some of the tables in my database. Wagtail's Page model reference is done by linking one to one relation to the table in the database which is not managed by Django migration. The model structure is as follow: class MyDocument(Page): wagtail_page = models.OneToOneField('wagtailcore.Page', models.DO_NOTHING, parent_link=True, primary_key=True) route_field = models.TextField(db_column='route', verbose_name='URL Route (non-editable value)') slug_field = models.TextField(db_column='slug', verbose_name='URL Slug') language_field = models.ForeignKey('Languages', models.DO_NOTHING, db_column='language', to_field='language', verbose_name='Language') label_field = models.TextField(db_column='label', blank=True, null=True, verbose_name='Label') title_field = models.TextField(db_column='title', verbose_name='Title') content_field = RichTextField(db_column='content', verbose_name='Page Contents') def route(self, request, path_components): print("Route is called") return super(MyDocument, self).route(request, path_components) class Meta: db_table = 'document_translations' unique_together = (('route_field', 'slug_field', 'language_field'),) When the request is made from the browser, MyDocument's route method is only called after the parent Page's route method. My first question is 'Why is parent's route method called before child's method?' The second question is 'How to override the Page model's route method completely?' -
How to connect MongoDB with Django?
I am using Python 3.6.3,Django 1.11.10,MongoDb 3.6.2. I already installed Django-nonrel,djangotoolbox,Django MongoDB Engine. What I need to change in django settings. -
Unable connect oracle 10g XE to django
I am trying to connect to oracle 10g XE database from windows but getting following error Here is my settings for database DATABASES = { 'default': { 'ENGINE': 'django.db.backends.oracle', 'NAME': 'xe', 'USER': 'xxx', 'PASSWORD': 'xxx', 'HOST': '127.0.0.1', 'PORT': '1527', } } installed libraries cx-Oracle==6.1 Django==1.11.10 pytz==2018.3 Tried to identify solutions but found nothing related -
django update data that already saved
I have a variable, j= sheet[col10].value and try to pass it as address1 = ADDRESS.objects.get(Store_Nbr = j) But this is showing an error "ADDRESS matching query does not exist". How can i achieve this? -
How RelatedFieldWidgetWrapper (django admin) loads the created content
I'm building a webpage that use ModelForm with ManyToMany relations. The Admin of django has the useful RelatedFieldWidgetWrapper. It creates a + next to relationfields that, when pressed, opens a popup to create a related-object. Once the creation is made the main webpage (the one where we press the +) has the new item loaded. Now, in my website I would like to have something similar, my questions are: is it correct to use the RelatedFieldWidgetWrapper in a webpage outside admin? how does the page autoloads the new content (this is mainly my curiosity) any other applicable solution to have a handy form without requiring complex JS or several pages? thanks -
Angular + Django: Sending POST request with cookies (CORS)
I'm developing an app using Angular for client side and Django for server side. During development I'm running Django in port 8000 for managing all API requests, and serving my client app using Angular CLI running at port 4200. Sending GET requests to Django work w/o problems but when I try to send a POST request that includes some cookies with session information, it fails as the cookies are not included in the header. I know that the source of this "problem" is the CORS issue [read more here] and that it won't be a problem in production as both client and server apps will be running in the same server and port, however I wonder how can I fix this situation at least for development. I've tried using the django-cors-headers module with the options CORS_ALLOW_CREDENTIALSand CORS_ORIGIN_ALLOW_ALL set to True but it didn't work. Any ideas? -
Format timestamp in Django query in values
I am trying to use a Dajngo QuerySet where I have to format time_stamp field in .values ('time_stamp'). In PostgreSql I can dot like this: GROUP BY time_stamp::date I have to do this because in the date column the format (2018-01-22 00:00:28+01) show time as well and I want know the average of the filed only in ONE day. So my main question how can I create a query in Django which equal with this PostgreSQL query. SELECT avg(field) FROM table GROUP BY time_stamp:date -
NoReverseMatch Error- Django
I am trying to build a Django project with multiple applications, hence using urls.py for each application. I encounter a NoReverseMatch Error when Django tries to access the view. Main urls.py: urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^intface/', intface), url(r'^',include("userapp.urls",namespace="userapp")),] userapp urls.py: urlpatterns=[ url(r'^user/',TemplateView.as_view(template_name="user.html")) ] user.html: <form method="POST" action="{% url "userapp:user" %}" > Error: NoReverseMatch at /user/ Reverse for 'user' not found. 'user' is not a valid view function or pattern name. Please help! -
Django including header.html dealigns
I am trying to create web app using django , i have the header html with a search module ,when i search for a particular result the header html included in the result page dealings.Below i have attacked the code for header.html and the based page html where i have extended the header.html. <!DOCTYPE html> <html lang="en"> <head> <title>Signals</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> {% load staticfiles %} <link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}" type="text/css"/> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <link rel="shortcut icon" type="image/png" href="{% static 'favicon.ico'%}"/> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> </head> <style> body { padding: 15px 15px 15px 15px; } html, body { height: 100%; width: 100%; margin: 0; } </style> <body class="body" style="background-color:#f6f6f6"> <nav class="navbar navbar-inverse"> <div class="container-fluid"> <div class="navbar-header navbar-center"> <a class="navbar-brand navbar-center" href="#">Signals</a> </div> <!--<div id="menu-outer"> <div class="table"> <ul id="horizontal-list"> <li><a href="#"><img src="images/list-item-1.gif" alt="list item 1" /></a></li> <li><a href="#"><img src="images/list-item-2.gif" alt="list item 2" /></a></li> <li><a href="#"><img src="images/list-item-3.gif" alt="list item 3" /></a></li> <li><a href="#"><img src="images/list-item-4.gif" alt="list item 4" /></a></li> </ul> </div> </div>--> <form class="navbar-form navbar-right-side" method="POST" action="search/">{% csrf_token %} <div class="input-group"> <input type="text" class="form-control" placeholder="Search" name="search" id="search"><br> <br><ul class="list-group" id="result"></ul> <div class="input-group-btn"> <button class="btn btn-default" type="submit" id="click"> <i class="glyphicon glyphicon-search"></i> </button> </div> </div> </form> </div> </nav> <div … -
How to make a search function in Django with multiple queryset?
Hi i'm having trouble with my search function, I want to get product and quantity items from DB as user inputs data in searchbar... but the problem is that im having getting no results.. any help? views.py def productsearch(request): try: product=request.GET.get['product'] quantity=request.GET.get['quantity'] product_result=Product.objects.filter(product_id__icontains=product) quantity_result=Product.objects.filter(quantity_onhand__icontains=quantity) return render_to_response('product/productlocation.html',{'product_result' : product_result,'quantity_result':quantity_result, 'product': product,'quantity':quantity}) except: return render_to_response('product/productlocation.html') template to show result {% if quantity_result %} {% for r in quantity_result %} {{r.quantity_onhand}} {% endfor %} {% else %} <h3>no results</h3> {% endif %} search bar <form action="{% url 'productsearch' %}" method="get"> <label for="from">Product</label> <input type="text" name="product" value={{request.GET.product}}> <br /><br /> <label for="to">Quantity &nbsp;</label> <input type="text" name="quantity" value={{request.GET.quantity}}> <br /> <input type="submit" value="Submit"> </form> models.py class Product(models.Model): product_id = models.CharField(max_length=100, primary_key=True) product_name=models.CharField("Product Name",max_length=50) product_unitprice=models.PositiveIntegerField("Unit Price") product_size=models.CharField("Product Size",max_length=10) productdetail=models.CharField("Product Detail",max_length=100) product_img=models.FileField() product_type= models.CharField(max_length=15,choices=product_choice, default='stockable') retailer_price=models.PositiveIntegerField() wholeseller_price=models.PositiveIntegerField() location=models.CharField("Locatiion",max_length=30) quantity_onhand=models.CharField("Quantity on Hand",max_length=30) product_status=models.CharField(max_length=15,choices=product_statuss, default='Available' ) -
django admin, how to check model instance belong to owner before deleting?
I tried overwriting def has_delete_permission(self, request, obj=None):, but obj is not passed when deleting a record in Django Admin. Any help would be appreciated! Thank you. -
iframe for Angular application not working, but only on mobile devices
I have an AngularJS application with a Django backend. I inserted an iframe onto another site and the application is working fine on desktop, and also on the Chrome debugger mobile menu. It also works on actual mobile devices when going to the actual Angular app. Its ONLY when I go to the iframe site on an actual mobile device where it doesn't work. It loads the html, but none of the data retrieved from our backend is populating the page like it does on the actual Angular app, and the iframe when on a desktop. Completely at a loss. I know its not my code since it works on all the other versions. Could this be an iframe issue, or perhaps an iOS issue ? -
Django ORM - Translate this self join query to ORM
Please help translate this SQL query to Django ORM query. select l.* from products l inner join products r on l.category = r.category where r.id = %s Please note that category is itself a ForeignKey that points to ProductCategory Model. Also, if possible combine this with this ORM query. Product.objects.prefetch_related('productrecipes', 'farmerprofiles', 'productfeedbacks') Thank you. -
How to pull values from a url and pass them in a text form field in my template page?
I am working on a DJANGO environment. I need to pull some values from a url. For instance : http://x.x.x.x/abc/abcde/?val1=123456&var1=random From the above url I need to pull the values of val1 and var1 and put/pass these values to a textbox field in a form in my HTML template. Later on, I need to pass these values to a Django views.py function. I had initially passed form values to views function using forms.py. I found that method to be better and easier than AJAX. However this time I need to first pull the url values. How can this be done ? I am pretty new in Django so I do not exactly know how to proceed. Thanks in advance -
null value in column "user_id" violates not-null constraint
I am working on a RSVP project based on Django. When I want to make a Event model and connect it with every user, It always has this error!The Event just has two fields: user and eventName. views.py def create_event(request): if request.method=='POST': form = CreateEventForm(data=request.POST) if form.is_valid(): form.save() return redirect('http://vcm-2971.vm.duke.edu:8080/rsvp/profile') else: form= CreateEventForm() args= {'form':form} return render(request, 'rsvp/create_event.html',args) else: form= CreateEventForm() args= {'form':form} return render(request, 'rsvp/create_event.html',args) models.py class Event(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) name = models.CharField(max_length=100,default='') forms.py class CreateEventForm(ModelForm): #name = forms.CharField(max_length=100,required = True) class Meta: model = Event fields=( 'name', ) -
Activate search, button Import and Export to Excel in Django Admin
I have the next code in Admin.py (Code 1), this code activate one search in the AdminDjango. But when I add code 2 and code 3 the search option is hidden I need that show the search option and buttons Import and Export from import_export import resources from import_export.admin import ImportExportModelAdmin from import_export.admin import ImportExportActionModelAdmin from app.models import Parte Code 1 class ParteAdmin(admin.ModelAdmin): list_display=['id','numero','modelo','unidad', 'proyecto','precio','tipo'] search_fields = ['unidad', 'proyecto','numero', 'modelo','tipo'] list_filter = ['tipo','nivel','unidad','proyecto'] code 2 class ParteResource(resources.ModelResource): class Meta: model = Parte code 3 class ParteAdmin(ImportExportModelAdmin): resource_class = ParteResource class ParteAdmin(ImportExportActionModelAdmin): pass admin.site.register(Parte,ParteAdmin) [enter image description here][1] [enter image description here][2] [enter image description here][3] -
Django authentication and cryptography - How does it works?
i’m new to django and I’ve wondered how the authentication system and hashed passwords worked in django? And why is it not possible to know the users password? (Even if i know the algorithm and the salt) In my mind, i see the authentication some what like a python condition: If input == password: authenticated =True (Obviously i know it isn’t coded like that) But I can’t figure out how it is hashed and unhashed, and if there is a way to know what the user password is? -
How to use deleteview for particular user and particular item in Django?
I have these models. Each reply can have none, one or more post. Post is user specific. How to make delete view so that user can only delete his post and not of posts by other on a reply. I tried this many time but my view is deleting post of some other user as well. Means any user can delete post of any other user. I want to make a button next to each post to delete, but button should be seen only to those who have written the post. class Reply(models.Model): User = models.ForeignKey(settings.AUTH_USER_MODEL) Question = models.ForeignKey(Doubt, on_delete=models.CASCADE) reply = models.TextField(max_length=40000) last_updated = models.DateTimeField(auto_now_add=True) image = models.ImageField(upload_to = upload_image_path, null = True, blank = True) created_at = models.DateTimeField(auto_now_add=True) def Post(self): return reverse("community:post", kwargs={"pk": self.pk}) class Post(models.Model): post = models.TextField(max_length=4000) reply = models.ForeignKey(Reply, on_delete = models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) time = models.DateTimeField(null=True) User = models.ForeignKey(settings.AUTH_USER_MODEL) -
Django QuerySet Count() Returns NoneType
In views, I have the following snippet: try: count = MembershipPurchaseHistory.objects.filter(user=self.request.user).count() except: count = 0 But somehow I got an error saying count has a NoneType value? How is this possible? -
Elastic Beanstalk Django App REST API Fails with Multiple EC2 Instances
I have a Django Application with the Django REST API framework setup on Elastic Beanstalk. My application works great when there is only 1 EC2 instance running. However when the application scales to more then 1 instance all API request start failing. Requests that don't require authorization fail. So it's not an authentication / token issue. These request also only seem to be failing within my Ionic application (v2+). My Django configuration has CORS_ORIGIN_ALLOW_ALL = True in it and like I said before this only stops working when multiple instances are spun up. The request fail in Ionic with the following message coming back in the Chrome Console. The requests fail in the browser, iOS but not Android. Failed to load https://xxxxxx/api/v1/series/?limit=30&offset=0: Response to preflight request doesn't pass access control check: The 'Access-Control-Allow-Origin' header contains multiple values '*, *', but only one is allowed. Origin 'http://localhost:8100' is therefore not allowed access. The interesting part is if I make a request using Postman it works fine. So it seems to be something to do with the HTTP Request library in Angular / Ionic. Digging into this further it seems that it is definitely a CORS issue, which must be related to … -
How to fix the Django All-Auth SocialApp matching query Error?
I'm using the Django All-auth login template. My app runs but when I click on the GitHub link I get these errors. The template has: {% get_providers as socialaccount_providers %} so the GitHub login should work, right? What do these errors below mean? DoesNotExist at /accounts/github/login/ SocialApp matching query does not exist. Request Method: GET Request URL: http://127.0.0.1:8000/accounts/github/login/?process=login&next=%2F Django Version: 1.11.10 Exception Type: DoesNotExist DoesNotExist: SocialApp matching query does not exist. [09/Feb/2018 00:37:59] "GET /accounts/github/login/?process=login&next=%2Fhome HTTP/1.1" 500 87171 -
Django - how to get list of inputs, selects dynamically created with javascript?
I have a javascript code to create all combination of product based on characteristics that are added dynamically. HTML eesult of this script is: <table> <tbody> <tr> <td>1</td> <td><select id="combination[0].product" name="combination[0].product"> <option value="25"> product_desc pc.10 </option> <option value="26"> product_desc pc.5 </option> <option value="21"> product_desc </option> </select></td> <td><input readonly="readonly" value="5.00" id="combination[0].price" name="combination[0].price" class="form-control" type="text" /></td> <td><input readonly="readonly" value="a" id="combination[0].color" name="combination[0].color" class="form-control" type="text" /></td> <td><input readonly="readonly" value="1" id="combination[0].quantity" name="combination[0].quantity" class="form-control" type="text" /></td> </tr> <tr> <td>2</td> <td><select id="combination[1].product" name="combination[1].product"> <option value="25"> product_desc pc.10 </option> <option value="26"> product_desc pc.5 </option> <option value="21"> product_desc </option> </select></td> <td><input readonly="readonly" value="5.00" id="combination[1].price" name="combination[1].price" class="form-control" type="text" /></td> <td><input readonly="readonly" value="a" id="combination[1].color" name="combination[1].color" class="form-control" type="text" /></td> <td><input readonly="readonly" value="5" id="combination[1].quantity" name="combination[1].quantity" class="form-control" type="text" /></td> </tr> <tr> <td>5</td> <td><select id="combination[8].product" name="combination[8].product"> <option value="25"> product_desc pc.10 </option> <option value="26"> product_desc pc.5 </option> <option value="21"> product_desc </option> </select></td> <td><input readonly="readonly" value="5.00" id="combination[8].price" name="combination[8].price" class="form-control" type="text" /></td> <td><input readonly="readonly" value="c" id="combination[8].color" name="combination[8].color" class="form-control" type="text" /></td> <td><input readonly="readonly" value="50" id="combination[8].quantity" name="combination[8].quantity" class="form-control" type="text" /></td> </tr> </tbody> </table> Of course there can be many more characteristics (for example type, material...). How can I process it with request.POST? I tried getlist but without success. For the record I use Django 1.9. Is there any way I … -
django-admin, add hyperlink in list_display to other application
under : mydomain/admin, I have several applications App1, app1modle1, app2model2, App2, app2model1, app2model2, App3, app3model1. In App3model1, say for each 'user',I want to add a column in list_display, and the content is a hyperlink to a corresponding model/table in App2, say what does the user sell, one-to-many relation. eg: under app3model1 (the link is mydomain/admin/app3/model1) u1,link u2,link, u3,link. and under app2model2 (the original view, link is mydomain/admin/app2/model2) u1,apple,$5 u1,orange,$10 u2,apple, $10 u3, grape, $5 Once I click the 'link' next to u1 in app3model1, I want to see mydomain/admin/app2/model2/?q=u1 u1,apple,$5 u1,orange,$10 I have tried the following code in App3/admin.py: list_display = ['username', 'link'] def link(self, obj): seller_link = 'admin/app2/model2/?q=' + obj.username return format_html("<a href= %s >link</a>" % seller_link) but it directs me to mydomain/admin/app3/model1/admin/app2/model2...and what I want is mydomain/admin/app2/model2.. with parameters. How can I achieve this?