Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Mod_wsgi, for apache2 wsgi file cannot be loaded
I am attempting to move a Django project on to a apache2 web server, iv tested that the apache2 server is running and can get to its default pages, has the python3 version of mod_wsgi installed and running, but when i enable my site i get a 500 internal error. Here is my .conf file <VirtualHost *:80> ServerName ticketblock.tk WSGIDaemonProcess ticketblock threads=18 python-path="/var/www/ticketblock/v0.1.0/" WSGIApplicationGroup %{GLOBAL} WSGIScriptAlias / /var/www/ticketblock/v0.1.0/TicketBlock/wsgi.py WSGIProcessGroup ticketblock WSGIScriptReloading On <Directory /var/www/ticketblock/v0.1.0/> Order deny,allow Allow from all Require all granted </Directory> My wsgi.py file import os import sys from django.core.wsgi import get_wsgi_application sys.path.append('var/www/ticketblock/v0.1.0') os.environ.setdefault("DJANGO_SETTINGS_MODULE", "TicketBlock.settings") application = get_wsgi_application() I know a that a common issue is a missing init.py file, I have this. The error log from apache2 including traceback. [Fri Jun 01 23:18:40.820768 2018] [wsgi:error] [pid 4998:tid 139728384325376] [remote 127.0.0.1:46603] mod_wsgi (pid=4998): Target WSGI script '/var/www/ticketblock/v0.1.0/TicketBlock/wsgi.py' cannot be loaded as Python module. [Fri Jun 01 23:18:40.820861 2018] [wsgi:error] [pid 4998:tid 139728384325376] [remote 127.0.0.1:46603] mod_wsgi (pid=4998): Exception occurred processing WSGI script '/var/www/ticketblock/v0.1.0/TicketBlock/wsgi.py'. [Fri Jun 01 23:18:40.822027 2018] [wsgi:error] [pid 4998:tid 139728384325376] [remote 127.0.0.1:46603] Traceback (most recent call last): [Fri Jun 01 23:18:40.822111 2018] [wsgi:error] [pid 4998:tid 139728384325376] [remote 127.0.0.1:46603] File "/var/www/ticketblock/v0.1.0/TicketBlock/wsgi.py", line 17, in <module> [Fri Jun 01 … -
Inserted Google Analytics into Django base.html template
As I am trying to integrate google analytics tool into my developing django project, it seems I cannot make it work. I tried to follow Google's instruction to insert the code snippet into my base.html, as the following: # base.html {% load staticfiles %} <head> ... a lot of meta and scripts here ... <script async src="https://www.googletagmanager.com/gtag/js?id=[GA-ID]"></script> <script> window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', [GA-ID]); </script> </head> <body> ...... </body> In other pages, I simply extend the base.html # other html templates {% extends 'base.html' %} ...... Is there anything I did wrong? Any suggestions for me to make it work? Thanks a lot in advance!! -
Django - How to customize storage so `FileField` can take either file (binary) or file path (unicode)?
Initially, I implemented a model that has FileField as the type of one of its fields: class Item(models.Model): content = models.FileField(upload_to=upload_path) # more fields here Then I use the Django REST Viewset to implement the API endpoints, so the user can upload files to the server. But then the requirements change: the files are now directly uploaded into a particular storage. At first, I decided to change the type of the content from FileField to CharField and store only the path of the file. However, I realized it would be better for the functionality to be backwards-compatible. If possible, I want the field to accept both file path and binary file, and save it as file (into the storage system) only when it is binary. I've heard you can specify a storage class for the FileField, but I don't know how to customize such storage class to solve my problems, if it's doable at all. -
How to solve model has no field named 'True'?
I'm useing django-restframework. I encountered a very weird problem and can't work it out. When I tried to access to 'http://127.0.0.1:8000/api/attendance/' after being authenticated, this problem occurred: Traceback: File "C:\ProgramData\Anaconda3\lib\site-packages\django\db\models\options.py" in get_field 566. return self.fields_map[field_name] During handling of the above exception (True), another exception occurred: File "C:\ProgramData\Anaconda3\lib\site-packages\django\core\handlers\exception.py" in inner 35. response = get_response(request) File "C:\ProgramData\Anaconda3\lib\site-packages\django\core\handlers\base.py" in _get_response 158. response = self.process_exception_by_middleware(e, request) File "C:\ProgramData\Anaconda3\lib\site-packages\django\core\handlers\base.py" in _get_response 156. response = response.render() File "C:\ProgramData\Anaconda3\lib\site-packages\django\template\response.py" in render 106. self.content = self.rendered_content File "C:\ProgramData\Anaconda3\lib\site-packages\rest_framework\response.py" in rendered_content 72. ret = renderer.render(self.data, accepted_media_type, context) File "C:\ProgramData\Anaconda3\lib\site-packages\rest_framework\renderers.py" in render 724. context = self.get_context(data, accepted_media_type, renderer_context) File "C:\ProgramData\Anaconda3\lib\site-packages\rest_framework\renderers.py" in get_context 656. raw_data_post_form = self.get_raw_data_form(data, view, 'POST', request) File "C:\ProgramData\Anaconda3\lib\site-packages\rest_framework\renderers.py" in get_raw_data_form 572. data = serializer.data.copy() File "C:\ProgramData\Anaconda3\lib\site-packages\rest_framework\serializers.py" in data 560. ret = super(Serializer, self).data File "C:\ProgramData\Anaconda3\lib\site-packages\rest_framework\serializers.py" in data 266. self._data = self.get_initial() File "C:\ProgramData\Anaconda3\lib\site-packages\rest_framework\serializers.py" in get_initial 413. for field in self.fields.values() File "C:\ProgramData\Anaconda3\lib\site-packages\rest_framework\serializers.py" in fields 363. for key, value in self.get_fields().items(): File "C:\ProgramData\Anaconda3\lib\site-packages\rest_framework\serializers.py" in get_fields 1026. field_names, declared_fields, extra_kwargs File "C:\ProgramData\Anaconda3\lib\site-packages\rest_framework\serializers.py" in get_uniqueness_extra_kwargs 1403. unique_constraint_field = model._meta.get_field(unique_constraint_name) File "C:\ProgramData\Anaconda3\lib\site-packages\django\db\models\options.py" in get_field 568. raise FieldDoesNotExist("%s has no field named '%s'" % (self.object_name, field_name)) Exception Type: FieldDoesNotExist at /api/attendance/ Exception Value: Attendance has no field named 'True' To be honest, … -
Get content from all pages in view
I am trying to create a blog using Django. The blog features an archive script I have made using javascript. This script is called directly from my template with an argument, containing a list of ALL articles. To allow for pagination I am using djangos built in pagination plugin. I have run into a problem, since implementing the pagination. The variable used in the call to my archive script now only contains articles from the current page, and so the archive only contains articles from the current page. Is there some way I can get all the content from each page directly from the template and call my archive function with this? views.py from django.shortcuts import get_object_or_404, render from django.http import HttpResponseRedirect from django.urls import reverse from django.views import generic from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator from .models import Article class IndexView(generic.ListView): template_name = 'blog/index.html' context_object_name = 'latest_article_list' paginate_by = 1 def get_queryset(self): """Return the published articles. Newest first.""" return Article.objects.order_by('-pub_date') class DetailView(generic.DetailView): model = Article template_name = 'blog/detail.html' index.html {% include "blog/header.html" %} {% load jsonify %} <div class="container"> <div id="header"> <ul> <li><a class="selected" href="/">blog</a></li> <li><a href="/projects/">projects</a></li> <li><a href="/contact/">contact</a></li> </ul> </div><hr> </div> <div class="container"> <div class="row"> <div class="col-md-9 content-main"> … -
How to fetch data while ignoring some specific fields?
With a model Book that uses MarkDown for a field called content, when I do the following query Book.objects.filter(published=True).order_by('read') The site becomes slow because of the content field, I think the hard work occurs when Django tries to convert these fields to python object. When I clean all the content field for each record and leave them blank, the query is pretty much faster. In my case content field contains large text. To gain in performance, How can I fetch data by ignoring a specific field? I want to ignore content field like: Book.objects.filter(published=True)#.ignore_fields('content',).order_by('read') -
Django - update model with user input by id
I stuck with my first app in Django. Basically it will be several objects on webpage, every object with input form. If user types and email address to input, this object should be marked as 'reserved'. I tried several solutions (and problably because of this multi-solution none of them worked). At the beggining I used AJAX to update the status of the object and it worked, but when I implemented email address input it failed. So I found out that I should give up on AJAX and go after ModelForm. So for now my not-working code is looking like this: urls.py urlpatterns = [ url(r'^$', views.index), url(r'^occupy/$', views.occupy, name='occupy'), index.html {% for gift in gifts %} <div class="panel-heading"> <h2 class="panel-title"> {{ gift.name }}</h2> </div> <div class="panel-body"> {{ gift.link }} <form role="form" action="" method="POST"> {% csrf_token %} {{ form }} <input type="submit" value="szukaj" name='q' data-id="{{ gift.id }}"> </form> </div> {% endfor %} models.py class Gift(models.Model): name = models.CharField(max_length=100) link = models.URLField(max_length=100) email = models.EmailField(blank=True, default='') occupied = models.BooleanField(default=0) forms.py class ContactForm(forms.ModelForm): class Meta: model = Gift fields = ('email',) views.py def index(request, id): gifts = Gift.objects.all() form_class = ContactForm() if request.method == 'POST': occupy(request) def occupy(request): print('hrj') gift_id = request.GET.get('gift_id', None) … -
Why celery task don't work?
In my Django project I need to run celery task periodically. I use Celery 4 + Redis. First I run redis-server, then use next commands: $ celery -A TestProject worker -l info $ celery -A TestProject beat -l info First command raise next error: The full contents of the message body was: b'[[], {}, {"errbacks": null, "chord": null, "chain": null, "callbacks": null}]' (77b) Traceback (most recent call last): File "/home/ubuntu/enjoy_jumping/lib/python3.5/site-packages/celery/worker/consumer/consumer.py", line 557, in on_task_received strategy = strategies[type_] KeyError: 'profile.tasks.amount_counting' celery.py (file in the same directory as settings.py file) from __future__ import absolute_import, unicode_literals import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'TestProject.settings') app = Celery('TestProject') # Using a string here means the worker doesn't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django app configs. app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) init.py: (file in the same directory as settings.py file) from __future__ import absolute_import, unicode_literals # This will make sure the app is always imported when Django starts so that shared_task will use this app. … -
I have created a django app for URL shortening
I have created a URL shortening django app. Now I want to modify this to shorten multiple URLs at once. How can I do this? My home page has a submit button and an input field. It returns short code generated and long URL. -
uWSGI listen queue of socket full
My setup includes Load Balancer (haproxy) with two NGINX servers running Django. Server 2 works fine but sometimes server 1 will start crashing and log will be full of "* uWSGI listen queue of socket ":8000" (fd: 3) full !!! (101/100) *" message. -
How can I optimize the following code
color and size are taken from URL using GET method in django color and size are check box inputs and are recieved as a list in the view.py file I am filtering my Prouct table using color and size attributes mydict = dict(request.GET) if 'size' in mydict: result1 = Product.objects.filter(attributes__size__in=mydict['size']) if 'color' in mydict: result2 = Product.objects.filter(attributes__color__in=mydict['color']) result = result1.intersection(result2) -
Django: Template tag - the right way?
I wrote the following simple template tag. I am wondering if there is any better way to write this without i = 0 and i + 1, or would you consider that as the good solution? @register.simple_tag def taxes(taxes): i = 0 s = "" for tax in taxes: if i is not 0: s += ", " s += tax.name i += 1 output = "Incl. {}".format(s) return output As an alternative, I wrote this function in my template. It has the same outcome, but the template tag seemed more structured to me. {% spaceless %} {% for tax in form.initial.ticket.ticket_tax.all %} {% if forloop.first %} Incl. {% else %} , {% endif %} {{ tax.name }} @ {% get_tax_rate tax.percentage %} {% endfor %} {% endspaceless %} -
Django form field validator not raising error on field in template
Tried using this (Django: How to set DateField to only accept Today & Future dates) SO post to have form raise error in template when a date field is given value less than current date (which, based on another SO answer (https://stackoverflow.com/a/22513989/8236733), I thought was done via the form field validators (see https://docs.djangoproject.com/en/2.0/ref/forms/validation/#cleaning-a-specific-field-attribute)). However, this does not seem to be working when inputting supposedly invalid values in the form template. forms.py: import datetime from django import forms from .models import Post class MyForm(forms.Form): title = forms.CharField(max_length=100, required=True, help_text='Give a title', widget=forms.TextInput(attrs={'size': '50rem'})) post = forms.CharField(max_length=280, required=True, widget=forms.Textarea(attrs={'rows': 5})) expire_date = forms.DateField( widget=forms.TextInput(attrs= { 'class':'datepicker', # to use jquery datepicker }), required=True ) expire_time = forms.TimeField( input_formats=['%H:%M %p'], widget=forms.TextInput(attrs= { 'class':'timepicker', # to use jquery timepicker }), required=True) class Meta: model = Post fields = ('title', 'post', 'expire_date', 'expire_time',) def clean_date(self): # see https://docs.djangoproject.com/en/dev/ref/forms/validation/#cleaning-a-specific-field-attribute date = self.cleaned_data['expire_date'] print(date) if date < datetime.date.today(): raise forms.ValidationError("The date cannot be in the past!") return date Relevant template snippet: <form method="post"> {% csrf_token %} {% for field in listing_form %} <p> {{ field.label_tag }} <div class="ui input">{{ field }}</div> {% if field.help_text %} <small class="ui inverted">{{ field.help_text }}</small> {% endif %} {% for error in … -
How to update user list field after user created; signals
Im Having Model Question, which is contains all user list field. After creating new user users field is not updating and i need to re-run server to see changes and i dont want to do that. class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') users = User.objects.values_list('id','username') authorized = MultiSelectField(choices=users,null=True) def __str__(self): return "{question_text}".format(question_text=self.question_text) @staticmethod def update_users(sender, instance, **kwargs): #q = Question.objects.all() userz = User.objects.values_list('id','username') Question.objects.all().update(users=userz) post_save.connect(Question.update_users, sender=User) Im geting : Question has no field named 'user' I followed those tips : How can I have a Django signal call a model method? and still not working and im stuck. Thanks for help! -
Trying to display a list of youtube videos into django template with django-embed-video
I am trying to embed a list of youtube videos, in which more videos will be added over time, into my django app using django-embed-video. Going after their documentation I did the following: models.py from embed_video.fields import EmbedVideoField class Youtube(models.Model): video = EmbedVideoField() slug = models.SlugField(max_length=200, db_index=True, unique=True) def __str__(self): return self.video admin.py from .models import Youtube from embed_video.admin import AdminVideoMixin class YoutubeAdmin(AdminVideoMixin, admin.ModelAdmin): list_display = ('video', 'slug') admin.site.register(Youtube, YoutubeAdmin) views.py from .models import Youtube def display_video(request): videos = Youtube.objects.all() context = {'videos': videos} return render (request, 'scienceblog/post/videos.html', context) videos.html {% extends "base.html" %} {% load embed_video_tags %} {% video item.video 'small' %} {% block content %} {% if videos %} {% for v in videos %} {{ v }} {% endfor %} {% else %} <p>No videos yet</p> {% endif %} {% endblock %} Everything works perfect in the admin site. The youtube links are added and the videos are displayed. However I am very unsure about the HTML tags. The browser only displays the youtube links as a string when videos.html is rendered. How can I display the videos? -
render_to_string using a template that no longer should exist
I'm using "render_to_string" in order to generate emails. def get_html(self): return render_to_string( 'emails/default.html', { 'subject' : self.subject, 'body' : self.body, }) Unfortunately, the output of this method does not correspond to the "emails/default.html" template. It's using an old template that no longer exists in my codebase (I've used Ctrl+Shift+F in Sublime Text to make sure this template exists absolutely nowhere). The "emails/default.html" template lives in "sitename/emails/templates/emails/default.html". Why is Django still using this old template ? How can I debug / fix this ? -
Django Application, Django forms
I am creating an image classifier application. I am new to Django and what I am trying to do is I take an input image from the user via Django form and running the backend code for classification. After successful submission of the form, I redirect to the same form's page. Again, if I input another/same image, tensorflow throws error. Only when I input image for the first time, error does not occur. Please help! -
Many to Many Bulk serilization Django Rest Framework
Can any one let me know how to use view and serializer for http post request for below format of data [{ “type1”: tv1, “type2”: “tv2”, “type3”: [ “g1”, " g2”, " g3”, " g4” ], “type4”: “tv3” }, { “type1”: tv1, “type2”: “tv2”, “type3”: [ “g1”, " g2”, " g3”, " g4” ], “type4”: “tv3” }] Model1: fields (type1,type2,type3,type4) Model2: fields (name) eg. g1,g2.... There is Many to Many relation between Model1 : field type3 with model2: name field I have spent some time now , unable to figure out. I am trying to serialize using ModelView Set and Model Serializer: -
How to locate the building locations in GEODJANGO?
I have some shape files that having the some objects that contains the adress fileds and geometric coordinates. I created the models for that format and import the shape files into the models. By using this models I need to locating the building location and shape of the building by using the shape file. here i am using the Python,GeoDjango for backend and javascript,Jquery for frontend. could you please give me the solution to get it done? -
docker images not working as expexted
i am working on an application which manages documents(EDMS) developed in python django and i have documents merge functionality in it by drag drop. as i run the application locally every thing works fine.but when i build docker images for application and run containers by docker-compose up it does not show 1-the cover image for document and 2-on merging the document it shows error "NoneType' object has no attribute 'mode". i am using postgres as database and python 2.7 My docker version: Docker version 18.03.1-ce, build 9ee9f40 Any help will be appreciated. Thanks in advance. -
Feedback a prompt page first then send validating email to User
I intend to send validating message to User's email to complete a registration with the following codes: def register(request): """1. register a new user 2. generate activating code 3. send validating email 4. prompt to check activating email. """ if request.method == "GET": form = UserForm() if request.method == "POST": form = UserForm(request.POST) print(vars(form)) if form.is_valid(): #1. Create User and save to sever user = User.objects.create_user( form.cleaned_data['username'], first_name=form.cleaned_data['first_name'], last_name=form.cleaned_data['last_name'], email=form.cleaned_data['email'], password=form.cleaned_data['password']) user.is_active = False user.save() #2. Create activate code and save to server. uuid_code = str(uuid.uuid4()).replace("-", '') activate_code = ActivateCode(user=user, code=uuid_code) activate_code.save() #3. Send Validation Email activate_link = "http://%s/user/activate/%s" %(request.get_host(), uuid_code) activate_message = """\ You're almost done! <a href="%s">Click here to complete your registration</a> """ % activate_link send_mail(subject="Complete Registration With Code Journey", message="Click here to complete your registration: %s" %activate_link, html_message=activate_message, from_email="anexmaple@mail.com", recipient_list=[form.cleaned_data['email'],], fail_silently=False) #4. Prompt user to check his email. context = {'email': form.cleaned_data['email'],} return render(request, "user/validate.html", context) The problem is that the user/validate.html feedbacks to me very slowly after formulated form was submittd. I guess it's send_email consuming lots of my patience. How could I implement step 4 in advance which immediately show prompt message then send mail unhurried. -
How should I move my completed Django Project in a Virtual Environment?
I started learning django a few days back and started a project, by luck the project made is good and I'm thinking to deploy it. However I didn't initiate it in virtual environment. have made a virtual environment now and want to move project to that. I want to know how can I do that ? I have created requirements.txt whoever it has included all the irrelevant library names. How can I get rid of them and have only that are required for the project. -
What does backend agnostic mean?
I installed django-organizations It says that django-organizations should be backend agnostic. How it works in practice? -
Unable to get tinymce to work in django: AttributeError: module 'django.db.models' has no attribute 'HTMLField'
I am trying to get this package to work in Django: https://github.com/romanvm/django-tinymce4-lite I'm using docker compose for my django installation. The setup is identical to this one here: https://docs.docker.com/compose/django/ Earlier when I encountered similar errors it had to do with the pip package not being properly loaded in docker. Now, I have loaded the "django-tinymce4-lite" package as follows: I have edited my requirements.txt in my project I have rebuilt my docker image When I log onto the docker instance, I can check the presence of the package using this: $ pip freeze Django==2.0.6 django-bootstrap3==10.0.1 django-tinymce4-lite==1.7.1 jsmin==2.2.2 Pillow==5.1.0 psycopg2-binary==2.7.4 pytz==2018.4 This seems to be in line with my requirements.txt file: Django>=2.0 psycopg2-binary django-bootstrap3 django-tinymce4-lite Pillow However, when I follow the instructions I do this: Add tinymce to INSTALLED_APPS in settings.py for your Django project INSTALLED_APPS = ( ... 'tinymce', ) Add tinymce.urls to urls.py for your project: urlpatterns = [ ... url(r'^tinymce/', include('tinymce.urls')), ... ] NOTE: because I use Django 2 I have had to rewrite this. Here is what I use: path('tinymce/', include('tinymce.urls')), I have tried this both in my main project urls.py as well as in my app urls.py. The next step is: In your code: from django.db import … -
Multiple checkboxes selected and form submitted
So I have a Student model which contains some students and then a Course model which contains courses. In order to enroll a student to a course, I am using a form with a checkbox. But now I was wondering how can I allow checking multiple boxes, for many students, and add them all at once. Below is what I tried, though it is not working.. For this I use just a function view. {% with crs_stud=course.student.all %} {% for student in students %} {% if not student in crs_stud %} <form action="" class="enroll enroll2" id="enroll2" style="height:120px;" method="POST"> <input type="checkbox" id="id_{{ student_id }}" value="{{ student.id }}" name="student_ids"> <input type="submit" value="Enroll"> </form> {% endif %} {% endfor %} {% endwith %} if request.method == 'POST': if 'student_ids' in request.POST: for item in (request.POST.getlist['student_ids']): course.student.add(item)