Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
[Django]Import data into mysql from file
Let's explain my problem. I'm trying to import data from a file ( 3 columns) into my local mysql database. It contains 27442 rows. i use code below def import(file): base_dir= '/home/xxxxx/Desktop/' with open(os.path.join(base_dir, file), 'r') as f: for line in f.readlines(): line=line.split() #remove all useless space if len(line) >= 3: host.objects.create( hostaddress=line[0], hostname= line[1], comment=line[2] #' ' by default ) else: raise('Invalide format') Everything seem work properly but when i check the table after importation. i get less than the half of total row (11xxx). code for django model class host(models.Model): hostname= models.SlugField(max_length=50) hostaddress= models.GenericIPAddressField(primary_key=True) comment= models.CharField(max_length=100) i need a help. Sorry for my bad english. Thanks. -
Changing Default python path on macs?
I've been doing some research on this matter but could not find a proper solution. python by default is preinstalled on Mac OS. I'm currently trying to run python 3.6 and above, but when I am using Django and creating a new virtual environment, it is referencing python 2.7. I have downloaded the newest version of python, but that does not seem to overwrite python 2.7. I believe the issue has to do with the default path of python on Macs. How would I go and change that path so that when I create a virtual environment and when I use the Django framework, it will reference python 3.6 instead of python 2.7 ? -
Django tell if last item with certain attribute in dual ordering (order_by)
In a Django queryset how can I tell if the list item I'm on (when iterating) is the list item that has a certain attribute. Example: I order a queryset by: MyModel.objects.all().order_by('-featured', '-created_at') So, all objects which are featured first by their appropriate time and then all non-featured items sorted by time properly as well. When iterating in the template I want to be able to tell if I've hit the last "featured" item in the dual-ordering (such that featured = True). Example usage: If last item -> display banner separating featured / non-featured -> continue iterating displaying non-featured after banner. {% for object in object_list %} # display object {% if last item with attribute %} # display banner {% endif %} {% endfor %} I know I can do another queryset to get the count, but that's an extra query I'd like to avoid. -
Accessing variables from other methods in a django app
I am quite new to django and python, and I have an issue using methods and define them properly. I would like to store calculation in a method .. and call that method in another method here is how it looks : def get_info_array(self, format=None, *args, **kwargs): current_response_list = get_current_team(self) member_info_array = [] for response_dic in current_response_list: current_response = list(response_dic.values())[0] chunk_score = get_chunk_score3() print(chunk_score) return chunk_score def get_chunk_score3(self, format=None, *args, **kwargs): answer_question1 = current_response.answers.get(question_id = 2) answer_question2 = current_response.answers.get(question_id = 3) json_answer_question1 = json.loads(answer_question1.body) json_answer_question2 = json.loads(answer_question2.body) answer_key_question1 = list(json_answer_question1.keys())[0][0] answer_key_question2 = list(json_answer_question2.keys())[0][0] if answer_key_question1 == "1" or "3": score1 = list(json_answer_question1.values())[0] else: score1 = -list(json_answer_question1.values())[0] if answer_key_question2 == "1" or "3": score2 = list(json_answer_question2.values())[0] else: score2 = -list(json_answer_question2.values())[0] chunk_score = math.ceil((score1+score2)/2) return chunk_score when I try to run that code I get that in current_response in get_chunk_score3 is not define, how can I access variable from other methods ? Any tips is well welcome to progress. -
Django authentication between views
I'm having some trouble using the django authentication i have a view that uses the decorator @login_required. Once logged the user will procede to a page, fill some data and use a post request to access the next page, however when trying to go back to the previous page django will show the log in form again. Is there a way to prevent this? I was thinking on using a button to go back with a post with the session so django wont ask for login again but i'm not sure if that can be done. -
How to pass a query set to the context class in Django?
I am trying to pass a queryset object to django context class, but doing so results in the following error: TypeError('context must be a dict rather than %s.' % context.__class__.__name__) Now i understand that the context accepts only a dictionary but i am following an example from a book called django_unleashed which uses Django version 1.8 and i am using django 2.0. and i guess it was done like that in previous versions. So my question is how should i do this step correctly using django 2.0 from django.shortcuts import render from django.http import HttpResponse from .models import Tag from django.template import Context, loader def homepage(request): tag_list = Tag.objects.all() template = loader.get_template('organizer/tag_list.html') context = Context({'tag_list', tag_list}) output = template.render(context) return HttpResponse(output) -
Installing Django unsuccessful
I'm trying to install Django on my MacBook (which runs OS High Sierra v10.13.2). I used the following command on my terminal: pip install Django==2.0 and it gives the error Command "python setup.py egg_info" failed with error code 1 in /private/var/folders/fz/p01c6tns6b1cn4pnzd32305c0000gn/T/pip-build-1KdXpL/Django/ Does anyone know how to resolve this issue? -
Access to RStudio Server hosted on EC2 through Django App on S3
I have a R Shiny app running on a EC2 instance on AWS. The app can be accessed directly through its link. I also have a Django app hosted on S3, which is accessing the app as an iframe. What I want to do is limit the access of the Shiny App only through the Django app. Currently there is no limit on the EC2 instance security groups, and they listen ports 80 & 22. Any ideas how I can do this? -
User Model with a foreign key and primary key?
I have a custom User Model that is setup as class User(AbstractBaseUser, PermissionsMixin): field1 = models.CharField(max_length=11, unique = True, primary_key = True) field2 = models.CharField(max_length=5) USERNAME_FIELD = 'field1' class Meta: app_label = 'accounts' db_table = "user" I have several additional models that relate to the primary key field1, the relationship works great. My problem is adding an existing database table which primary key is field2 in my user model. class ModelWantingToRelateOnField2(models.Model): field2 = models.OneToOneField(settings.AUTH_USER_MODEL, db_column='field2',primary_key=True, serialize=False, max_length=5) class Meta: managed = False db_table = 'Table2' When I add the one to one my vizgraph data model shows it's trying to relate on field1, when I need the relationship to occur for field2 on this model and all my others relate on field1. I've tried using ForeignKey and also related_name, but after migration the model tries to relate on field1. -
request.FILES returns empty dictionary despite setting enctype="multipart/form-data"
I am trying to upload a csv file using Django but when I attempt to retrieve the file in my view, the request.FILES object is always an empty dictionary. I've followed various guides and ensured that the form is submitting a POST request and that the enctype="multipart/form-data" but I can't seem to figure out why it is always empty. My form code is here: <form action="{% url 'upload_lessons' %}" method="post" enctype="multipart/form-data" class="form-horizontal"> {% csrf_token %} <div class="form-group file-upload-form-input"> <div class="col-md-8"> <input type="file" name="csv_file" id="csv_file" required="True" class="form-control"> </div> </div> <div class="form-group file-upload-form-upload-button"> <div class="col-md-3 col-sm-3 col-xs-12 col-md-offset-3" style="margin-bottom:10px;"> <button class="btn btn-primary" type="submit" formmethod="post" formaction="{% url 'upload_lessons' %}"> <span class="glyphicon glyphicon-upload" style="margin-right:5px;"></span>Upload </button> </div> </div> </form> My view code is here: def upload_lessons(request): if "GET" == request.method: return redirect('get_scheduler') try: print(request.FILES) print(request.body) except Exception as e: print(e) return redirect('get_scheduler') I am only testing out the file uploading process and I will be adding additional logic after I am able to read the csv file. Not sure if this would be helpful, but when I print request.body, an example output is as follows: b'csrfmiddlewaretoken=iELCfd6yPd4NZaXVSQrtBkkufxmq9FlKRtSTC9m5j0x71M5IjshmdE1eLPSnevVj&csv_file=classwithseats.csv' -
Best practice to handle Django Rest Framework Users with 2 Modes
I've started working on a Django Rest Framework based project and there is a requirement to enable 2 'modes' for the same User. For example, there is one User model which upon registration is either a Teacher or a Student. There are multiple Models throughout the project which have a Foreignkey to this User object. (e.g. Chat, Class, Subjects etc). These other models are mostly agnostic to the User type. e.g. Chat There is now a requirement to allow a teacher to login as a student and vice versa. So the User would only register once but could choose to login as a Student or as a Teacher and they would see the appropriate data. They should not see the data from the other 'mode'. i.e. A User logged in as a Teacher would not see any of their Chats/Subjects/Classes etc from when they were logged in as a Student and vice versa. For all intensive purposes it would appear and behave as 2 separate User accounts with the exception that they would share Login credentials. I'm unsure of the best way to proceed here. What I'm thinking currently is to make 2 User profile models for these 2 different … -
Is any needs to create a simple login view when using djangorestframework-jwt obtain_jwt_token views?
Basically I want to developed a system where user logged in using username and password using 'JSONWebTokenAuthentication'.That's way I am use 'django rest framework JWT'.Before i was create an accounts app where user can registration and login using there username and password. In account/urls.py urlpatterns = [ url('^login/$', UserLoginApiView.as_view(), name='login'), url('^register/$', UserCreateApiView.as_view(), name='register'), ] In mainproject/urls.py urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^api/auth/token/', obtain_jwt_token), url(r'^api/users/', include("account.urls", namespace='user_api')), ] When i was open 'api/auth/token/' This URL. it shows username field and password field in the browserable api it's ok coz it is built in view djangorestframework-jwt.If username & password match in db that's provided a token. My question is when i use my own login view .If using 'djangorestframework-jwt' obtain_jwt_token views in api/auth/token/ Only registration is enough to create an user. Is any needs to create an extra login view if we use djangorestframework-jwt. -
How to consider a related field in unique key in Django?
I have a following django models: class Entity(models.Model): name = models.CharField(max_length=255) class EntityProp(models.Model): entity = models.ForeignKey('Entity') key = models.CharField(max_length=255) value = models.CharField(max_length=255, blank=True, default='') I want to make a unique key for Entity that includes name and related EntityProp. For example, I want two entities with the same name and different set of related EntityProp instances to be different. But I want to keep the same Entity if they have identical names and EntityProp instances. Is there an elegant way to do it in Django? As a reserve way I can create an additional field in Entity called props_hash that contains a hash of the identifiers of all related instances, but it wouldn't be easy to support such structure, I think. So I believe there's a better way. -
I have a query and I want to output a message
I'm working on Django and I'm returning the result of a query from oracle in a HTML page. Then, I want to print a message with some simple words and a value from the query for example "You have 5€ on your cart". The "5€" is the value from the query and it's name is "valor" from the table "cc" Any ideas of how to do this? -
how to make dango url ignore query string in urls.py
I'm working on a website where I can have the user choose from a list of similar elements on a list page and I want it to open a separate page based on the element they choose in the list I have a list setup and each element in the list is identifiable with a random string of 15 characters containing [0-9], [a-z] and [A-Z]. Example of an url for an element of the list: http://127.0.0.1:8000/view?s=fkiscl49gtisceg where s is the identifier (kinda like how youtube videos have a seperate link) however I can't understand how I need to make django ignore the ?s=fkiscl49gtisceg part of the string. I've written the path like this now: path('(?P<v>[\w]{15})', element_display, name='v'), django however tels me that the page was not found... How do I fix this? -
django whitenoise on heroku static files not available on local
I know there are TONS of posts about this, but I feel like I'm staring into a black hole as far as debugging. I have set up a new django project on heroku using the template. I have added an app and templates and static files, and when I run the app on the heroku server, evertyhing is fine. When I run using heroku local or python manage.py runserver the static files are just unfound (404). The default heroku django tempalte uses WhiteNoise for static files. I've never had trouble before running other projects locally, and I can't figure out what is different about my project now. I ran the collectstatic just for good measure although i don't think its required but i get nothing for static files locally. Again the static files work when run on the heroku server. Any ideas are greatly appreciated. here is the settings file: """ Django settings for nonfictionfilm project on Heroku. For more info, see: https://github.com/heroku/heroku-django-template For more information on this file, see https://docs.djangoproject.com/en/1.11/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.11/ref/settings/ """ import os import dj_database_url # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) … -
Bootstrap does not be set to Django app
Bootstrap does not be set to my Django app.In google console,Failed to load resource: the server responded with a status of 404 (Not Found) bootflat.min.css error happens.I wrote in settings.py BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) DEBUG =True STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, "static/") STATICFILES_DIRS = [os.path.join(BASE_DIR,'bootflat.github.io'), ] in PythonServer_nginx.conf server { # the port your site will be served on listen 8000; # the domain name it will serve for server_name MyServerIPAdress; # substitute your machine's IP address or FQDN charset utf-8; # max upload size client_max_body_size 75M; # adjust to taste location /static { alias /home/ubuntu/PythonServer/PythonServer/accounts/static; # your Django project's static files - amend as required } # Finally, send all non-media requests to the Django server. location / { uwsgi_pass django; include /home/ubuntu/PythonServer/uwsgi_params; # the uwsgi_params file you installed } } I do not know why Bootstrap does not be set to my Django app.I run command python manage.py collectstatic but no error happens.How should I fix this?What should I write it? -
Django Debug Toolbar Time Panel doesn't work
I have installed Django Debug Toolbar. all enter image description hereother panels work very well but the Time Panel. There is Time Panel showed there, but when I click there is no response. When I click all other panels, it can display the related information such as sql panel, version panel etc. How can get the Time Panel work, BTW, for my site, the SQL panel show only 3 to 4 seconds, but the Time panel show around 10 seconds, what is the diff, where is the 6 seconds? Thanks! -
django models DateTimeField(default=next 3-days)
models.py class TestModel(models.Model): event = models.DateTimeField(default=next 3-days) How to get default next 3 days? Is it possible? -
Django - get item with index in template [duplicate]
This question already has an answer here: How to access array elements in a Django template? 4 answers While redirecting to index.html, I pass the topics variable in the argument: def index(request): args={ 'user': request.user, 'topics': Topic.objects.all(), } return render(request, 'index/index.html', args) Now in the template, I want to get the second topic from the list. Tried doing like {{topics.get(1)}} or {{topics}}.get(1) What is the correct way to do it? -
Django Ajax POST empty Error 500
I am trying to let the user select x and y coordinates from an image using cropper.js and pass the data with using ajax to the next view. I am using Django 1.9.4. I am also not really practiced with Javascript, the Javascript part is not written by me. Using the Firefox Dev Tools Network Tab I seem to get a 500 Internal Server Error. In the Dev Tools view the request has the needed JSON data. However Django does not seem to work the request properly. Why? Relevant part from views.py: def render_stl(request): print("Got to STL render") if request.method == 'POST': print("BELOW DATA") print(request.POST) # <QueryDict: {}> print(request.is_ajax()) # False print(request.POST.__dict__) # {'_encoding': 'utf-8', '_mutable': False} urls.py: urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^render_img$', views.upload_file, name='render_img'), url(r'^render_stl$', views.render_stl, name='render_stl'), url(r'^download_stl$', views.download_stl, name='download_stl'), # url(r'^media/mySTL.stl', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}), ] Javascript (the csrftoken is defined in another function): sendDataOfCroppedImage = function(dataOfCroppedImage) { // var data = 'data : [' + JSON.stringify(dataOfCroppedImage) + ']'; var data_s = JSON.stringify(dataOfCroppedImage); console.log('data',data_s); console.log("I AM HERE M*****F***er"); $.ajax({ async: true, crossDomain: true, method: 'POST', data: data_s, dataType: 'json', headers: { 'HTTP_X_REQUESTED_WITH': 'XMLHttpRequest', 'content-type': 'application/json', 'cache-control': 'no-cache', 'X-CSRFToken': csrftoken }, url: 'render_stl', success: function () { console.log('sendDataOfCroppedImage … -
Django project behind uWSGI monitor device state
There is a webapp in Django, served by NGinx + uWSGI. It is required to monitor a streaming device (a serial tty) and record some events in the database. I want it to be part of the same distribution (tar.gz) and so that this monitor can reuse Django database settings as well as Django models to access the database. Options that I'm reviewing so far: In the Django app create an extra thread, and maybe have some mutex or something so that only one process listens to the device (uWSGI creates multiple processes). The option seems too hackish. Add a separate entry point that I daemonize and simply import the Django environment. (Or is there a way to create a web hook that could only be called localy? That way I'd avoid pulling in Django and would only process events on the web side.) What other options are there? Thank you for your help! -
How can I dynamically add a mixin to a view class in Django?
I have a custom Django mixin which should be imported/added to a view class only if some app is installed, e.g. class MyView(LoginRequiredMixin, CustomMixin, View): # ^ # this is an optional mixin pass How to achieve this in Django? -
Edit files trough sftp Django
First of all I'm new to Django. I have just installed Django using Digitalocean Ubuntu 16.04. So i started with writing my first Django app using this tutorial: https://docs.djangoproject.com/en/2.0/intro/tutorial01/ After editing some files I'm starting to realize that it is not very practical to use ssh for editing files. So i want to use SFTP. I saw in the documentation that their is a Django user with a password. But, because this is not to secure to use a password to login, I created a new user with sudo privileges and added a ssh-key to it. So when I logged-in as my new user using SFTP and editing a file I figured out that i cannot save files. I'm getting this error: Unable to save file: Permission denied So then I tried it with the Django user, same results: Unable to save file: Permission denied Then I tried it as root and successful. But I Don't want to change files through root but as my new user name. All the files are owned by Django user and the permissions of files and folders are 644 and 755. Anyone knows how to fix this? -
how can i pass three arguments in my djnago template tags filter?
i know how to pass two parameters in template tag filter in Django but bit confused how to confussed 3 parametrers. My template tags- @register.filter("status_of_booking") def status_of_booking(status,create_date,from_time): print create_date print status return 'hola' and i am passing three arguments like this and it is showing error:- {{ item.status|status_of_booking:item.classSession.date,item.id }} and the error it shows: status_of_booking requires 3 arguments, 2 provided