Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to setup an ubuntu server at home to host django website?
I've developed web apps with django for two years. But I have no experience with servers. Now I need to setup an Ubuntu server at home to host my django website and attach my web domain to the server. I'm using python 3.6 and django 1.11 with pipenv. my database is postgres. Can any one show me the installation and configuration process step by step? -
Image upload. Convert ImageFieldFIle to string or buffer
I made my storage to upload files to BackBlaze, I am overriding save method, one of its parameters is content, when I pass images, content's data type is ImageFieldFile. What is the best approach to convert ImageFieldFile into string or buffer? I tried create a instance of StringIO and write there content and after that getting value, but it didn't work _content = content.file.file #getting _io.BytesIO buffer = StringIO.StringIO() buffer.write(_content) file_data = buffer.getvalue() -
Run a Django QuerySet when user authenticated
I am looking for a solution to the following problem: I have a main function which contains many kind of QuerySets and python codes. In this function there are many query which has to be run only when user authenticated. I know that when I use @login_required before the function I can authenticate the users but how can I use the authentication inside the function? My example code: def auth(request): username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return render(request, 'project/index.html') else: login(request, user) def dashboard_data(request): qs1 = MyModel.objects.all() qs2 = MyModel.objects.all() qs3 = MyModel.objects.all() #Lets say I want to run the the following queries when user logged in qs_logged1 = MyModel.objects.all() qs_logged2 = MyModel.objects.all() send_data = { 'qs1': qs1, 'qs2': qs2, 'qs3': qs3, 'qs_logged1':qs_logged1, 'qs_logged2':qs_logged2 } return render(request, 'project/index.html', send_data) How could I run the queries abobe only when user logged? -
how to fetch multiple columns from join table Django model Serializer
this is my model code class questions(models.Model): q_name = models.CharField(max_length=100) q_active = models.IntegerField q_createdby = models.CharField(max_length=100) q_created = models.DateTimeField(auto_now=True) def __str__(self): return self.q_name class choice(models.Model): c_name = models.CharField(max_length=100) c_question = models.ForeignKey(questions, related_name='choice', on_delete=models.CASCADE) def __str__(self): return self.c_name my serializer is class choiceserializer(serializers.ModelSerializer): c_question = serializers.SlugRelatedField(read_only=True, slug_field='q_name') class Meta: model = choice fields = ('id','c_name','c_question') this is my view class chl(APIView): def get(self, request): clist = choice.objects.all() data = choiceserializer(clist, many = True).data return Response(data) my output for the serializer is { "id": 1, "c_name": "name", "c_question": "what is your name?" }, i want to fetch few more columns with the serializer. i want to fetch q_active, q_created column with it. is there any serializer relation i can use with? i need this final json response { "id": "c_name": "c_question": "q_active": "q_created ": }, -
Prefetch Related not working as expected
I'm developing an API with Django 1.11.11 and python 3.6.4. I have the following model: class Subsection(models.Model): genres = models.ManyToManyField(Genre, blank=True, default=None) tags = models.ManyToManyField(Tag, blank=True, default=None) And I'm doing the following query: subsection = Subsection.objects.filter(**q_objects).prefetch_related('genres', 'tags').first() So, then I can do: genres = subsection.genres.filter(is_active=True).values_list("id", flat=True) tags = subsection.tags.filter(is_active=True).values_list("id", flat=True) However, this is doing new calls even the prefetch_related, what am I doing wrong? Thanks in advance -
Django: Passing data to views from pre_save
I have the following issue: I want to pass data from my model pre_save function to my views.py The reason is that in my pre_save function, there is a unique order_id generated. This unique order id must also be saved in a session id (request.session['order_id'] = unique_order_id). Models don't accept a request, so I am trying to save it in my views.py, but how do I get the generated unique order id there? Appreciate your help! views.py def another_view(request): if request.POST: # Generate unique order_id x = Order().save() request.session['order_id'] = x # This is how I hoped it to solve, but x is not passing any data, even when adding a return variable in pre_save models.py # Imports (removed) # Create your models here. class Order(models.Model): order_id = models.CharField(max_length=10, unique=True) updated = models.DateTimeField(auto_now=True) timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.order_id) def order_pre_save_receiver(sender, instance, *args, **kwargs): instance.order_id = unique_id_generator(instance) # Here the unique order id is generated. Additionally I want to save this id as a session. pre_save.connect(order_pre_save_receiver, sender=Order) -
Can same instance of Redis be used as Cache and Session for Dhjango and Mesage Broker for Celery
I want to use Redis for django cache as well as session. I also plan to use celery. Can the same Redis server running on Ubutu server be used for all 3 or is there a catch. -
I wanna update model's data
I wanna update model's data.I am using Django Rest Framework.I am making a system saved user data to model.I wrote in views.py class InfoViews(viewsets.ModelViewSet): queryset = Info.objects.all() serializer_class = InfoSerializer lookup_field = 'id' def update(self,request, *args, **kwargs): data = request.data info_serializers = InfoSerializer(data = data) if info_serializers.is_valid(raise_exception=True): info_serializers.save() return JsonResponse(info_serializers.data) in serializers.py class InfoSerializer(serializers.ModelSerializer): created_time = serializers.DateTimeField(required=False) class Meta: model = Info fields = '__all__' in models.py class Info(models.Model): username = custom_fields.NotEmptyCharField(max_length=100, unique=True) email = models.EmailField() password = custom_fields.NotEmptyCharField(max_length=100) class Meta: db_table = 'info' When I run this codes,always when i update a record,new record is made.Is it cause save() of info_serializers.save()? What is wrong in my codes?How should I fix this? -
display model's function in template
Good day, I am trying to integrate a data function to an existing system, I am basically new to Django right now I am a bit confused with these two functions. The existing code in models.py @property def some_func(self): return self.get_other_func_same_model_class() the function that I want to add def some_func2(self): return self.get_other_func_same_model_class() I am playing around with it right now to see how both functions behave, so I decided them to return the same function. Problem is, I can call the first function in to the template but I am unable to do so on the second func. Is there anything that I missed? Suggestions will be highly appreciated. Thanks, -
django 2 jquery autocomplete
I'm having touble getting my autocomplete box to show results. I'm not sure if I'm not importing something from django that I need to. Any help is greatly appreciated. Thanks! views.py def contact_name_search(request): if request.is_ajax(): q = request.GET.get('term','') names = PhoneBook.objects.filter(first_name__istartswith=q) result = [] for n in names: name_json = n.full_name result.append(name_json) data = json.dumps(result) mimetype = 'application/json' return HttpResponse(data, mimetype) urls.py path('contact-name-search/', views.contact_name_search, name='contact-name-search'), main.html <div> <input type="text" id="contact_name_search_input" name="contact_name_search" /> </div> <script> $(function() { $("#contact_name_search_input").autocomplete({ source: "{% url 'contact-name-search' %}", minLength: 1, delay: 200, }); }); </script> -
I want to write a logic in views.py and save data in serializer
I am making a system saved user data to model.I want to write a part of logic in views.py and a part of save data in serializer.I want to make a system password is changed into hash.Now I wrote codes in views.py, class InfoViews(viewsets.ModelViewSet): queryset = Info.objects.all() serializer_class = InfoSerializer lookup_field = 'id' def create(self,request, *args, **kwargs): user = Info() passwd = request.data['password'] md5 = hashlib.md5() md5.update(passwd.encode('utf-8')) user.password = md5.hexdigest() user.save() return JsonResponse({"data":"data"}) in serializer.py class InfoSerializer(serializers.ModelSerializer): created_time = serializers.DateTimeField(required=False) class Meta: model = Info fields = '__all__' def create(self, validated_data): user = Info( email=validated_data['email'], username=validated_data['username'], ) user.set_password(validated_data['password']) user.save() return user in models.py class Info(models.Model): username = custom_fields.NotEmptyCharField(max_length=100, unique=True) email = models.EmailField() password = custom_fields.NotEmptyCharField(max_length=100) class Meta: db_table = 'info' def __str__(self): return '%s: %s' % (self.username, self.email) Now whenI tried to save user data to model,django.core.exceptions.ValidationError: ['Can not be empty!'] error happens.What is wrong in my codes?I searched http://www.django-rest-framework.org/api-guide/serializers/ .How should I fix this? -
Why M I getting a 404 in my django project?
So I have a page which I want to render after the details section in my project. My urls.py is below: url(r'incubators/(?P<incubator_id>[0-9]+)/', views.details, name = 'details'), # shows details of incubators url(r'^incubators/(?P<incubator_id>[0-9]+)/locate/', views.locate, name = 'locate'), #shows the latt and longitude of particular incubator I want to open a page (present in the details.html) which will be showing some info (in my case latitude and longitude) of that particular element. Following is my views.py def details(request, incubator_id): inc = get_object_or_404(Incubators, pk = incubator_id) details = Details.objects.get(pk = incubator_id) return render(request, 'main/details.html', {'inc': inc, 'details': details}) def locate(request): locate = get_object_or_404(Incubators, pk = incubator_id) return render(request, 'main/locate.html', {'locate': locate}) But I am getting the following error: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000//locate/ Using the URLconf defined in Ekyam.urls, Django tried these URL patterns, in this order: I think I am doing some mistake in making urls for this. Help would be appriciated. -
How to convert html template (with images) to pdf?
I have been struggling with this for a few days now. I am trying to convert an html template in django to a pdf. I have got this part down using both reportlab and xhtml2pdf in seperate instances, but have not been able to get the images to convert with either option. With xhtml2pdf I keep getting the error 'Warning: needs a valid file name! the file name being a url such as /home/products/2312312 Please if you know how I can achieve this I would GREATLY appreciate your help!! -
How can I upload and download files with graphene-django?
I'm currently using graphene-django v2.0 and I've absolutely no clue of how can I upload and download files like images, does anyone have an example of a query where you can download an Image and a mutation where you can upload one? -
Django TemplateDoesNotExist at /courses/course_list.html
i am get this warning while running the code below: here is the image outputenter image description here while in browser its showing 1.11.1 this is my pycharm project interpreter setting enter image description here its creating bit confusing i am running 2.03 or 1.11.1 course_list.py {% for course in courses %} <h2>{{course.title}}</h2> {{course.description}} {% endfor %} courses\urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.course_list ), admin.py from django.contrib import admin from .models import Course admin.site.register(Course) view.py from django.http import HttpResponse from django.shortcuts import render from .models import Course def course_list(request): courses = Course.objects.all() return render(request, 'courses/course_list.html', {'courses': courses}) trackback Traceback Switch to copy-and-paste view C:\Users\parad\tiger\heil\lib\site-packages\django\core\handlers\exception.py in inner response = get_response(request) ... ▶ Local vars C:\Users\parad\tiger\heil\lib\site-packages\django\core\handlers\base.py in _get_response response = self.process_exception_by_middleware(e, request) ... ▶ Local vars C:\Users\parad\tiger\heil\lib\site-packages\django\core\handlers\base.py in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ... ▶ Local vars C:\Users\parad\tiger\heil\learning_site\courses\views.py in course_list {'courses': courses}) ... ▶ Local vars C:\Users\parad\tiger\heil\lib\site-packages\django\shortcuts.py in render content = loader.render_to_string(template_name, context, request, using=using) ... ▶ Local vars C:\Users\parad\tiger\heil\lib\site-packages\django\template\loader.py in render_to_string template = get_template(template_name, using=using) ... ▶ Local vars C:\Users\parad\tiger\heil\lib\site-packages\django\template\loader.py in get_template raise TemplateDoesNotExist(template_name, chain=chain) -
django.core.exceptions.ValidationError: ['Can not be empty!']
I got an error,django.core.exceptions.ValidationError: ['Can not be empty!'].I wrote codes, user = Data() passwd = request.data['password'] md5 = hashlib.md5() md5.update(passwd.encode('utf-8')) user.password = md5.hexdigest() print(user.password) user.save() Traceback says Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 35, in inner response = get_response(request) File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py", line 128, in _get_response response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/usr/local/lib/python3.6/site-packages/rest_framework/viewsets.py", line 95, in view return self.dispatch(request, *args, **kwargs) File "/usr/local/lib/python3.6/site-packages/rest_framework/views.py", line 494, in dispatch response = self.handle_exception(exc) File "/usr/local/lib/python3.6/site-packages/rest_framework/views.py", line 454, in handle_exception self.raise_uncaught_exception(exc) File "/usr/local/lib/python3.6/site-packages/rest_framework/views.py", line 491, in dispatch response = handler(request, *args, **kwargs) File "/opt/project/ff_ssg_app/views/user_info_views.py", line 32, in create user.save() File "/usr/local/lib/python3.6/site-packages/django/db/models/base.py", line 729, in save force_update=force_update, update_fields=update_fields) File "/usr/local/lib/python3.6/site-packages/django/db/models/base.py", line 759, in save_base updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) File "/usr/local/lib/python3.6/site-packages/django/db/models/base.py", line 842, in _save_table result = self._do_insert(cls._base_manager, using, fields, update_pk, raw) File "/usr/local/lib/python3.6/site-packages/django/db/models/base.py", line 880, in _do_insert using=using, raw=raw) File "/usr/local/lib/python3.6/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/usr/local/lib/python3.6/site-packages/django/db/models/query.py", line 1125, in _insert return query.get_compiler(using=using).execute_sql(return_id) File "/usr/local/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1280, in execute_sql for sql, params in self.as_sql(): File "/usr/local/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1233, in as_sql for obj in self.query.objs File "/usr/local/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line … -
django views, getting request and using it as a parameter
I'm very confused about this right now, so I know when there's a simple code like the below def text_detail(request ,course_pk, step_pk): step = get_object_or_404(Text, course_id = course_pk, pk=step_pk) course_pk and step_pk from the url, and those requests are set equal to course_id and pk here. but what I don't understand is what is course_id and pk here? I mean, course_id is from Course model which is foreignkey to step. so it's self.Course.id so it's course_id. But then, how about the next one pk? shouldn't it be step_id = step_pk? when it's just pk how does django know which pk it is? Sorry if the question is very confusing, I'm very confused right now. -
Django application not starting on port 8000 in aws ec2 instance
I tried to host a simple django project on aws but am unable to run the website using ./manage.py runserver 0.0.0.0:8000 at http://18.217.250.17:8000 . I plan on using ngingx and gunicorn later to serve the static files. I have enabled port 8000 as a custom TCP inbound port in Security groups of my aws instance. Also port 8000 has been allowed by the firewall. Output of sudo ufw status - Status: active To Action From -- ------ ---- 8000 ALLOW Anywhere Nginx HTTP ALLOW Anywhere OpenSSH ALLOW Anywhere 8000 (v6) ALLOW Anywhere (v6) Nginx HTTP (v6) ALLOW Anywhere (v6) OpenSSH (v6) ALLOW Anywhere (v6) and curl -v ec2-18-217-250-17.us-east-2.compute.amazonaws.com port 8000 gives the following output - * Rebuilt URL to: ec2-18-217-250-17.us-east-2.compute.amazonaws.com/ * Trying 172.31.41.98... * Connected to ec2-18-217-250-17.us-east-2.compute.amazonaws.com (172.31.41.98) port 80 (#0) > GET / HTTP/1.1 > Host: ec2-18-217-250-17.us-east-2.compute.amazonaws.com > User-Agent: curl/7.47.0 > Accept: */* > < HTTP/1.1 200 OK < Server: nginx/1.10.3 (Ubuntu) < Date: Tue, 27 Mar 2018 01:21:38 GMT < Content-Type: text/html < Content-Length: 612 < Last-Modified: Tue, 27 Mar 2018 00:21:13 GMT < Connection: keep-alive < ETag: "5ab98e79-264" < Accept-Ranges: bytes < <!DOCTYPE html> <html> <head> <title>Welcome to nginx!</title> <style> body { width: 35em; margin: 0 auto; … -
`table "django_migrations" already exists` error with Python 3 and SQLite3
I've recently started receiving an error that I'm having trouble identifying with a Django project using SQLite. The project linked below was/is previously Python 2/3 compatible, though I primarily ran it using Python 2. Recently, I switched over most of my computers and projects to default to using Python 3 (I know, better late than never, right?). Additionally, I upgraded the project from Django 1.7 to 1.11. After this, the project started receiving the table already exists error, but only when running the migrate command using python3. I also only get the error when running python3 manage.py migrate. For instance, python3 manage.py test works just fine, which is a bit baffling given test first runs the migrations. Running python2 manage.py migrate works just fine, no errors. I am running Python 3.6.4, installed via Homebrew on a Mac, and the error I received is: File "/usr/local/lib/python3.6/site-packages/django/db/migrations/recorder.py", line 59, in ensure_schema raise MigrationSchemaMissing("Unable to create the django_migrations table (%s)" % exc) django.db.migrations.exceptions.MigrationSchemaMissing: Unable to create the django_migrations table (table "django_migrations" already exists) I run into this exact same issue—broken with Python 3 but working with Python 2—on multiple computers, so I'd imagine anyone else will see the same issue. You should be … -
Django static files won't refresh
For some reason the URLs for the static files in my django won't change. I changed it from static to staticfiles to avoid conflict with my global static files. My project setup is as follows exampleproject/ app1/ static/ css/ app2/ static/ css/ static/ css/ exampleproject/ settings.py staticfiles/ # static files collected here app1/static/css/ app2/static/css/ manage.py And it seems to work in my test environment. But on deployment, it won't change the URLs on the page to /staticfiles/ instead of /static/, even after clearing cache, restarting nginx/gunicorn and making sure it was up to date with git. -
Django Beginner. I want a queryset of a certain field of all the items in a queryset. How do I do that? Django
An animal species can belong too many zoo and a zoo can contain many animal species. One zookeeper is assigned to each zoo. I need a queryset that contains the zookeepers of a certain animal species from django.db import models class Zoo(models.Model): zoo_keeper = models.ForeignKey(ZooKeeper, related_name='zoo') class ZooKeeper(models.Model): #... class Animal(models.Model): zoo = models.ManyToManyField(Zoo) The following is my solution, but I was told this is gonna be slow with large databases. I need something that is pure django, maybe some kind of filter?. def get_queryset(self): animal_id = self.kwargs['pk'] animal = Animal.objects.get(pk=animal_id) zoos = animal.zoo.all() queryset = [zoo.zoo_keeper for zoo in zoos] return queryset This is my other solution, I'm not sure if it will work: def get_queryset(self): animal_id = self.kwargs['pk'] animal = Animal.objects.get(pk=animal_id) zoos = animal.zoo.all() queryset = ZooKeeper.objects.filter(zoo__in=zoos) return queryset -
How to pass a value returned by Javascript function to a url in django?
I am using Google Place Autocomplete in django template. I have a search bar which will show prediction for places. When users clicks the search button, I want to pass the value which is in search bar to django URL. Below is the code <label for="locationTextField">Location</label> <input id="locationTextField" type="text" size="50"> <a href="{% url 'filteredcars' city %}" id= "output">Search</a> <script> function init() { var input = document.getElementById('locationTextField'); var autocomplete = new google.maps.places.Autocomplete(input); google.maps.event.addListener(autocomplete, 'place_changed', function f1() { var place = autocomplete.getPlace(); var city = place.address_components[0].short_name; document.getElementById("output").innerHTML = city; }); } google.maps.event.addDomListener(window, 'load', init); </script> I am able to get the city and show it in a HTML page, but I am not able to pass it as parameter in URL. -
Data from django models not passing to highcharts chart
I've been trying to follow this approach here to try and pass data from django models to a highcharts chart. However, it doesn't seem to be passing any data, even though there is indeed applicable data in my database. Here is the relevant code: views.py: def master(request): class ChartData(object): def check_usage_data(): data = {'usage': []} sources = RealTimeData.objects.all() for source in sources: data['usage'].append(source.usage) return data if request.user.is_authenticated(): data = ChartData.check_usage_data() series = [ {"data": data['usage']} ] return render(request, 'Properties/master.html', {'series': series}) else: # If the usre isn't authenticated, the user is redirected to the Sign-n Page return render(request, 'SignIn/SignInPage.html') master.html: <!-- Chart builders --> <script type="text/javascript"> var RealTimeSeries = {{ series|safe }} // hours setting // hoursX = ['1:00', '2:00', '3:00', '4:00', '5:00', '6:00', '7:00', '8:00', '9:00', '10:00', '11:00', '12:00', '13:00', '14:00', '15:00', '16:00', '17:00', '18:00', '19:00', '20:00', '21:00', '22:00', '23:00', '24:00'] // categories/dates setting // oneYearX = ['Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec', 'Jan', 'Feb', 'Mar'], sixMonthX = ['Oct', 'Nov', 'Dec', 'Jan', 'Feb', 'Mar'] threeMonthX = ['Jan', 'Feb', 'Mar'] // usage data sets // usageoneYearY = [9164950.4, 8154238.9, 3387452.8, 8849677.6, 9957030.6, 10740101.9, 9196562.5, 10532428.8, 10017343.7, 10190627.7, 9454554.3, 7832326.9] usagesixMonthY = [9196562.5, 10532428.8, 10017343.7, 10190627.7, 9454554.3, 7832326.9] … -
Django + Daphne hot reload after code updates
I am running a Django restserver application served by Daphne and Nginx acting as reverse proxy. I also have a periodic cron job that pulls updated code from my git to the server. I am not able to find a way to do a hot reload and regenerate the pyc files like it how it does in Django development server. Is there a good way to go about this? Don't want to restart my entire server for this. -
Django Models FULL JOIN
I have three models namely, accounts, transactions, logs: class accounts(model.Model): id = models.CharField(max_length=200, blank=True, null=True) name = models.CharField(max_length=200, blank=True, null=True) date = models.DateField() class transactions(model.Model): id = models.CharField(max_length=200, blank=True, null=True) date = models.DateField() class logs(model.Model): id = models.CharField(max_length=200, blank=True, null=True) date = models.DateField() activity = models.CharField(max_length=200, blank=True, null=True) Accounts add new entries with the same name and ID but different dates every day so that we could track changes of accounts per day. How can I possible join query set results from these three different models? Example: accounts.id = transactions.id WHERE both dates = YYYY-mm-dd, and displays all fields in accounts and transactions? I've tried iterating through the queryset of transactions where date = N and match it with the queryset of accounts where date = N but it takes a long time considering the number of transactions per day.