Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get aggregation in django rest framework inside same api
Here is my models.py from __future__ import unicode_literals from django.db import models class User(models.Model): name = models.CharField(max_length=200) company_name = models.ForeignKey('Company',on_delete=models.CASCADE,related_name='user') def __str__(self): return self.name class Company(models.Model): name = models.CharField(max_length=200) phone_number = models.IntegerField(null=True,blank=True) def __str__(self): return self.name class Catalog(models.Model): name = models.CharField(max_length=200) no_of_pcs = models.IntegerField(null=True,blank=True) per_piece_price = models.DecimalField(null=True,blank=True,max_digits=10,decimal_places=2) company_name = models.ForeignKey(Company,on_delete=models.CASCADE,related_name='catalog') def __str__(self): return self.name here is my serializers.py from rest_framework import serializers from .models import * from django.db.models import Sum,Avg,Max,Min,Count,F,Q class CatalogSerializer(serializers.HyperlinkedModelSerializer): dynamic_data = serializers.SerializerMethodField() class Meta: model = Catalog fields = '__all__' def get_dynamic_data(self, obj): totalpieces = Catalog.objects.all().aggregate(total_pieces=Count('no_of_pcs')) totalprice = Catalog.objects.all().aggregate(total_price=Sum('per_piece_price')) print(totalpieces["total_pieces"],totalprice["total_price"]) return totalpieces["total_pieces"],totalprice["total_price"] class UserSerializer(serializers.ModelSerializer): # name = serializers.StringRelatedField() company_name = serializers.CharField() class Meta: model = User fields = '__all__' class CatalogData(serializers.ModelSerializer): class Meta: model = Catalog fields = ('name', 'no_of_pcs', 'per_piece_price') class CompanySerializer(serializers.ModelSerializer): # catalog_details = serializers.SerializerMethodField() # name = serializers.StringRelatedField() catalog = CatalogData(many=True) user = UserSerializer(many=True) class Meta: model = Company fields = ('name', 'phone_number', 'catalog','user') here is my views.py from __future__ import unicode_literals from django.http import HttpResponse from .models import * import json from django.http import JsonResponse, HttpResponse from .serializers import * from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from rest_framework import viewsets class CatalogView(viewsets.ModelViewSet): queryset = Catalog.objects.select_related('company_name') serializer_class = … -
Saving images from scrapy integrated with django
I’ve got a Scrapy project hooked up to a Django project and everything is working fine (i.e. when I run my scraper, I’m able to save items to the DB). I’m trying to add an image scraper to my project and I can’t get it to work. I can get Scrapy’s image scraper to work on its own but not when hooked up to the Django project The error I’m getting is the following: File "/Users/junaid/Desktop/clscraper2/lib/python3.6/site-packages/twisted/internet/defer.py", line 654, in _runCallbacks current.result = callback(current.result, *args, **kw) File "/Users/junaid/Desktop/clscraper2/lib/python3.6/site-packages/scrapy/pipelines/media.py", line 79, in process_item requests = arg_to_iter(self.get_media_requests(item, info)) File "/Users/junaid/Desktop/clscraper2/lib/python3.6/site-packages/scrapy/pipelines/images.py", line 155, in get_media_requests return [Request(x) for x in item.get(self.images_urls_field, [])] File "/Users/junaid/Desktop/clscraper2/lib/python3.6/site-packages/scrapy/pipelines/images.py", line 155, in <listcomp> return [Request(x) for x in item.get(self.images_urls_field, [])] File "/Users/junaid/Desktop/clscraper2/lib/python3.6/site-packages/scrapy/http/request/__init__.py", line 25, in __init__ self._set_url(url) File "/Users/junaid/Desktop/clscraper2/lib/python3.6/site-packages/scrapy/http/request/__init__.py", line 62, in _set_url raise ValueError('Missing scheme in request url: %s' % self._url) ValueError: Missing scheme in request url: h Here’s my project: Models.py class atl_sale_listing(models.Model): metro_area = models.CharField(max_length=40, null=False, blank=False) listing_id = models.CharField(max_length=250, null=False, blank=False, unique=True) #must be unique url = models.CharField(max_length=450, null=True, blank=True) status = models.CharField(max_length=25, null=True, blank=True) price = models.IntegerField(null=True, blank=True) tax = models.FloatField(null=True, blank=True) Items.py -- Note - I'm adding the image_urls and images field to … -
Unable to resolve URL string for path using name with reverse
I have been spending the better part of my week learning Django to build my website and I've stumbled upon an issue I can't seem to get working. I wish to resolve a URL string for a path by including with that path a particular name and then being able to reference that name down the line. This works fine until I change the route in path to use the include method. First Attempt: from django.url import include, path from . import views urlpatterns = [ path('testapp/', include('testapp.urls'), name='testapp'), path('about/', views.about, name='about'), ] Now when I call {% url 'about' %} from my template html file I get back '/about/' as expected but when I try and call {% url 'testapp' %} I get a NoReverseMatch exception instead of getting '/testapp/'. After digging through the documentation I stumbled upon this example that shows path with include using a namespace instead so I adapted the above a bit. Second Attempt: # from mysite/urls.py (adapted from before) from django.url import include, path from . import views urlpatterns = [ path('testapp/', include('testapp.urls', namespace='testapp')), path('about/', views.about, name='about'), ] #from testapp/urls.py from django.url import include, path from . import views app_name = 'testapp_name' urlpatterns = … -
how to insert data in elasticsearch for nested types?
I am new to elasticsearch.I am using elasticsearch with django.I successfully created elasticsearch index, { "productcategories": { "aliases": {}, "mappings": { "product_categories": { "properties": { "categoryName": { "type": "text" }, "subCategories": { "type": "nested", "properties": { "partNumbers": { "type": "nested" }, "subCategoryName": { "type": "text" } } } } } }, "settings": { "index": { "creation_date": "1537766526678", "number_of_shards": "5", "number_of_replicas": "1", "uuid": "k_8XilbrTn2jM03Djp1pXQ", "version": { "created": "6040099" }, "provided_name": "productcategories" } } } } and I am trying to insert data using format, data={ "categoryName":'TestConnector', "subCategories": [ { 'subCategoryName':'Connector1', 'partNumbers':['HFBR-2412T','HFBR-2506AMZ'] }, { 'subCategoryName':'Connector2', 'partNumbers':['HFBR-2422Z','HFBR-2412Z'] } ] } settings.ES_CLIENT.index(index=ProductCategories._meta.es_index_name,doc_type=ProductCategories._meta.es_type_name,body=data) It gives me following error, elasticsearch.exceptions.RequestError: RequestError(400, 'mapper_parsing_exception', 'object mapping for [subCategories.partNumbers] tried to parse field [null] as object, but found a concrete value') can anyone help me. -
Django error occurs while saving data fetched from Twitter api into database
I am trying to save data from Twitter api. While doing so, TypeError: get_serializer() got an unexpected keyword argument "many" error occurs. I think it is due to calling too MANY get_serializer() The below is how I fetch data from twitter api for statusNEAR in tweepy.Cursor(api.search, q='#NYU', geocode="40.72942,-73.99721,1km").items(1): json_dataNEAR = (statusNEAR._json) nearTEXT_data = json_dataNEAR['text'] nearNAME_data = json_dataNEAR['user']['name'] nearUSERNAME_data = json_dataNEAR['user']['screen_name'] nearLOCATION_data = json_dataNEAR['user']['location'] class TweetListCreate(generics.ListCreateAPIView): model = Tweet def get_serializer(self): return TweetSerializer def get_queryset(self): return Tweet.objects.all() def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.DATA) if not serializer.is_valid(): return Response( serializer.errors, status=status.HTTP_400_BAD_REQUEST) tweet = Tweet.objects.create( type= 'near', text = context['near']['text'], name = context['near']['name'], username = context['near']['username'], location = context['near']['location'], month = context['near']['month'], day = context['near']['day'], hour = context['near']['hour'], min = context['near']['min'], year = context['near']['year'], retweet = context['near']['retweet'], favorite = context['near']['favorite'], img = context['near']['imgurl'] ) result = TweetSerializer(tweet) return Response(result.data, status=status.HTTP_201_CREATED) Images are attached for the details Error CodeHow I try to save data into database thanks in advance -
How to filter names based on the letter in Django?
My question is that im having normal form having fields like productname and price model.py (This was main model where all product already stored) product_name = models.CharField(max_length=255) price =models.IntegerField() html <form action="/event/" method="POST" enctype="multipart/form-data"> <div> <label for="pro_name"> Product Name </label> <input type="text" name="product_name " class="form-control" id="pro_name"> </div> <div> <label for="pri"> price </label> <input type="text" name="price " class="form-control" id="pri"> </div> <div> <label for="qnt"> Quantity </label> <input type="text" name="quantity" class="form-control" id="qnt"> </div> <div> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> <button type="submit" class="btn btn-primary">Save changes</button> </div> </form> In this form when the user starts typing product name based on that letter it should list out similar product names. please help me to do this. -
Testing when a ValidationError is raised
I am new to programming and Django in general. I am trying to test one of my functions to make sure that a validation error is raised. The test confirms that the error is raised but also says the test Failed. How is this possible? #models.py def check_user_words(sender, instance, **kwargs): for field in instance._meta.get_fields(): #field_name = getattr(instance, field.attname) if (isinstance(field, models.CharField) and contains_bad_words(getattr(instance, field.attname))): raise ValidationError("We don't use words like '{}' around here!".format(getattr(instance, field.attname))) #tests.py def test_check_user_words(self): question = create_question(question_text="What a minute bucko", days=1) with self.assertRaises(ValidationError): check_user_words(question) question.full_clean() #after running python manage.py test polls ...... raise ValidationError("We don't use words like '{}' around here!".format(getattr(instance, field.attname))) ValidationError: [u"We don't use words like 'What a minute bucko' around here!"] -
autocomplete_fields shows error "ValueError: invalid literal for int() with base 10: 'Empty'"
My autocomplete was working but something broke it Here is the admin.py from django.contrib import admin from pages.models import Ipaddress, DeviceGroup, Location,Department,Comment from django_admin_listfilter_dropdown.filters import DropdownFilter, RelatedDropdownFilter class DepartmentAdmin(admin.ModelAdmin): search_fields = ['name'] class LocationAdmin(admin.ModelAdmin): search_fields = ['description'] class IpaddressAdmin(admin.ModelAdmin): prepopulated_fields = {'slug': ('ipaddress',)} search_fields = ['ipaddress','location','department',] list_display = ('ipaddress', 'machinename', 'user', 'department','location','updated',) list_display_links =('ipaddress', 'machinename', 'user', 'department','location','updated',) autocomplete_fields = ['location','department',] list_filter = ( ('user', DropdownFilter), ('department', RelatedDropdownFilter), ('location', RelatedDropdownFilter), ) Here is my model.py class Ipaddress(models.Model): ipaddress=models.CharField("Ip Address",max_length=20) slug = models.SlugField(unique=True) machinename=models.CharField("Machine Name",max_length=500) user=models.CharField("User",max_length=200) department= models.ForeignKey("Department", on_delete=models.CASCADE,default='Empty') location= models.ForeignKey("Location", on_delete=models.CASCADE) updated = models.DateField("Date Updated",null=True) note =models.TextField() class Meta: verbose_name = 'IP Management' def __str__(self): return self.ipaddress[:50] when I try to add a new Ip address it shows me following error in HTML page In the console it shows following error: ValueError: invalid literal for int() with base 10: 'Empty' I have not made any big changes other than adding class Meta. all other models working fine only this one is shows error when try to add a new record. -
Python Django ValueError: The view app.views.register_user didn't return an HttpResponse object. It returned None instead
I'm very new with the Django framework, creating the sample application for user registration and login views.py from django.shortcuts import render, redirect, HttpResponse from app_StageBr.forms import RegisterForm from app_StageBr.forms import ProfileForm def register_user(request): if request.method == 'POST': register = RegisterForm(request.POST, prefix='register') usrprofile = ProfileForm(request.POST, prefix='profile') if register.is_valid() * usrprofile.is_valid(): user = register.save() usrprof = usrprofile.save(commit=False) usrprof.user = user usrprof.set_token() usrprof.subscribed = '1' usrprof.save() return HttpResponse('congrats') else: userform = RegisterForm(prefix='register') userprofileform = ProfileForm(prefix='profile') return render(request, 'app_StageBr/register.html', {'userform': userform, 'userprofileform': userprofileform}) template: <form action="" method="post"> <div class="field"> {{ userform.first_name.errors }} <label for="id_first_name">First name: </label> {{ userform.first_name }} </div> <div class="field"> {{ userform.last_name.errors }} <label for="id_last_name">Last name: </label> {{ userform.last_name }} </div> <div class="field"> {{ userform.email.errors }} <label for="id_email">Email: </label> {{ userform.email }} </div> <div class="field"> {{ userform.username.errors }} <label for="id_username">Username: </label> {{ userform.username }} </div> <div class="field"> {{ userform.password.errors }} <label for="id_password1">Password: </label> {{ userform.password }} </div> <div class="field"> {{ userprofileform.address.errors }} <label for="id_address">Address: </label> {{ userprofileform.address }} </div> <div class="field"> {{ userprofileform.city.errors }} <label for="id_city">City: </label> {{ userprofileform.city }} </div> <div class="field"> {{ userprofileform.post.errors }} <label for="id_post">Post: </label> {{ userprofileform.post }} </div> {% csrf_token %} <input type="submit" value="Submit"> </form> models.py from django.db import models from random import choice from django.utils.translation import … -
Django model is refering itself
I am using the django user model and want to create a logic that which user has been registered by which user like admin as a user can only register another employee or admin as a user. Means an entry in the user model can be created by another user(user in the same user model) under some business logic. I want to reference/know which user belongs to which user.and don't wanna create a new model to do this until no way left. please help me with this. Thank you -
Django translations in Javascript files
I followed the Django doc to internalize the js files, but it does not work. Here's my setup: settings.py: LOCALE_PATHS = (os.path.join(BASE_DIR, 'locale'),) urls.py in root project: from django.views.i18n import JavaScriptCatalog from django.conf.urls.i18n import i18n_patterns urlpatterns += i18n_patterns( path('jsi18n/', JavaScriptCatalog.as_view(), name='javascript-catalog'), ) Running the following commands inside the folder and the .po and .mo files were generated: django-admin makemessages -l pt_BR django-admin makemessages -d djangojs -l pt_BR django-admin makemessages -a django-admin compilemessages djangojs.po file: msgid "Customer" msgstr "Cliente" In the html template use as follows: <script type="text/javascript" src="{% url 'javascript-catalog' %}"></script> console.log( gettext('Customer') ); Nothing happens, the text continues in English. Does anyone know what can it be? -
Typeahead search with Django/Jquery not quite working
I have a search bar that is getting autocompleted models in my Django app using typeahead.js, but I was looking for some assistance with clicking the autocompleted result to go to the model detail page. Right now you cannot click it or search the result. I will post my view and template. Thank you for your assistance. *views.py* def get_members(request): if 'query' in request.GET: q = request.GET.get('query', '').capitalize() member_list = [] member_dict = {} members = Member.objects.all().filter( Q(last_name__icontains=q) | Q(first_name__icontains=q) | Q(number__icontains=q) ).distinct() for m in members: member_list.append(m.search_result) member_dict['options'] = member_list data = json.dumps(member_dict) mimetype = 'application/json' return HttpResponse(data, mimetype) return HttpResponse() Note: On the append(m.search_result), this is a model property which I'm sure is not recommended and will post as well below. I am open to a better method here as well. *models.py* @property def search_result(self): "Returns the member's number: full name in autocomplete search." return '%s: ' '%s %s' % (self.number,self.first_name,self.last_name) *html template* {% csrf_token %} <input type="search" name="searched_item" id="searched_item" class="form- control" autocomplete="off" placeholder="Enter member name to be searched (eg. John Smith)" style="max-width: 700px;width: 700px;color: threeddarkshadow;"> <script> $(document).ready(function($) { $('#searched_item').typeahead({ items:12, source: function (query, process) { return $.get('/membership/search/', { query: query }, function (data) { return process(data.options); }); … -
how to search in multiple columns using search_fields
I have multiple columns in a model. I am attaching a screenshot: I can search only IP address but I also want to search in Department and location. Any idea how to solve this: Here is my admin.py looks like: from django.contrib import admin from pages.models import Post, Device, DeviceType, DeviceModel, Ipaddress, DeviceGroup, Location,Department,Comment from django_admin_listfilter_dropdown.filters import DropdownFilter, RelatedDropdownFilter class IpaddressAdmin(admin.ModelAdmin): prepopulated_fields = {'slug': ('ipaddress',)} search_fields = ['ipaddress','department', 'location',] list_display = ('ipaddress', 'machinename', 'user', 'department','location','updated',) list_display_links =('ipaddress', 'machinename', 'user', 'department','location','updated',) # autocomplete_fields = ['department', 'location',] list_filter = ( ('user', DropdownFilter), ('department', RelatedDropdownFilter), ('location', RelatedDropdownFilter), ) list_per_page = 100 class DepartmentAdmin(admin.ModelAdmin): search_fields = ['name'] class LocationAdmin(admin.ModelAdmin): search_fields = ['description'] Following line is giving me error search_fields = ['ipaddress','department', 'location',] The error i am seeing is: C:\Users\mohiuddin_rana\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\sql\query.py", line 1087, in build_lookup raise FieldError('Related Field got invalid lookup: {}'.format(lookup_name)) django.core.exceptions.FieldError: Related Field got invalid lookup: icontains [23/Sep/2018 23:45:19] "GET /admin/pages/ipaddress/?q=dev HTTP/1.1" 500 155606 How to search in multiple columns? -
merge table django query
I have 4 tables: station(models.Model): station_name=models.CharField() data1(models.Model): station = models.ForeignKey(station) date = models.DateField() value1 = models.CharField() data2(models.Model): station = models.ForeignKey(station) date = models.DateField() value2 = models.CharField() value3 = models.CharField() data3(models.Model): station = models.ForeignKey(station) date = models.DateField() value4 = models.CharField() value5 = models.CharField() and my querysets: mydate = '2018-09-09' data_1 = data1.objects.filter(date__gte= mydate ) <Queryset[<data1 : 2018-09-19>,<data1 : 2018-09-19>,<data1: 2018-09-20>] data_2 = data1.objects.filter(date__gte= mydate ) <Queryset[<data2 : 2018-09-19>,<data2 : 2018-09-19>,<data2: 2018-09-22>,<data2: 2018-09-23>] data_3 = data1.objects.filter(date__gte= mydate ) <Queryset[<data3 : 2018-09-19>,<data3 : 2018-09-19>,<data3: 2018-09-22>] Now i want display queryset to table in html like bellow station | date | value1 | value2 | value3 | value4 | value5 1 | 2018-09-19| x1 | y1 | z1 | a1 | b1 2 | 2018-09-19| x2 | y2 | z2 | a2 | b2 1 | 2018-09-20| x3 | Null | Null | Null | Null 2 | 2018-09-22| NUll | y4 | z4 | a4 | b4 1 | 2018-09-23| NUll | y5 | z5 | Null | Null How to do that please help me thanks you alot. -
IntegrityError, (1048, "Column 'category_owner_id' cannot be null")
I would like to POST server's data to frontend by axios, But I continuously face the error ; IntegrityError at /profile/ (1048, "Column 'category_owner_id' cannot be null") I'm using DRF in backend and React in frontend. Here is my React and DRF part. getCategory.js axios({ url: 'http://127.0.0.1:8000/profile/', method: 'POST', data: { data: this.state.information, }, contentType: 'application/json', }) .then(res => { console.log(res); }) .catch(err => { console.log(err); }) Serializer.py class CategorySerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Category fields = ('id', 'category_name', 'category_owner_id', 'parentId') views.py class SettingView(viewsets.ModelViewSet) : queryset = models.Category.objects.all() serializer_class = CategorySerializer def get(self, request) : return JsonResponse(context) def post(self, request, format=None): return Response("ok") Of course, I quickly checked to go inside http://127.0.0.1:8000/profile/ if there is null value in column 'category_owner_id', but none of them is null.. enter image description here I'm new to django REST Framework, so all of your help will be great for me! -
Cannot access my django app at google cloud on port 8000
I'm trying to run my djnago application on google cloud by using the following command: python manage.py runserver 0.0.0.0:8000 The Application runs as normal and start receiving the sensor measurement data as the screenshot shows. However when I try to access the django admin section by visiting http://35.237.20.70:8000/admin it does not connect and says "The Site Cannot Be Reached". Also when I try to send data from Postman to the same url for sensor measurement It also returns the same error.Screenshot of application running on gcloud. -
Little issue with django and EmailMultiAlternatives sending emails
Hello guys I hope you can help me with an issue with django. I’m trying to send an email with EmailMultiAlternatives and all words fine, the only problem is that I need to use accent in the company name, let’s suppose it’s “México Perú México CO” when I write accent it does not show the company name only the email, the mail that was sent, if I write the company name without accent or uppercase there is not a problems but I really would like to write the company name with accents, I have tried to encode and decode but it doesn’t work. from django.core.mail import EmailMultiAlternatives subject, from_email, to = 'hello', 'Welcome to México Perú México CO', 'to@example.com' text_content = 'This is an important message.' html_content = '<p>This is an <strong>important</strong> message.</p>' msg = EmailMultiAlternatives(subject, text_content, from_email, [to]) msg.attach_alternative(html_content, "text/html") msg.send() Thank you ! -
how to add multiple autocomplete in django admin page
I am using built in function to build autocomplete for many fields: https://docs.djangoproject.com/en/2.0/ref/contrib/admin/#django.contrib.admin.ModelAdmin.autocomplete_fields I have following model: class Ipaddress(models.Model): ipaddress=models.CharField(max_length=20) slug = models.SlugField(unique=True) machinename=models.CharField(max_length=500) user=models.CharField(max_length=200) department= models.ForeignKey('Department',on_delete=models.CASCADE,default='Empty') location= models.ForeignKey('Location', on_delete=models.CASCADE) updated = models.DateField("Date Updated",null=True) note =models.TextField() def __str__(self): return self.ipaddress[:50] class Department(models.Model): name= models.CharField(max_length=100, unique=True) def __str__(self): return self.name[:50] class Location(models.Model): description= models.CharField(max_length=100, unique=True) def __str__(self): return self.description[:50] The admin page is here: from django.contrib import admin from pages.models import Ipaddress, DeviceGroup, Location,Department, from django_admin_listfilter_dropdown.filters import DropdownFilter, RelatedDropdownFilter class IpaddressAdmin(admin.ModelAdmin): prepopulated_fields = {'slug': ('ipaddress',)} search_fields = ['ipaddress'] autocomplete_fields = ['department',] list_display = ('ipaddress', 'machinename', 'user', 'department','location','updated',) list_filter = ( ('user', DropdownFilter), ('department', RelatedDropdownFilter), ('location', RelatedDropdownFilter), ) If i change the autocomplete_fields = ['location',] it works but it does not work when i try to change it department. Also i want to have autocomplete for both department and location at the same time. The error i am seeing is when i set autocomplete_fields = ['department',] ERRORS:<class 'pages.admin.IpaddressAdmin'>: (admin.E040) ModelAdmin must define "search_fields", because it's referenced by IpaddressAdmin.autocomplete_fields. Any idea how to fix this error I want to some thing like this: autocomplete_fields = ['department', 'location','user',] -
Tying input form to view but not seeing results.
I'm trying to create a currency converter and so far I created a Form with input value, and 2 dropdown from my database for the currency. class MyForm(forms.Form): value = forms.IntegerField() coin1 = forms.ModelChoiceField(queryset=Post.objects.all()) coin2= forms.ModelChoiceField(queryset=Post.objects.all()) Then with the coin1,coin2 values, it would go through my database to find the price rate by the Post.objects.filter and output pricecoin1,pricecoin2 and finally go through a cal_currency function to calculate with given value. Input and results will both be in the about.html def about(request): if request.method == 'POST': form = MyForm(request.POST) if form.is_valid(): value = form.cleaned_data['value'] coin1 = form.cleaned_data['coin1'] coin2 = form.cleaned_data['coin2'] if (Post.objects.filter(symbol =coin1).exists() and Post.objects.filter(symbol = coin2).exists()): pricecoin1 = Post.objects.get(symbol=coin1).price pricecoin2 = Post.objects.get(symbol=coin2).price final_convert= calc_currency(value,pricecoin1,pricecoin2) return render(request, 'blog/about.html', {'final_convert':final_convert, 'coin1':coin1,'coin2':coin2, 'value':value}) else: form = MyForm() return render(request, 'blog/about.html', {'form':form} ) My input template work fine, but here is the html code for result, for some reason it's not showing value, coin1,coin2, and final_converter after submit. Where did I go wrong? These are in my render right? <h1> The price of {{value}} <u>{{coin1}}</u> in <u>{{coin2}}</u> is <u>{{final_convert|floatformat}}</u>. </h1> -
Django App with Tinder script deployed on Heroku (Selenium + Chromedriver) need guidance
Has anyone had experience deploying a Django app on Heroku that contains a script within it? I'm currently building a web app that works as a front end tool to a couple of python bots that I have been creating during the years, as well as for personal useful tools (Scripts). The issue is that I've been trying to deploy my app on Heroku and test the functionality of running my Tinder Bot from within Heroku, but I have not been successful, i'm currently getting errors such as: "unknown error: Chrome failed to start: exited abnormally (unknown error: DevToolsActivePort file doesn't exist" Thing's that I've done to try to solve the issue: 1- Setting the chrome arguments as: chrome_settings = Options() chrome_settings.add_argument('--headless') chrome_settings.add_argument('--no-sandbox') chrome_settings.add_argument('--disable-dev-shm-usage') As well as setting the directories for chrome binary and chromedriver to: GOOGLE_CHROME_BIN = '/app/.apt/usr/bin/google-chrome' path_of_chrome_driver = '/app/.chromedriver/bin/chromedriver' But I am still getting the same error. Would anyone know whats the proper procedure to create a web app that can contain python scripts in it, and to be deployed on Heroku? Ps: I have followed the steps to set up (Whitenoise and gunicorn) for heroku deployment. Requirements: Django==2.1.1 gunicorn==19.9.0 pytz==2018.5 selenium==3.14.1 urllib3==1.23 whitenoise==4.1 This is the … -
Catch TemplateDoesNotExist in django for 500, 404
Is there a way to do something like the following instead of django trying to load a template here? def 500(request): log.error('500 error') return HttpResponse(status=500) Otherwise I get a: File "/Library/Python/2.7/site-packages/django/template/loader.py", line 138, in find_template raise TemplateDoesNotExist(name) TemplateDoesNotExist: 500.html And I don't want to include a 500 or 404 template. -
update local MySQL database from official, django
please forgive me for uncleared terms. I am picking up a job from work that I am very new but no one else knows about. we have a django application, I have the local copy of the database for my development and testing purpose. after started making modification, I realized users have updated the official database, how do I get their updates and make sure they are in my local database? I thought about manage.py dbshell git pull, but that would be the code instead of the database, right? please help me with this super basic problem. thank you -
About how to update data on queryset
I'm trying to update own data but i think didn't work, i don't know why. def get_queryset(self): self.queryset = None #... some code to get billing_obj & cart_obj & shipping_address_id.... if billing_obj is not None: order_obj = models.Order.objects.new_or_get(billing_obj=billing_obj, cart_obj=cart_obj) if shipping_address_id: order_obj.shipping_address = Address.objects.get(id=shipping_address_id) if billing_address_id: order_obj.billing_address = Address.objects.get(id=billing_address_id) if billing_address_id or shipping_address_id: order_obj.update() return self.queryset And i have got 'QuerySet' object has no attribute 'save' when i use .save(). And about update don't show me any error but didn't update data. -
Django using generic views, error http 405
I am trying use the django generic view for CRUD, but the DeleteView result in error 405, following the guide official Django https://docs.djangoproject.com/en/2.1/ref/class-based-views/generic-editing/ , I don't understand where is my error, so that's my code: views.py class ContatoDeleteView(DeleteView): template_name = 'contato/contato_delete.html' def get_object(self): id_ = self.kwargs.get("id") return get_object_or_404(Contato, id=id_) def get_success_url(self): return reverse('contato:contato-list') urls.py from django.urls import path from .views import ( ContatoCreateView, ContatoDeleteView, ContatoDetailView, ContatoListView, ContatoUpdateView, ) app_name = 'contato' urlpatterns = [ path('', ContatoListView.as_view(), name='contato-list'), path('create/', ContatoCreateView.as_view(), name='contato-create'), path('<int:id>/', ContatoDetailView.as_view(), name='contato-detail'), path('<int:id>/update/', ContatoUpdateView.as_view(), name='contato-update'), path('<int:id>/delete/', ContatoDeleteView.as_view(), name='contato-delete'), ] contato_delete.html <form action='.' method='post'>{% csrf_token %} <dialog class="mdl-dialog"> <h6>Deseja excluir {{ object.nome }}?</h6> <div class="mdl-dialog__actions"> <input type="submit" class="mdl-button mdl-js-button mdl-button--accent" value="Excluir"> <button type="button" class="mdl-button close">Cancelar</button> </div> </dialog> </form> contato_detail.html {% extends 'base.html' %} {% load staticfiles %} {% block content %} <style> #fab { position: fixed; display: block; right: 0; bottom: 0; margin-right: 40px; margin-bottom: 40px; z-index: 900; } .demo-list-icon { margin-left: 30px; } .mdl-card__title{ margin-left: 30px; } .mdl-button{ margin-right: 10px; margin-top: 10px; } </style> <div class="mdl-card__title"> <h2 class="mdl-card__title-text">{{ object.nome }}</h2> </div> <div class="mdl-layout-spacer"></div> <a id="show-dialog" class="mdl-button mdl-js-button mdl-button--icon"> <i class="material-icons">delete</i> </a> {% include "contato/contato_delete.html" %} <script type="text/javascript" src="{% static 'js/dialog.js' %}"></script> <div class="mdl-card__actions mdl-card--border"> <ul class="demo-list-icon mdl-list"> <li class="mdl-list__item"> … -
TypeError at /add_team/ 'dict' object is not callable
views.py: class AddTeamView(View): template_name = 'add_team.html' def get (self, request): form = TeamForm() context = {'form': form} return render(request, 'add_team.html', context) def post(self, request): form = TeamForm(request.POST) if form.is_valid(): team = Team() team.name = form.cleaned_data('name') team.details = form.cleaned_data('detials') context = {'form': form, 'team.name':team.name,'team.details':team.details} return render(request, self.template_name, context) add_team.html : {% extends 'base.html' %} {% block title %} add team {% endblock %} {% block content %} <form action="/add_team/" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Submit"> </form> {% endblock %} forms.py : from django import forms class TeamForm(forms.Form): name = forms.CharField(label='name of team') details = forms.CharField(label='details of team') when I went to the browser it appeared this: TypeError at /add_team/ 'dict' object is not callable Request Method: POST Request URL: http://127.0.0.1:8000/add_team/ Django Version: 2.1.1 Exception Type: TypeError Exception Value: 'dict' object is not callable Exception Location: C:\Users\Acer\Desktop\teammanager\teams\views.py in post, line 52 Python Executable: C:\Users\Acer\Desktop\teammanager_env\Scripts\python.exe Python Version: 3.7.0