Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Keras Model Prediction Multiple Times One Program
I am currently using Django to serve a Keras model. Currently, I have it set to load the model once, when the server is started, but I am having errors when making predictions. For the first prediction it is able to make a prediction, but for the second and onward predictions it is giving me an error: Cannot interpret feed_dict key as Tensor: Tensor Tensor("Placeholder:0", shape=(5, 400), dtype=float32) is not an element of this graph. I believe this has something to do with Tensorflow session because I am using Tensorflow as the backend for the Keras model. However, I am not sure how to fix this issue as I can't just restart the server after every prediction. I need to have a way where I can load the model once but have it make predictions multiple times with the model only being loaded at first. Any help is much appreciated. -
Django REST with gRPC
Has anyone integrated these 2 technologies successfully? I want to expose gRPC using Django REST. Is that possible? If so, are there any good examples out there? Any help would be appreciated. Thanks. -
How to get object add to it or create it if it doesn't exist
Hello I done making a mini inventory app **kind off but on testing the app I ran into a problem which I did not think about before creating the app. My models look something like this class Branch(models.Model): name=models.CharField(max_length=20) def __str__(self): return self.name.title() class Stock(models.Model): .... branch = models.ForegnKey(Branch, related_name="stock", on_delete=models.CASCADE) class Waybill(models.Model): product = models.ForeignKey(Stock, related_name="waybill", on_delete=models.CASCADE) I have a signal on stock model to reduces the quantity of on Waybill save like this def update_stock_on_waybill(sender, instance, **kwargs): instance.product.quantity -= instance.quantity instance.product.save() pre_save.connect(update_stock_on_sales, sender=Waybill) Now My problem is this if Eg: Branch A is sending stock to Branch B and I want to create a new stock object from the waybill that I am getting from stock object how do I achieve this. I have read update_or_create() it seems like a good candidate for my problem but I don't know how to apply it since I am relatively new to django. thanks in adv. -
PayPal Rest SDK execute payment url No Post Data
I have been working on integrating paypal express checkout into my website and am having a strange issue. onAuthorize: function(data) { return paypal.request.post(EXECUTE_PAYMENT_URL, { paymentID: data.paymentID, payerID: data.payerID }).then(function(res) { console.log(res.success) // The payment is complete! // You can now show a confirmation message to the customer }); def confirm_paypal_payment(request): '''Confirm Paypal.com payment.''' if request.method == 'POST': payment_id = request.POST['paymentID'] payer_id = request.POST['payerID'] After I make a post request to the EXECUTE_PAYMENT_URL, I am receiving an error that the post data key does not exist. I have also tried to find these values on request.body to no avail. Thoughts? Exception Type: MultiValueDictKeyError Exception Value: "'paymentID'" -
Crispy forms inline radio button doesn't work for me
class RatingForm(forms.Form): def __init__(self, *args, lista_de_productores, **kwargs): super(forms.Form, self).__init__(*args, **kwargs) for p in lista_de_productores: CHOICES = (('1', '1',), ('2', '2',), ('3', '3',) , ('4', '4',) , ('5', '5',)) self.fields[str(p)] = forms.ChoiceField(required=True, widget=forms.RadioSelect(), choices=CHOICES) helper = FormHelper() helper.layout = Layout( InlineRadios(str(p)) ) Not sure what I'm doing wrong but this just displays normal radio buttons instead of inline -
Make multiple API calls using Django
I am trying to make an API call and am able to get it working when I request it with a given input (so returning one record, and making the API call on that one record) from a form. Now, if the input is not provided I want to loop through all rows in the actual table, and make API calls for any missing data columns... However, when I try to make multiple requests on the same page, on form submit, I can't get the api call to work, I get this error: JSONDecodeError at /url Expecting value: line 1 column 1 (char 0) Request Method: POST Request URL: http://localhost:8000/url Django Version: 2.1.1 Exception Type: JSONDecodeError Exception Value: Expecting value: line 1 column 1 (char 0) Exception Location: C:\Users\AppData\Local\Programs\Python\Python37-32\Lib\json\decoder.py in raw_decode, line 355 Python Executable: C:\Users\.virtualenvs\projects\Scripts\python.exe views to make the API call: class API(View): def get(self, request, *args, **kwargs): url = 'https://ExternalAPI/{param1}'.format(param1=param1) response = requests.get(url, headers={'x-Key': settings.KEY}) if response.status_code == 404: return JsonResponse({}) return JsonResponse(response.json()[0]) # Works for 1 row, doesn't work when called within a loop from a form submission.... def getAnotherAPICall(self, request, address): print('getting data...') response = requests.get('{}?param={}&id={}'.format(settings.URL, data, settings.ID)) data = response.json() result = data['Response'][0] # This … -
how to retrieve data from a query set in django and put it inside an array without putting the column names
I have to insert the data from a query set in django to an array and not a dictionary without entering the column name. My django code : permissions = Permission.objects.all().order_by('perm_label') array = [] name1 = [] for type in permissions: name1.append(type) array.append(name1) name1 = [] Here i can do for example name1.append(type.personName) but i would like to loop through the data without setting the name of the column -
Not addind one-to-many relationship
I hava class class Read(models.Model): class Meta: verbose_name_plural = 'reads' id=models.AutoField(primary_key=True); name = models.CharField(max_length=30, null=True); owner_reader = models.ForeignKey(User, related_name='owner_reader', null=False, blank=True,on_delete=models.PROTECT) # тот, кто прочитал articles_readed = models.ManyToManyField(Article, null=False, related_name='articles_readed') # те, на кого он пдписалса And want adding article to read item: def mark_readed(request,id): #id -article id user =request.user # подписант try: reader1 = Read.objects.get(name='test',owner_reader=request.user) except Read.DoesNotExist: reader1 = Read.objects.create(name='test',owner_reader=request.user) article = Article.objects.get(pk=id) reader1.articles_readed.add=article reader1.save(); return main(request) But in result I have only readed item wisout articles. -
Any way I can shorten the length of this date without having to run date()?
I am working with django and using angularjs. I made a request which responded with an object containing the name, price and date this input was modified. My html has the following {{price_level.modified }} providing me with 2018-01-16T10:15:34.401839Z. Here is the data that I am getting when I console.log the data created: "2017-06-02T05:01:17.803045Z" fs_charge: 10 id: 595 locked: false modified: "2018-02-06T07:36:21.517414Z" moq: 30 moq_price: 60 -
Django: search with haystack and whoosh - paginator redirects back to empty form
I am stuck on a problem that I never encountered before. I was trying to integrate a new search with haystack and whoosh and found some useful code for that. I used a form to display the CharField. forms.py class SearchForm(forms.Form): query = forms.CharField(label='Search:') Everything worked fine. Then I tried to add pagination to the page, which worked too, with the exception that when I click on "next page" it redirects me back to the empty form on my index.html template and not to the next search results. views.py def index(request): form = SearchForm() if 'query' in request.GET: form = SearchForm(request.GET) if form.is_valid(): cd = form.cleaned_data results = SearchQuerySet().models(Profile).filter(content=cd['query']).load_all() total_results = results.count() paginator = Paginator(results, 4) page = request.GET.get('page') try: results = paginator.page(page) except PageNotAnInteger: results = paginator.page(1) except EmtyPage: results = paginator.page(paginator.num_pages) return render(request, 'users/search.html', {'form': form, 'cd': cd, 'results': results, 'total_results': total_results, 'page': page, 'paginator': paginator}) return render(request, 'profiles/index.html', {'form': form}) The paginator and it's template is coded after the Django documentation. I have tried a couple of things, but I am not getting it to work. Does anyone know how I could fix that? Or should I get rid of the form completely? -
Django Site not showing Logo on Facebook, Linkedin
Can someone please help me in order to fix this simple issue? The site is working properly, but the logo not. What i am doing: i type the name of the site e.g www.foo.com and the head is taken ok with the title of the site etc, but the logo not. The same issue happen on Linkedin also, so what should i do? This is my head_css.html: {% load staticfiles %} <link href=" {% static 'css/fontawesome-free-5.0.2/web-fonts-with-css/css/fontawesome-all.min.css' %}" rel="stylesheet"> <link href=" {% static 'css/bootstrap.min.css' %}" rel="stylesheet"> <link href="{% static 'css/custom.css' %}" rel="stylesheet"> <link href=" {% static 'css/navbar-top.css' %}" rel="stylesheet"> <link rel="stylesheet" href="{% static 'favicon/favicon.ico' %}"> <link rel="apple-touch-icon" sizes="180x180" href="{% static 'favicon/apple-touch-icon.png' %}"> <link rel="icon" type="image/png" sizes="32x32" href="{% static 'favicon/favicon-32x32.png' %}"> <link rel="icon" type="image/png" sizes="16x16" href="{% static 'favicon/favicon-16x16.png' %}"> <link rel="manifest" href="{% static 'favicon/webmanifest' %}"> <meta name="msapplication-TileColor" content="#da532c"> <meta name="theme-color" content="#ffffff"> -
Django - Business Logic In Serializer?
I have a view that I use to take in a string, validate it, and send an email. Would I add an email method to the serializer, or just call Email(serializer.validated_data) in the view itself w/ a try block? -
Stripe Django: How to charge the existing customer with a plan
I am trying to charge the existing stripe customer with updated credit-card (Stripe token) and with a new subscription plan. Most of examples are to create a new customer and charge him a new plan but I want to change to the existing customer. new_customer = stripe.Customer.create( email=request.POST['stripeEmail'], plan = 'plan_DgV0NXZk7vlMMG', card=request.POST['stripeToken'] ) -
Scrape a PDF and upload it to S3 in Django
I am trying to scrape PDFs from a website and upload them to an S3 bucket. I have a working scraper that successfully downloads the file locally using beautifulsoup4, as well as a working script that uploads a file to S3 using Boto. What I am having an issue with is a way to skip the middle step of downloading it locally and just downloaded it directly to S3. Is there a good interface between scraping and uploading to S3? -
How to compare many to many fields in a Django model?
Given the following model example, how could I compare the two M2M fields when querying the model? class PaidModel(models.Model): users = models.ManyToManyField(UserProfile) paid_users = models.ManyToManyField(UserProfile) I am trying to find which 'PaidModel' instances have 'users' that do not match 'paid_users' (i.e. are assigned but not paid for). I tried F objects as follows: unpaid = PaidModel.objects.exclude(users=F('paid_users')) This returns a queryset but the two M2M fields didn't match as expected. I was trying to avoid iterating through and 'manually' finding the non-matching instances. Any help would be appreciated. -
Django language internationalisation - I cannot get translations to work
I'm trying to figure out how to get different languages, based on user selection, to show in Django. I don't know what I'm missing, so I wonder if someone can explain where I've gone wrong. This is my urls.py urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^i18n/', include('django.conf.urls.i18n')), ] urlpatterns += i18n_patterns( url(r'^', TemplateView.as_view(template_name="lang_test/index.html")) ) Within settings.py I've added: MIDDLEWARE = [ ... 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', ] from django.utils.translation import ugettext_lazy as _ LANGUAGES = ( ('en', _('English')), ('fr', _('French')), ('el', _('Greek')), ) LOCALE_PATHS = ( os.path.join(BASE_DIR, 'locale'), ) USE_I18N = True USE_L10N = True USE_TZ = True I've run manage.py makemessages -fr manage.py makemessages -el and having added messages I've run manage.py compilemessages I've then got this simple template which I was expecting to see the 3 different languages showing because I've set the language. {% load i18n %} <html> <head> </head> <body> {{ LANGUAGE_CODE|language_name }} <h1>{% trans "Welcome to my website" %}</h1> {% with 'fr' as LANGUAGE_CODE %} {{ LANGUAGE_CODE|language_name }} <!-- Current language: {{ LANGUAGE_CODE }} --> <h1>{% trans "Welcome to my website" %}</h1> {% endwith %} {% with 'el' as LANGUAGE_CODE %} {{ LANGUAGE_CODE|language_name }} <!-- Current language: {{ LANGUAGE_CODE }} --> <h1>{% trans "Welcome to my website" … -
Django REST Framework: Disable migration of all built in schemas, i.e., (auth. contenttypes. admin., etc.)
I would like to disable migrations for all built in schemas, i.e., auth., contenttypes. admin., etc. I'm not using any of these and they really slow down testing. Is it possible to easily disable migrations for these schemas? -
django approval workflows for some models
I have a business problem where a public site creates a wiki of sorts. This is similar to a problem I had back in 2001 when I created a job board. Users could sign up and then immediately post a job for free. The position was immediately visible on the site for searches, notification emails, and so forth. Well, that was okay for a while but then some spammers found the site and started posting work-from-home positions (just send us $25 for the info! ... and worse, far worse) faster than we could take them down. This resulted in a workflow that required a verification step that was not very convenient. I'm working on a Django site now where a user could sign up then start creating posts. However, I've learned my lesson - they can't just immediately be visible. What I'm looking for is an app or library that will allow a user to create a post and then leave that in Draft status until it can be reviewed and published (i.e., given permission to be public). That itself isn't too much of a problem; that's really just another field on the model. What I'm looking for is something … -
Access a subset of django form fields
How can one insert markup between subsets of form fields in django, while staying DRY? Given: class CompensationUpdate(UpdateView): model = Compensation fields = [ 'salary1', 'salary2', 'incentive1', 'incentive2', ] I'd like to be able to access them in the view in subsets, to wrap in markup, for example: <div class="ibox-content"> {% for field in form.salary_fields %} ... {% endfor %} </div> <div class="ibox-content"> {% for field in form.incentive_fields %} ... {% endfor %} </div> I have over 50 fields on the form, so I need to do this in a DRY manner. While I can access each field individually, I can't figure out how to define--and iterate over--subsets of the fields (either in the UpdateView or directly in the template. -
Installed apps necessary for bare-bones django user authentication
I am trying to add in a custom user model that allows for (1) creating a user; (2) checking their password; and (3) verify if someone is logged in or not with something like @login_required. What installed apps do I need for this? I tried using: INSTALLED_APPS = ( 'django.contrib.auth', ) But I kept getting setting errors until I had all of: INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', ) Are all three of these required just to have a User model that passes django auth? -
Trouble Connecting to PostgreSQL Running in a Ubuntu VM
I have created an instance of PostgreSQL running in a Ubuntu/Bionic box in Vagrant/VirtualBox that will be used by Django in my dev environment. I wanted to test my ability to connect to it with either the terminal or pgAdmin before connecting with DJango, just to be sure it was working on that end first; the idea being that I could make later Django debugging easier if I am assured the connection works; but, I've had no success. I have tried editing the configuration files that many posts suggest, with no effect. I can, however, ping the box via the ip assigned in the Vagrantfile with no issue - but not when specifying port 5432 with ping 10.1.1.1:5432. I can also use psql from within the box, so it's running. I have made sure to enable ufw on the vm, created a rule to allow port 5432 and insured that it took using sudo ufw status. I have also confirmed that I'm editing the correct files using the show command within psql. Here are the relevant configs as they currently are: Vagrantfile: Vagrant.configure("2") do |config| config.vm.hostname = "hg-site-db" config.vm.provider "virtualbox" do |v| v.memory = 2048 v.cpus = 1 end config.vm.box … -
Using Amazon Redshift for analytics for a Django app with Postgresql as the database
I have a working Django web application that currently uses Postgresql as the database. Moving forward I would like to perform some analytics on the data and also generate reports etc. I would like to make use of Amazon Redshift as the data warehouse for the above goals. In order to not affect the performance of the existing django web application, I was thinking of writing a NEW Django application that essentially would leverage a READ-ONLY replica of the Postgresql database and continuously write data from read-only replicas to the Amazon Redshift. My thinking is that perhaps the NEW Django application can be used to handle some/all of the Extract, Transform and Load functions My questions are as follows: 1. Does the Django ORM work well with Amazon Redshift? If yes, how does one handle the model schema translations? Any pointers in this regard would be greatly appreciated. 2. Is there any better alternative to achieve the goals listed above? Thanks in advance. -
Django: getting all records from multiple models
I have been stuck on this issue for a while now. Have tried itertools for proposed solutions but that doesn't really answer my needs. I should need to do the following: class QueryAllModels: modelA = modelA.objects.all() modelB = modelB.objects.all() modelC = modelC.objects.all() result = [modelA, modelB, modelC] queryset = result serializer_class = QueryAllModelsSerializer So in essence I could query all models independently but that seems like a very inefficient way to do so aka performing three individual requests. Have the independent queries but I need them for other routes within my API, but I'd like to be able to create a filter which would filter out records from another model based on the three models above. Ideally I'd set a route for these filters which just gives me either an array of models or an object of models containing all their records. That way the main model is filtered based on f.e. modelA value1 and modelC value5. Thanks in advance ! -
Specifying url namespace in Django
This error is quite unusual one. In project/urls.py I specified the namespace of the url path but anyway Django is showing the following error: 'Specifying a namespace in include() without providing an app_name ' django.core.exceptions.ImproperlyConfigured: Specifying a namespace in include() without providing an app_name is not supported. Set the app_name attribute in the included module, or pass a 2-tuple containing the list of patterns and app_name instead. But in my urls.py everything is OK I think. I am using django version 2.1. here is my urls.py: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('social/', include('social.apps.django_app.urls', namespace='social')), path('auth/', include('django.contrib.auth.urls', namespace='auth')), path('', include('sixerrapp.urls', namespace='sixerrapp')), ] -
Any disadvantage in removing a model's content type after removing the model in a Django application?
I understand from other answers around this topic, removal of a model via migrations do not automatically remove its remnants including the content type entries for the model unless you answer 'yes' to the prompts to do so or not use --noinput option. While it is understandable the Django is conservative and leaves that control to the developers, I want to know if there is any other benefit in leaving in the content type entries of removed models. I could only see disadvantages since there are a bunch of collateral content hanging around such as in auth.Permission. Over a period of time my apps may develop a content fat. Please note my question is only about the content type removal and what I might be missing out if I removed entries there. Aka, what is the thing that Django folks had in mind to decide to keep its content intact by default when a model is removed other than want to be conservative in general for cleanups.