Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
__init__() takes 1 positional argument but 2 were given
I have seen this error before and it was due to something quite unrelated, but I can't seem to get past this now try as I might. The whole error seems contradictory to me, but Python is probably somehow right in the end. So, in foo/foo.py I have a class and its constructor defined as below: class Foo: def __init__(self, bars): self.bars = bars In baz.py I have the following: from foo import foo test_bars = [ a list of things ] f = foo.Foo(test_bars) which leads me to __init__() takes 1 positional argument but 2 were given I tried turning the constructor into kwargs too, as below class Foo: def __init__(self, bars=None): self.bars = bars and then calling from foo import foo test_bars = [ a list of things ] f = foo.Foo(bars=test_bars) and this gives an error about unidentified kwarg. Other classes included in foo/foo.py seem to work normally. What is it I'm not seeing? -
Providing an SSH based AJAX terminal on Django app
I am working on a Django app with following features. online terminal to all users on my local network The terminal frame should open at the bottom view, as soon as they are logged in. There's a code editor in the top frame. Their exists a linux account on the server with the same credentials that they use to login. What I want: spawn a terminal instance ssh's to their remote account change directory to their home directory as directed by ssh-config file persist the terminal connection until they logout. Bear in mind, this is all local, so accounts are all localplace, accessible. I have created the top editor view, for now and it looks like this The terminal picture shown below is from CodingGround How do I add this sort of terminal here? How do sites like StudyTerminal do it? How can I implement this? I have looked at implementations of shellInaBox and GateOne but they occupy full screen space and are their own server. I don't want another server just to provide a terminal. Can anybody help me sort this out? Probably like a Jquery / AJAX terminal interface that takes the following parameters: new terminal{ ssh_location : … -
how to integrate recommender system(python file) to the django project.
This is the python script made by my friend .How to integrate this file in my django project which contains all list of movies taken from the movierulz data set.Where should I integrate this code. import numpy as np import pandas as pd # set some print options np.set_printoptions(precision=4) np.set_printoptions(threshold=5) np.set_printoptions(suppress=True) pd.set_option('precision', 3, 'notebook_repr_html', True, ) # init random gen np.random.seed(2) #users_file = "/media/sourabhkondapaka/Sourabh's/main_project/sandbox/ml-latest-small/ratings.csv" #movies_file = "/media/sourabhkondapaka/Sourabh's/main_project/sandbox/ml-latest-small/movies.csv" #users = pd.read_table(users_file,sep=',', header=None,names = ['user_id','movie_id','rating','timestamp']) #movies = pd.read_table(movies_file, sep=',') class popularity_based(): def __init__(self,users,movies): self.users = users self.movies = movies self.user_id = None self.mean_ratings = None self.movielens= None self.c = 0 def create(self): self.movielens = pd.merge(users,movies) self.movie_ratings = self.movielens.ix[:,1:3] self.mean_ratings = self.movie_ratings.groupby('movie_id',as_index = True)['rating'].mean().sort_values(ascending = False) self.mean_ratings = pd.DataFrame(self.mean_ratings).reset_index() self.mean_ratings['title'] = self.mean_ratings['movie_id'].map(self.movies.set_index('movie_id')['title']) def recommend(self, user_id,topu): #no arguement required here, just for the sake of uniformness across other recommender implementations self.user_id = user_id #From = self.c #self.c += topu #To = self.c print(type(self.mean_ratings.as_matrix(columns=None))) return self.mean_ratings.ix[:topu,'title'].as_matrix(columns = None) -
django showing a list users with data from another model
I have a django model, player, I have another model, class pictureList(models.Model): belongToPlayer = models.CharField(max_length=128) the iPlayer has a charField which is the same name belongToPlayer now I want to show a player list,I want to show 4 pictures for each player, How to do that? ps:I keep the pictureList as separate model because each picture has some field like tag,clicked_time which I want to keep away from player data. -
Where to find the default context processors in django 1.10?
When adding a context processor, you seem to need to add the default context processors as well, else you won't have for example the auth context processors. But in django 1.10, the documentation for the context processors doesn't contain the default list anymore, except on the pages for migrating from old TEMPLATE_CONTEXT_PROCESSORS to the new TEMPLATES setting. Where can i find a official list of context processors for default projects? Or is there some option to append just the own context processor, without touching the default list? -
Django retrieve data from another form
I am new to Django and would like to know how can I save the teacher's email when the teacher logs in with LoginFormView shown below. After the teacher logs in, he can create a class using CreateClassForm. I have problem trying to store ClassTeacherTeaches model into the database under CreateClassForm when the teacher creates a new class. How to I retrieve the teacher's email from LoginFormView and store the teacher's email and get the auto incremented class id (this is created once teacher creates a new class) into ClassTeacherTeaches model database? models.py class User(AbstractBaseUser): email = models.EmailField(max_length=100, primary_key=True) password = models.CharField(max_length=100, null=False) full_name = models.CharField(max_length=100, default="", null=False) USERNAME_FIELD = 'email' def get_full_name(self): return self.full_name def set_full_name(self, fname): self.full_name = fname def get_short_name(self): pass def get_full_name(self): pass class Class(models.Model): classid = models.AutoField(primary_key=True) class_name = models.CharField(max_length=100, null=False) class ClassTeacherTeaches(models.Model): class Meta: unique_together = (('classid', 'teacher_email'),) classid = models.ForeignKey(Class) teacher_email = models.ForeignKey(User) form.py class CreateClassForm(forms.Form): class_name = forms.CharField(widget=forms.widgets.TextInput(attrs={'placeholder': 'Module Code'}), label='') class Meta: model = Class fields = ['class_name'] def save(self, commit=True): data = self.cleaned_data module = Class(class_name=data['class_name']) if commit: module.save() return module class LoginFormView(FormView): form_class = LoginForm template_name = 'SqlLabApp/index.html' success_url = '/' def post(self, request, *args, **kwargs): login_form = self.form_class(request.POST) … -
How to get an object with django serializer the contains Foreignkeys WITHOUT execution of queries to every referenced object
I'm really new to Django, but one in our projects we have a Django backend, and no one else would like to touch it, so I have to make little tweaks on that. Models set up, everything work fine, but we need a new view, where we need basic data about one of our models, without referenced models (only the foreign key id is needed). I've got a solution from SO before, but while that solution returns the prefered result, still executes a tons of queries in the background. Every referenced object is queried for every returned object, meanwhile we need only their ids/keys. Models: class Row(models.Model): row = models.IntegerField(null=True, blank=True) height = models.TextField(null=True, blank=True) key = models.CharField(max_length=36, unique = True) def save(self, *args, **kwargs): super(Row, self).save(*args, **kwargs) class Column(models.Model): col = models.IntegerField(null=True, blank=True) width = models.TextField(null=True, blank=True) key = models.CharField(max_length=36, unique = True) def save(self, *args, **kwargs): super(Column, self).save(*args, **kwargs) class Product(models.Model): key = models.CharField(max_length=36, unique = True) text = models.TextField(null=True, blank=True) column = models.ForeignKey(Column, db_column='column_key', to_field='key', related_name="products") row = models.ForeignKey(Row, db_column='row_key', to_field='key', related_name="products") merged_with = models.ForeignKey("Product", db_column='merged_with_key', to_field='key', related_name="merges", blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) updated_by = models.ForeignKey('auth.User', null=True) Serializer: class SimpleProductSerializer(serializers.ModelSerializer): class Meta: model = … -
getting list from django views to googlecharts in templates
I am trying to get sensor data from postgresql database to googlecharts in django, but I am unable to get the charts though data shows when I write {{ sensor_data }} in template. Can anyone tell what I am doing wrong here, this is the template: <html> <head> <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script> <script type="text/javascript"> google.charts.load('current', {packages: ['corechart']}); google.charts.setOnLoadCallback(drawChart); function drawChart() { // Define the chart to be drawn. var data = new google.visualization.DataTable(); data.addColumn('datetime','Date/Time'); data.addColumn('number','Temperature'); {% for data in sensor_data %} data.addRow([new Date("{{ data.data_date }}"), {{ data.amb_temp }}]); {% endfor %} var chart = new google.visualization.LineChart(document.getElementById('myPieChart')); chart.draw(data, null); } </script> </head> <body> <div id="myPieChart" style="width: 900px; height: 500px;"></div> <a href="/polls/{{node.id }}/"></a> </body> </html> this is the view: # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.shortcuts import render from django.http import HttpResponse, HttpResponseForbidden from django.views.decorators.csrf import csrf_exempt from .models import * import json from django.core.serializers.json import DjangoJSONEncoder def date_handler(obj): if hasattr(obj, 'isoformat'): return obj.isoformat() else: return obj def history(request,node): if request.method == 'GET': try: crop=bitter_gourd_node_c.objects.filter(node_id=node).values_list('data_date','amb_temp') sensor_data = [] if crop: for i in range(0, len(crop)): sensor_data.append([crop[i]]) json_list = json.dumps(sensor_data, cls=DjangoJSONEncoder) return render(request,'history.html', {"sensor_data": reversed(json_list)}) except Nodes.DoesNotExist: return HttpResponseForbidden return HttpResponseForbidden and this is the model: class bitter_gourd_node_c(models.Model): node_id=models.ForeignKey(Nodes) record_no= … -
Double urls python change to single in i18n
I have problem with urls django i18n... Now this works like this: http://127.0.0.1:1234/en/en/dashboard/ I would like to see: http://127.0.0.1:1234/en/dashboard/ How can I delete double language in url ? Single "en" doesn't works.. When I go for http://127.0.0.1:1234/en/dashboard/ django redirect me to double /en/en in url. -
Serving Static Images from Application in Django
I am following a Django book which builds a web application. When I build a template, I get the same result as that of the book, except for my images - they are not there. I am wondering what can be causing this issue. The images have correct URL's but when I try to open them, Django states "Page NOT found 404". I am pasting the relevant code below. In addition, I include a screenshot of my directory tree. shop/models.py: class Product(models.Model): category = models.ForeignKey(Category, related_name='products') name = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=200, db_index=True) image = models.ImageField(upload_to='products/%Y/%m/%d', blank=True) description = models.TextField(blank=True) price = models.DecimalField(max_digits=10, decimal_places=2) stock = models.PositiveIntegerField() available = models.BooleanField(default=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) template: <a href="{{ product.get_absolute_url }}"> <img src=" {% if product.image %} {{ product.image.url }} {%else %} {% static 'img/no_image.png' %} {% endif %} "> </a> views.py def product_list(request, category_slug=None): category = None categories = Category.objects.all() products = Product.objects.filter(available=True) if category_slug: category = get_object_or_404(Category, slug=category_slug) products = products.filter(category=category) return render(request, 'shop/product/list.html', {'category': category, 'categories': categories, 'products': products}) -
how to read the following structure in django,python
( {'locker__city': u'Old Delhi', 'locker__state': u'Delhi', 'locker__locker_name': u'BI', 'day5': 50L, 'locker__pincode': u'110096'}, {'locker__city': u'Old Delhi', 'locker__state': u'Delhi', 'locker__locker_name': u'BI', 'day2': 50L, 'locker__pincode': u'110096'} ) I have the following data structure to read and access in python. I am really new to the language. Can anyone helpme out as to how could i print the value of "Locker__city" and other fields and print in django templates. -
coercing to Unicode: need string or buffer, NoneType found everything seems fine and still getting this error
this is my str and unicode... def __str__(self): return '%s' % self.id def __unicode__(self): return self.title or u'' and i have already tried this... def __str__(self): return self.id def __unicode__(self): return self.id still getting this error.. coercing to Unicode: need string or buffer, NoneType found not able to figure it out -
Django on Mac with mysql
I’m new in Django on Mac. I faced a problem in configuring Django environment with mysql on Mac. The error is “ django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: dlopen(/Users/david/david-env/lib/python2.7/site-packages/_mysql.so, 2): Symbol not found: _mysql_shutdown Referenced from: /Users/david/david-env/lib/python2.7/site-packages/_mysql.so Expected in: flat namespace in /Users/david/david-env/lib/python2.7/site-packages/_mysql.so ” I have referred serval related answers and methods from stackoverflow, such as pip uninstall MySQL-python brew uninstall mysql brew install mysql --universal pip install MySQL-python Unfortunately, it doesn’t work. I have built my virtualenv of python2.7.10 on Mac. I have used “pip install ” command to install serval packages including “Django-1.10.6”, “MySQL-python-1.2.5” and “mysqlclient”. I have installed “MySQL Server 5.7.17”, “MySQL Workbench” and “XCode”. Everything looks good , but the error can not be fixed. I also tried to use different versions of “MySQL-python” package, including “1.2.5” and “1.2.3” (I failed to install version 1.2.4). Failed either. I hope there is someone could help give a hand and lead me out of the trouble which destroyed my weekend. Thank you very much. -
Django rest framework : How to download image with image directly in the body
I need to return an Image directly in the body request, but i get in response a generated file with no extension and an empty array/json inside... I'm using python 3, Django==1.10.5 and djangorestframework==3.5.3 My models.py class Image(models.Model): class Meta: verbose_name = _('Image') verbose_name_plural = _('Images') creation_date = models.DateTimeField( help_text=_('Creation date'), auto_now_add=True, editable=False ) modified_date = models.DateTimeField( help_text=_('Last modification date'), auto_now=True ) image_file = models.ImageField(upload_to='', null=True) My serializers.py class ImageSerializer(serializers.ModelSerializer): class Meta: model = Image fields = ('image_file',) My views.py class ImageViewSet(NestedViewSetMixin, viewsets.ModelViewSet): http_method_names = ['get', 'put'] queryset = Image.objects.all() serializer_class = ImageSerializer pagination_class = None def get_queryset(self, *args, **kwargs): image = Image.objects.last() filename = image.image_file size = filename.size response = FileResponse(open(filename.path, 'rb'), content_type="image/png") response['Content-Length'] = size response['Content-Disposition'] = "attachment; filename=%s" % 'notification-icon.png' return response If someone find what I'm doing wrong, I will really appreciate. Thx a lot ;p -
django not upload image in admin
if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) MEDIA_ROOT = os.path.join(BASE_DIR, 'images') MEDIA_URL = '/images/' class Profile(models.Model): qrcode = models.ImageField(default = None, blank=True, null=True, upload_to="images/", name='qrcodea', verbose_name=u'qr_code_adr', help_text='148x148 in django admin save Profile and Saved OK but File unchoised. Why? -
Access standard javascript variable inside of react/webpack bundle
In my .html file I am passing in a variable from python.. <script> var api_context = {{ api_context | safe }}; </script> But i want to use it within my react bundle. So in my js bundle - - // main.js var React = require('react'); var ReactDOM = require('react-dom'); var axios = require('axios') console.log(api_context); The console logs 'undefined' What is the proper way of doing this? -
Django: trouble serving media files
I have been through the Django documentation multiple times and multiple stackoverflow questions but I can't get media serving to work at all . No errors but just errors when getting the files. Any help or extra sources to help me understand how to serve media files. Settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') MEDIA_ROOT=BASE_DIR + os.path.join(BASE_DIR, 'store/media/') MEDIA_URL='media/' I have a usual folder structure : /store { static, media, migrations,templates, etc } /venv /staticfiles manage.py Procfiles README requirements.txt runtime.txt My requirements.txt appdirs==1.4.3 Django==1.10.5 gunicorn==19.6.0 olefile==0.44 packaging==16.8 Pillow==4.0.0 psycopg2==2.7 pyparsing==2.2.0 six==1.10.0 virtualenv==15.1.0 whitenoise==3.3.0 Model with image field: class Product(models.Model): product_category = models.CharField(max_length=20) product_id = models.AutoField(primary_key=True) product_name = models.CharField(max_length=50) product_description = models.CharField(max_length=100) small_price = models.IntegerField() medium_price = models.IntegerField() large_price = models.IntegerField() rating = models.FloatField() image = models.ImageField( default='static/imgs/products/Cleanser.png') Template code calling media : {% for product in all_products %} <div class="item col-xl-4 col-lg-4" style="max-width: 400px;border-color:black;" > <div class="thumbnail" style="box-shadow: 1px 1px 10px grey;"> {% load staticfiles %} <img class="group list-group-image" style="height:200px;width:120px;" src="{{ product.image }}"> <div class="caption" style="text-align:Center;"> <p class="group inner list-group-item-heading" style="font-family:Raleway;font-size:23px;color:black;"> <strong>{{ product.product_name}}</strong></p> <p class="group inner list-group-item-text" style="font-family:Roboto,sans-serif;font-style:italic;color:#222;opacity: 0.5"> {{ product.product_description }}</p> <div class="row"> <div class="col-xs-12 "> <div class="form-group" > <label for="size">Sizes</label> <select class="form-control" class="size" style="max-width: 50%;margin:auto;"> {% if … -
How to get foreign key id instead of referenced model in Django serializers
I'm really new to Django, but one in our projects we have a Django backend, and no one else would like to touch it, so I have to make little tweaks on that. Models set up, everything work fine, but we need a new view, where we need basic data about one of our models, without referenced models (only the foreign key id is needed). I've spent a day with search for a solution. Maybe it's so trivial, it hasn't written anywhere :) Models: class Row(models.Model): row = models.IntegerField(null=True, blank=True) height = models.TextField(null=True, blank=True) key = models.CharField(max_length=36, unique = True) def save(self, *args, **kwargs): super(Row, self).save(*args, **kwargs) class Column(models.Model): col = models.IntegerField(null=True, blank=True) width = models.TextField(null=True, blank=True) key = models.CharField(max_length=36, unique = True) def save(self, *args, **kwargs): super(Column, self).save(*args, **kwargs) class Product(models.Model): key = models.CharField(max_length=36, unique = True) text = models.TextField(null=True, blank=True) column = models.ForeignKey(Column, db_column='column_key', to_field='key', related_name="products") row = models.ForeignKey(Row, db_column='row_key', to_field='key', related_name="products") merged_with = models.ForeignKey("Product", db_column='merged_with_key', to_field='key', related_name="merges", blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) updated_by = models.ForeignKey('auth.User', null=True) Now i need a list of products from a view, with the json output looks like: { id: 1, key: "1746495d-8ea0-42df-9ed9-06df621ef7c5", column_key: "<key of refrenced column>" merged_with_key: "<key … -
I am creating a social networking site using django, should I have create a email app
I am creating a social networking site using django, I will be sending lots of emails depending on the actions of the user. Should I create an email app or just create an email_funcitons.py file in each individual app. Which is best practice. Apps creted so far: Accounts NewsFeed Profile Notifications Messaging Privacy -
Displaying initial values in DJango CRUD application in a form
I have created an add/update form in Django Crud application. The Model for data is like this: class Proposal(models.Model): org = models.CharField(max_length=200) country = models.CharField(max_length=100) recdate = models.DateField(blank=True, null=True) subdate = models.DateField(blank=True, null=True) status = models.CharField(max_length=20) and in views.py I have following code for add and update: ADD def proposal_create(request, template_name='proposal/proposal_form.html'): form = ProposalForm(request.POST or None) if form.is_valid(): form.save() return redirect('list') return render(request, template_name, {'form':form}) UPDATE def proposal_update(request, pk, template_name='proposal/proposal_form.html'): server = get_object_or_404(Proposal, pk=pk) form = ProposalForm(request.POST or None, instance=server) if form.is_valid(): form.save() return redirect('list') return render(request, template_name, {'form':form}) AND finally I have in my template I have forms.py which is like this: <div align="center" style=" margin-top: 150; padding-top: 30; padding-bottom: 20; text-align: right; border-style: double; width: 50%; float: center; margin-left: auto; margin-right: auto; background-color: grey; color: black; border-color: white; border-width: 5px; box-shadow: 10px 10px 5px #888888;"> <form method="post">{% csrf_token %} <div align="center" style="margin-right: auto; margin-left: auto; align-content: center; width: 80%; vertical-align: middle;"> <table class="table table-bordered"> <tr> <td valign="middle" width="30%"><label for="{{ form.org.id_for_label }}">Organization:</label></td> <td valign="middle" width="70%"><input type="text" name="org" class="form-control" form="{form.org}"></td> </tr> <tr> <td valign="middle" width="30%"><label for="{{ form.country.id_for_label }}">Country:</label></td> <td valign="middle" width="70%"><input type="text" name="org" class="form-control" form="{form.country}"></td> </tr> <tr> <td valign="middle" width="30%"><label for="{{ form.recdate.id_for_label }}">Received Date:</label></td> <td valign="middle" width="70%"><input type="Date" name="org" class="form-control" … -
Mass Deploy same code to Heroku individual accounts
I want to set a business model where I Mass deploy same code base(Python Django with Postgres) to my customers heroku accounts . (I want customers to manage their own accounts and for me to stay only as software provider.However customers should get a SaaS experience without me actually having to take care of multitenant details.Also customers will be able to freeze at any time and get out of the upgrade process or to switch to custom code) So customer will purchase my software and setup the heroku account . I will get credentials from customer and add it to my deployment process and the code will be deployed each time to all the accounts for bugs fixes and for new versions. Do you think it is possible to achieve with Heroku? -
Show title only once inside django if statement
I have an car object in django view as follows: 'damages': [ { "location": "Voorbumper", "type": "Kras(10 cm, leger)", "severity": "Light damage", 'comment': "This is some comment.", "images": [ 'http://pathtophoto.jpg', 'http://pathtophoto.jpg' ] }, { "location": "Vleugel rechts voor", "type": "Deuk (Licht)", "severity": "", 'comment': "", "images": [ 'http://pathtophoto.jpg', 'http://pathtophoto.jpg', 'http://pathtophoto.jpg' ] }, { "location": "Deur links voor", "type": "Kras (5 cm, leger)", "severity": "", 'comment': "", "images": [ 'http://pathtophoto.jpg' ] }, { "location": "Waterlijst", "type": "Beschadigd", "severity": "", 'comment': "", "images": [] }, { "location": "Antenne", "type": "Ontbreekt", "severity": "", 'comment': "", "images": [ 'http://pathtophoto.jpg' ] }, { "location": "Antenne", "type": "Ontbreekt", "severity": "", 'comment': "", "images": [] } ] I want to loop through that object and show the images of the damages. But I want first to show the damages with images, and the the damages without images with appropriate title. In a django template I try to d it as follows: {% for damage in car.damages %} {% if damage.images|length > 0 %} <div class="width-100 pad text-left primary-bg">{% trans "Shades met foto's" %}</div> <div class="width-100 mar-top clear-float"> <div class="width-30 bord-my-way pad-half damage-info"> <div class="mar-btm-half"><b>{{ damage.location }}</b></div> <div class="mar-btm-half">{{ damage.type }}</div> <div class="mar-btm-half">{{ damage.severity }}</div> <div class="mar-btm-half">{{ damage.comment … -
Django: Error during template rendering
I am trying to build a feedback form but i am getting this error: Could not parse the remainder: '% csrf_token %' from '% csrf_token %' Here is my views.py: def contact(request): if request.method=='POST': form=ContactForm(request.POST) if form.is_valid(): topic=form.cleaned_data['topic'] message=form.cleaned_data['message'] sender=form.cleaned_data.get('sender') send_mail( 'Feedback from your site,topic:%s'%topic, message, sender, ['jpahultiwari@gmail.com'] ) return HttpResponseRedirect('/contact/thanks/') else: form=ContactForm() context={'form':form} return render(request,'blog/contact.html',context) Here is my template contact.html: <!DOCTYPE html> <html> <head> <title>Feedback Form</title> </head> <body> <h1>Contact Us</h1> <form action="." method="post" > {{% csrf_token %}} <table>{{form.as_table}}</table> <p><input type="submit" value="Submit"></p> </form> </body> </html> -
Set filters from user and get results after processing with the data of the objects (django form)
I would like to have your help in this part of my project: I am trying to get results based on the filters that a user puts in a form (is it html form or modelform?). Then, I make some actions to process with the input data of the user and display some results based on these filters. To be more specific, I have created several instances of the below model: class Task(models.Model): Taskdetails = models.CharField(max_length=500, null=True) asset = models.ForeignKey('Asset', null=True def __str__(self): return str(self.id) and class Asset(models.Model): Assetdescription= models.CharField(max_length=50, null=True) def __str__(self): return str(self.id) So in my DB, there are plenty of Tasks created. Each Task has a single Asset. The problems i face are: I want the user to choose an asset from a dropdown menu. This will happen in a simple html form? Can I do that with Modelform? These data will be sent to the view and processed. For example for the asset that the user has chosen, I would like to display the number of tasks in another template that belongs to this particular asset. To sum up, the way I imagine the process is: a. The user chooses one asset from a form. b. … -
Using php to write into django ORM
I use a php library where something similar does not exist for python / django. So I wrote a php script using the library and now I would like to use the resulting data in Django. I can think of two approaches to get the php data into Django: I could use php to write into the mysql database that I use for the Django ORM. I could write my php results into a local file and trigger Django by calling a view via http or via a management command to import the data. Is there a commonly accepted way of doing such things?