Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
django Return outside function
when I try to migrate my django site that give me a this error return render(request, 'compare.html', context) SyntaxError: 'return' outside function I cant find where the error line is views.py class compare(request): all_waterLevels = waterLevel.objects.all() context = {all_waterLevels: all_waterLevels} return render(request, 'compare.html', context) models.py class waterLevel(models.Model): height = models.FloatField(max_length=250) date = DateTimeField(max_length=250) def __float__(self): return self.waterLevel_height Please help me to figure out this issue. -
Post photo on Facebook page doesn't work
I can't post a photo on a facebook page with my facebook app (V 2.11). My app has the manage_pages e publish_pages permissions. I have a page token too. Post text works well. If I use a image url from my domain the post doesn't work if I use a image url from another domain (eg: tripadvisor) the post works. My domain has a SSL DigiCert SHA2 Secure Server CA. This is my code: def PostPhotoFB(photo, title, link, text , fb_access_token, fb_page_id, desc): facebook_data = {'url': photo, 'access_token': fb_access_token, 'caption': text, } facebook_request = "https://graph.facebook.com/" + fb_page_id + "/photos" response_facebook = requests.post(facebook_request, data=facebook_data) if response_facebook.status_code == 200: return json.loads(response_facebook.text)['id'] else: return "" with an image in my server I get 400 and "(#324) Missing or invalid image file","type":"OAuthException","code":324 I use Jpg or PNG image. I don't understand. Can you help me please? Thanks a lot -
filter object_list in django templete
I am new in Django and have some problem: I create a template with object_list table and run in each object with loop: but I also need to have filter by substring then when the user will filter the table will updates online. I attch part from my code .. only the relvant I debug the code and get the expected querset both in server print to log and in response ajax call but I still need to refresh point_list in some way or to determine the filters inside the templete and not in the server? Any help??? I create view for this filter get the ajax request with substring value def filters_points(request): point_list = Point.objects.all() try: req = request.GET.get("filterData") if req: point_list = Point.objects.filter(onsitePointName__icontains=req) except AttributeError: print("failed") #qs_json = serializers.serialize('json', point_list) #return HttpResponse(qs_json, content_type='application/json') return render_to_response('point/point_list_update.html', {'point_list': point_list}) in HTML templete: {% for point in point_list %} ... {{ point.mangoId }} {{ point.onsitePointName }} .... -
how to convert an InMemoryUploadedFile upload to cloudinary in Django=1.11 using cloudinary.uploader.upload()
I am trying to upload an image file to cloudinary which I have sent from my django template to a function in views.py The file is in request.FILES['image'] cloudinary.config( cloud_name="p*****", api_key="33************", api_secret="4***-S***_o*********" ) img_obj = request.FILES['image'] cloudinary_response = cloudinary.uploader.upload(img_obj) image_url = cloudinary_response['url'] Printing img_obj gives the name of the image (Like : "tree.jpg") cloudinary upload doc is as follows https://cloudinary.com/documentation/image_upload_api_reference#upload The type of img_obj is InMemoryUploadedFile. Now is there a way to convert it to base64 or somthing like that so I can upload. Or any other solution ?? -
'NoneType' object is not iterable (Python Django) [on hold]
This is what I'm trying in view, try: numbers = Data.objects.all().aggregate(Sum('number')) except: numbers = None But I'm getting this error, 'NoneType' object is not iterable How can I fix that ? -
unable to connect django and angular 2
I want to connect my angular 2 app to django but how can i connect because both have different servers. I also read about cors but didn't work. Please suggest me some simple way to connect both of them Thanks in Advance -
Collapsible list of app models on django admin page
The list of apps and models is getting long in Django project. Is it possible to make apps and models lists on Django Admin page collapsible ? I've seen some admin replacements, but I'm looking for a way to incorporate this in standard Admin.