Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Show a logged in user their own information from a database model
I am relatively new to Django, and web development in general. Basically, I'm trying to build a website with two types of users: customers, and suppliers. Both the customers and suppliers have user accounts (containing a username, email, and password) created using Django's built-in 'from django.contrib.auth import login -forms.Form' and stored in the table 'auth_user' in my mySQL database. But, the suppliers can also create a more detailed profile (name, bio, images etc) which is created using a 'forms.ModelForm' called 'SupplierSignupForm' and stored in a separate table to 'auth_user', called 'home_suppliersignup'. What I want to happen is, when a supplier is logged in, they can click on their 'my profile' link in the header and be taken to their profile located in the 'home_suppliersignup' table in my database. Currently, I know how to call a logged in users ID from the table 'auth_user' using their session info, and then use that to link to their respective 'auth_user' profile: views.py user = request.user template <a href="{% url 'supplier_profile' id=user.id %}">My profile</a> urls.py url(r'^supplier-profile/(?P<id>[0-9]+)', supplier_profile, name="supplier_profile") But I don't know how to use this to pull up their information from another database table (i.e. home_suppliersignup). Any help would be much appreciated! -
From wsdl to services in python
I need to query a SOAP service wrote in Java from a webapplication developed with Django. To build a SOAP client I use the Zeep library but my problem is to understand which services expose the SOAP service, which parameter need to passe to the Zeep client. Is there a python library able to parse a wsdl file and build, as example, an sdk to query the SOAP services or any ideas? -
I am using the python django, and i wanted to know to get use thingsboard dashboard, and database as postgresql
I am using the Python3, Django and database as Postgresql, and I wanted to use the Thingsboard dashboard in my web application. can anyone pls guide me how can I use this -
Tensor Flow custom re-training model with new Images as they are uploaded
I have a Django web app hosted on Heroku and am pretty ok using pretrained model like inception and mobilenet to classify images with tensorflow. My question here is how do I use Tensrflow to retrain a model to learn about new images as they get uploaded on my Django app, so that when I search the app using image it can detect if similar image exist within the app. (Similar to Google search by images) -
Frames, maps, forms, textboxes all together with leaflet : HowTo
I al new to web development. I have not done this before. I have a requirnment to build a front end (client for a server) that looks like in the image below. I am using django to build the framework when the user clicks on the provided link [maps] below webframe work should be displayed in the browser [Forms] user should be able to able to upload data after filling the field and then load [text] response should be displayed eg : Success etc Currently : I have sucessfully tested the Forms and it is working as expected. I donot know how I can include all these three together Any suggestions are welcome -
How to set up session in vuejs django after successful login?
If login is successful i need to redirect to a login success page and I need to include a session in that.. How can it be possible. I am using html with vue js for front end and back end is django. This is my vue js script for login. <script> logBox = new Vue({ el: "#logBox", data: { email : '', password: '', response: { authentication : '', } }, methods: { handelSubmit: function(e) { var vm = this; data = {}; data['email'] = this.email; data['password'] = this.password; $.ajax({ url: '/login/', data: data, type: "POST", dataType: 'json', success: function(e) { if(e.status){ alert("Login Success"); // Redirect the user window.location.href = "/loginsuccess/"; } else { vm.response = e; alert("failed to login!"); } } }); return false; } }, }); </script> So, how can I include session in login successpage.. This is the first time I am doing a work.. Please help me .. -
Cannot update the user.last_login field
I am using Django 1.11 and User model from django.contrib.auth. Here's my code: from django.contrib.auth.models import User from django.utils import timezone u = User.objects.create_user('user1') print(u.last_login) # prints old date u.last_login = timezone.now() u.save() u.refresh_from_db() # just in case print(u.last_login) # prints old date Why does the last_login field not get updated? -
Django list of item did not appear
I created model, view and template for display list of items in template but after I run the website It didn't anything. Please help me to solve this. model.py class waterLevel(models.Model): height = models.CharField(max_length=250) date = DateTimeField(max_length=250) def __str__(self): # # return self.height + '-' + self.date view.py def compare(request): all_waterLevels = waterLevel.objects.all() context = {'all_waterLevels': all_waterLevels} return render(request, 'Home/compare.html', context) compare.html {% if all_waterLevels %} <ul> {% for height in all_waterLevels %} <li><a href="/Home/compare{{ waterLevel.id }}/"> {{ waterLevel.height }}</a></li> <li><a href="/Home/compare{{ waterLevel.id }}/"> {{ waterLevel.date }}</a></li> {% endfor %} </ul> {% else %} <h3>no any details</h3> {% endif %} -
Django getting value from a Jquery Post
Task: it is the implementation of checking on the fly at run time if a word has been taken I have used jquery in the past and never had problems with PHP but I m new to Django: This code is imported in a page called home.py and it will want to send the value picked from a textfield to a receiving page called checkkeyword.py. But before getting to that I wanted to see if the receiving page actually responded and the baffling thing is that what I get is the whole content of what is written in checkkeyword.py. That is, I enter a character in the text field, and yes, I get a reply right next to it, but the reply is the full content of whatever is written in checkkeyword.py. Why? $( document ).ready(function() { $('#keyword').keyup(function() { var keyword = $(this).val(); $('#keyword_status').text('searching ...'); if(keyword!= ''){ $.post('/static/js/checkkeyword.py', {param: keyword}, function (data){ $('#keyword_status').text(data); }); } }); }); If checkkeyword.py contains "hello", it will return hello. If it contains print("hello"), it will return print("hello") etc For testing purposes, I placed, as you can see, the checkkeyword.py inside the same directory where the jquery file is. I have seen some posts about … -
Django error Coercing to Unicode: need string or buffer
i m getting this error: >>> Child.objects.all() Traceback (most recent call last): File "<input>", line 1, in <module> Child.objects.all() u = six.text_type(self) TypeError: coercing to Unicode: need string or buffer, Main found Whenever i try to pull an object from Child. i tried to use the unicode but it still gives me this error. I also commented the **def str ** thought that was a problem. I don't know what i can do about it? Please help class Main(models.Model): website = models.CharField(db_column='Website', unique=True, max_length=250) main = models.CharField(db_column='Main', unique=True, max_length=100) tablename = models.CharField(db_column='TableName', unique=True, max_length=100) created_at = models.DateTimeField(db_column='Created_at') class Meta: managed = False db_table = 'Main' # def __str__(self): # return self.main def __unicode__(self): return unicode(self.main) class Child(models.Model): mainid = models.ForeignKey(Main, models.DO_NOTHING, db_column='MainID') day = models.IntegerField(db_column='Day') hour = models.TimeField(db_column='HOUR') created_at = models.DateTimeField(db_column='Created_at') class Meta: managed = False db_table = 'Child' # def __str__(self): # return self.mainid def __unicode__(self): return unicode(self.mainid) Thank you -
get_children not working. get_descendants does. But i can't use that
I am currently working on the navbar of a project with Django-cms. I am fairly new to this framework and language, so sorry if this is a stupid question. This has double dropdowns, which respond to user changes in the Django-cms admin interface. Which works. Sort of. The problem is that get_children doesn't work (no errors or something, just not detecting children, and showing the 'should be dropdown button' as a non dropdown version), but get_descendants does. But if i use that the content of the second dropdown will be shown again in the first dropdown. So children will be perfect, as it will only show the direct descendants, instead of all. {% load cms_tags menu_tags sekizai_tags staticfiles%} {% load menu_tags %} {% for child in children %} <!--non dropdown--> {% if child.is_leaf_node %} <li><a href="{{ child.get_absolute_url }}">{{child.get_menu_title }}</a></li> {% endif %} <!--dropdown 1--> {% if not child.is_leaf_node or child.ancestor %} <div class="dropdown"> <li><a href="{{ child.get_absolute_url }}" class="dropbtn">{{child.get_menu_title }}<b class="caret"></b></a></li> <!-- dropdown 1 content--> {% if child.get_descendants %} <div class="dropdown-content"> {% for kid in child.get_descendants %} <!--non dropdown--> {% if kid.is_leaf_node %} <li><a href="{{ child.get_absolute_url }}">{{child.get_menu_title }}</a></li> {% endif %} <!--dropdown 2 --> {% if not child.is_leaf_node or child.ancestor %} … -
How to override 400 view in django
I want to find a way for override django 400 error and extract message data. urls.py : from django.conf.urls import url from django.contrib import admin from listener.views home,customFunction handler400 = customFunction urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', home) ] listener/customFunction : def customFunction(request): print(request) return '00' -
Apidoc how to run correctly?
can't run apidoc base command, I know that I need to run like this apidoc -o ../frontend/static/apidoc/ all file exist and current place where I run command it's already correct, but I really don't know why it's everytime show me this base command lines of apidoc apidoc -o ../frontend/static/apidoc usage: apidoc [-h] [-c CONFIG] [-i DIRECTORY OR FILE [DIRECTORY OR FILE ...]] [-o FILE] [-v] [-n] [-a ARGUMENT [ARGUMENT ...]] [-y] [-w] [-q] [-qq] [-t] Base command-line interface for ApiDoc optional arguments: -h, --help show this help message and exit -c CONFIG, --config CONFIG configuration file -i DIRECTORY OR FILE [DIRECTORY OR FILE ...], --input DIRECTORY OR FILE [DIRECTORY OR FILE ...] directories and/or files containing documentation's source files -o FILE, --output FILE rendered output file -v, --version show program's version number and exit -n, --no-validate disable validation -a ARGUMENT [ARGUMENT ...], --arguments ARGUMENT [ARGUMENT ...] documentation's arguments arg1=value1 arg2=value2 -y, --dry-run analyse config's and source's files without building the documentation -w, --watch re-render the documentation each time a source's file or a template's file changes -q, --quiet does not display logging information below warning level -qq, --silence does not display any logging information -t, --traceback display traceback when an … -
How do I access the ATTRIBUTE of a Foreign Key Object in another Model?
class doctorMaster(models.Model): doctorID = models.AutoField(primary_key=True) doctorName = models.CharField(max_length=100,null=False) doctorDesignation = models.CharField(max_length=100,null=True) doctorSpecialization = models.CharField(max_length=100,null=True) UpdatedOn = models.DateTimeField(default=timezone.now, null=True) def __unicode__(self): return str(self.doctorID) class SMSlookup(models.Model): recordID = models.AutoField(primary_key=True) doctorID = models.OneToOneField(doctorMaster,on_delete=models.CASCADE,to_field='doctorID') doctorName = models.CharField(max_length=100,null=False) SMSContact = models.IntegerField (null = False) UpdatedOn = models.DateTimeField(default=timezone.now, null=True) def __unicode__(self): return str(self.doctorID) I need to be able to access doctorID of the first model using its namesake in the second. -
Django cut strings
Django: How can one cut the beginning of a string and keep the remainder ? I couldn´t find a method reference for strings in Django, and the name|cut: function doesn´t work. -
How to join two tables across dbs using django ORM?
I want to perform the equivalent SQL query using django's ORM: USE TRADING_DB; SELECT NAME, BUY_UNITS, BUY_NAV, SELL_UNITS, SELL_NAV,PANDL FROM MUTUAL_FUND_POSITIONS INNER JOIN MUTUAL_FUND_DB.MF_NAV_DATA AS NAV ON NAV.ISIN = MUTUAL_FUND_POSITIONS.MF_ISIN WHERE STATUS='OPEN' AND CLIENT_ID="Z712A"; Let's assume I have the following models: class MutualFundPositions(models.Model): pos_id = models.AutoField(db_column='POS_ID', primary_key=True) client_id = models.CharField(db_column='CLIENT_ID', max_length=45) mf_isin = models.CharField(db_column='MF_ISIN', max_length=100) buy_units = models.DecimalField(db_column='BUY_UNITS', max_digits=10, decimal_places=5) buy_nav = models.DecimalField(db_column='BUY_NAV', max_digits=10, decimal_places=5) sell_units = models.DecimalField(db_column='SELL_UNITS', max_digits=10, decimal_places=5) sell_nav = models.DecimalField(db_column='SELL_NAV', max_digits=10, decimal_places=5) status = models.CharField(db_column='STATUS', max_length=45) product = models.CharField(db_column='PRODUCT', max_length=45, blank=True, null=True) pandl = models.DecimalField(db_column='PANDL', max_digits=10, decimal_places=2, blank=True, null=True) class Meta: managed = False db_table = 'MUTUAL_FUND_POSITIONS' class MfNavData(models.Model): scheme_code = models.IntegerField(db_column='SCHEME_CODE') isin = models.CharField(db_column='ISIN', primary_key=True, max_length=45) name = models.CharField(db_column='NAME', max_length=500) class Meta: managed = False db_table = 'MF_NAV_DATA' unique_together = (('isin', 'name'),) How would I do that with Django's ORM? The idea is that I want a single query, using Django's ORM. MutualFundPositions table is on TRADING_DB and MFNAVDATA is on MUTUAL_FUND_DB. -
How to couple django oauth2 with javascript (reactjs) frontend correctly?
I've got a big problem to correctly implement (couple) oauth2 within Django project with Javascript (reactjs) frontend. As a backend we are using Django server - this server offers some APIs to store or retrieve data from SQL database. I am following this guide: Django OAuth Toolkit Documentation and using password based grant type (there are three others at disposal). What is working for me is that I can access server's API calls via command line using curl. That is, I know how to acquire token using URL like example.com/o/token and then I can call some of my APIs with granted token within header as "Authorization: Bearer acquired_token". I am new to OAuth within little knowledge on this topic so far. For information: all the stuff is running within Docker container. Reactjs is build using webpack. Within first request (clean browser cache - no javascript/reactjs available) django server is contacted and it servers index.html page with all the javascript stuff. Then Reactjs is present in browser and runs the Reactjs frontend which makes calls to APIs to get data from database and show them within some tables, etc. My problem and question is what needs to be done on frontend … -
How to limit values of IntergerField with Django?
i wonder if it's possible to limit values of an IntegerField with Django. My code in forms.py : class RatingForm(forms.Form): rate = forms.IntegerField(label='Noter') -
Django rest framework search filter for foreign key
So i tried using the search filter for my api because i want to get the data from a specific user using userId (which is a foreign key) If i use (url/id) , it will give me the table id data instead of the userId from foreign key. So i use the search filter (http://www.django-rest-framework.org/api-guide/filtering/#searchfilter) However i keep getting error "Cannot resolve keyword 'MyUser' into field. Choices are: BMI, bloodType, circumference, height, id, immunisation, timeStamp, userId, userId_id, weight" In views.py class HealthViewSet(viewsets.ModelViewSet): permission_classes = [AllowAny] queryset = Health.objects.all() serializer_class = HealthSerializer filter_backends = (filters.SearchFilter,) search_fields = ('MyUser__userId', ) and this "Related Field got invalid lookup: icontains" In views.py class HealthViewSet(viewsets.ModelViewSet): permission_classes = [AllowAny] queryset = Health.objects.all() serializer_class = HealthSerializer filter_backends = (filters.SearchFilter,) search_fields = ('userId', ) My models.py class MyUser(AbstractUser): userId = models.AutoField(primary_key=True) gender = models.CharField(max_length=6, blank=True, null=True) nric = models.CharField(max_length=9, blank=True, null=True) birthday = models.DateField(blank=True, null=True) birthTime = models.TimeField(blank=True, null=True) ethnicGroup = models.CharField(max_length=30, blank=True, null=True) mobileNo = models.CharField(max_length=14, blank=True, null=True) favoriteClinic = models.CharField(max_length=50, blank=True, null=True) objects = CustomUserManager() serializer.py class HealthSerializer(serializers.ModelSerializer): class Meta: model = Health fields = ('id', 'userId', 'immunisation', 'height', 'weight', 'BMI', 'circumference', 'timeStamp', 'bloodType') -
wagtail pages vs using django views and urls
When and where should I use wagtail pages and when should I write my custom urls and views using django? for example should I create pages for user profiles or should I add a urlpattern for profile and write profile logic in a django view? -
how to integrate a django project to a cloud storage like google drive , onedrive etc
I have a running Django application running on webfaction server. I want to integrate my django project with a cloud storage system. How can I Integrate that ? Here is the detail about my app: It is an erp software in django. It has a app named Projects. In that app, it has a model name Project. class Project(BaseModel): event = models.ForeignKey("events.Event") client = models.ForeignKey("clients.Client") project_supervisor = models.ForeignKey("staffs.Staff",blank=True,null=True) name = models.CharField(max_length=128) project_number = models.CharField(max_length=128,unique=True) currency = models.ForeignKey("projects.Currency") hall_number = models.CharField(max_length=128) stand_number = models.CharField(max_length=128) start_date = models.DateField() end_date = models.DateField() notes = models.TextField(blank=True,null=True) terms_and_conditions = models.TextField(blank=True,null=True) is_design_required = models.BooleanField(choices=BOOL_CHOICES,default=False) status = models.CharField(max_length=128,choices=PROJECT_STATUS,default="pending") admin_confirmed = models.BooleanField(default=False) is_quote_send = models.BooleanField(default=False) is_estimate_send = models.BooleanField(default=False) is_deleted = models.BooleanField(default=False) I want add an extra field to this model to store the project details.And I want to upload these pictures in the cloud, say dropbox or google , and want to upload it through django.That means I want to store that document field only in a cloud database? Is that possible in DJANGO? -
Substitute for Django session
I'm saving great amount of data in Django session and it takes from few seconds to minutes to retrieve it. For example, I save a Json list of 100 milion models and when I need to use this list, I retrieve it very frequently which causes awful performances. My question is: is there a substitute for Django session? I know about the cache but the data is too big for that. i also changed my session to be django.contrib.sessions.backends.cache but it's not good enough. -
How to filter a query by an instance in django rest framework?
I want to filter all comment objects using the property instance that name is "example". Basically I want to get all comments, which item name is "example". How can I do this filtering? class Comment(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE) owner = models.ForeignKey(Account, on_delete=models.CASCADE) message_body = models.TextField() is_read = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) class Item(models.Model): category = models.ForeignKey(ItemCategory, on_delete=models.PROTECT) owner = models.ForeignKey(Account, on_delete=models.PROTECT) name = models.CharField(max_length=150) description = models.CharField(max_length=1000) address = models.CharField(max_length=150, null=True) Thank you for your help! -
Django REST zip file download return empty zip
I'm writing a script to download a zip file. I read a lot around on how to do this, but i still got some troubles. As you can see in the code, I first create a tempfile, write data on it, then zip it and download. The problem is the result: a zip archive with an empty file inside. This is the code: f = tempfile.NamedTemporaryFile() f.write(html.encode('utf-8')) print(f.read) #the "writing of tmp file" seem to work, the expected output is right fzip = ZipFile("test.zip","w") fzip.write(f.name,'exercise.html') #this file remains empty response = HttpResponse(fzip, content_type="application/zip") response['Content-Disposition'] = 'attachment; "filename=test.zip"' return response I already tried to set NamedTemporaryFile(delete=False) or to seek(0) and stuff like that. I think the problem is the fzip.write, but actually I can't figure other solutions, can anyone help? thanks :) -
Django default value not being assigned! django 1.11 python 3.6
I am stuck finding the solution to this issue. I have a model named 'Album' where certain fields need to be assigned default values if not specified manually. After all the research, it feels like all my code is correct, yet default values are not being assigned. Also, this is my first time posting a question on stackoverflow so please bear with my newbieness. Here are all the codes: models.py file: class Album(models.Model): artist = models.CharField(max_length = 250, blank = True, null = True, default = "some_default_artist_name") album_title = models.CharField(max_length = 500, default='some_default_album_name', blank = True, null = True) genre = models.CharField(max_length = 100) album_logo = models.FileField() date_field = models.DateField() dt_field = models.DateField(blank = True, null = True, default=date.today().strftime('%d/%m/%Y')) forms.py file: class AlbumForm(forms.ModelForm): artist = forms.CharField(required = False) album_title = forms.CharField(required = False) genre = forms.CharField() album_logo = forms.FileField() date_field = forms.DateField(widget = forms.DateInput(attrs={'placeholder': 'dd/mm/yyyy'}, format='%d/%m/%Y')) dt_field = forms.DateField(required = False, widget = forms.DateInput(attrs={'placeholder': 'dd/mm/yyyy'}, format='%d/%m/%Y')) class Meta: model = Album fields = '__all__' It is expected that default values be assigned to 'artist', 'album_title' and 'dt_field' when those fields are left blank in the form. None of the fields are being assigned default values and are remaining null unless …