Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django AttributeError: 'MyModel' object has no attribute 'username'
I have a model, MyModel that is linked via ForeignKey to Django's User model. MyModel was initially linked using models.OneToOneField but I later changed it to models.ForeignKey and also deleted some fields. Initial Models.py: from django.contrib.auth.models import User from myapp.models import mymodel class MyModel(models.Model): user = models.OneToOneField(User, blank=True, null=True, related_name='mymodel') username = models.CharField(max_length=145, blank=True, null=True) name = models.CharField(max_length=45, blank=True, null=True) Editted Model.py: class MyModel(models.Model): user = models.ForeignKey(User, blank=True, null=True, related_name='mymodel') name = models.CharField(max_length=45, blank=True, null=True) I deleted migration folder and my DB and recreated them anew but each time I try retrieving data from MyModel via MyModel.objects.all() or User object I get AttributeError: 'MyModel' object has no attribute 'username' -
How to make subquery in django ORM
I have 2 tables: people and people_tag. Every people has 3 tags in people_tag table. I want to execute specific query. Tables (I create this tables with help django ORM): create table people ( id serial primary key ); create table people_tag ( id serial primary key, people_id serial references people(id), tag text, threshold integer ); Raw query example (that me need in result): select people_id from ( select people_id, array_agg(tag) as tags from people_tag where threshold >= 40 group by people_id ) as t where 'man' = ANY(tags) and ('tall' = ANY(tags) or 'short' = ANY(tags)) and 'thin' = ANY(tags); I try that in django: PeopleTag.objects.values_list('people_id').annotate(ArrayAgg('tag')).filter(threshold__gte=min_threshold) And get: SELECT "peopletag"."people_id", array_agg("peopletag"."tag") AS "tag__arrayagg" FROM "peopletag" WHERE "peopletag"."threshold" >= 70 GROUP BY "peopletag"."people_id"; How to make subquery for filter tags (tag__arrayagg)? I know how to make filtration(with .extra(where=...)), but can't make subquery. In result me need people ID array. Playground: http://sqlfiddle.com/#!15/97d788/16 Thank you. -
Django: Redirect to same page after POST method using class based views
I'm making a Django app that keeps track of tv show episodes. This is for a page on a certain Show instance. When a user clicks to add/subtract a season, I want the page to redirect them to the same detail view, right now I have it on the index that shows the list of all Show instances. show-detail.html <form action="{% url 'show:addseason' show=show %}" method="post"> {% csrf_token %} <button class="btn btn-default" type="submit">+</button> </form> <form action="{% url 'show:subtractseason' show=show %}" method="post"> {% csrf_token %} <button class="btn btn-default" type="submit">-</button> </form> views.py class AddSeason(UpdateView): model = Show slug_field = 'title' slug_url_kwarg = 'show' fields = [] def form_valid(self, form): instance = form.save(commit=False) instance.season += 1 instance.save() return redirect('show:index') class SubtractSeason(UpdateView): model = Show slug_field = 'title' slug_url_kwarg = 'show' fields = [] def form_valid(self, form): instance = form.save(commit=False) if (instance.season >= 0): instance.season -= 1 else: instance.season = 0 instance.save() return redirect('show:index') I get an error when I try return redirect('show:detail') This is the error NoReverseMatch at /Daredevil/addseason/ Reverse for 'detail' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: [] -
Comments not showing in post_detail view
I am doing a project in django 1.9.9/python 3.5, for exercise reasons I have a blog app, an articles app and a comments app. Comments app has to be genericly related to blog and articles. My problem is that the templates are not showing my comments. Comments are being created and related to their post/article because I can see it in admin, so it is not a comment creation problem. They are simply not showing in my template. My comments/models.py: from django.db import models class Comment(models.Model): post = models.ForeignKey('blog.Entry',related_name='post_comments', blank=True, null=True) article = models.ForeignKey('articles.Article', related_name='article_comments', blank=True, null=True) body = models.TextField() created_date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.body My commments/views.py: from django.utils import timezone from django.shortcuts import render, get_object_or_404 from django.shortcuts import redirect from .forms import CommentForm from .models import Comment from blog.models import Entry from articles.models import Article from blog.views import post_detail from articles.views import article_detail def article_new_comment(request, pk): article = get_object_or_404(Article, pk=pk) if request.method == "POST": form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.article = article comment.created_date=timezone.now() comment.save() return redirect(article_detail, pk=article.pk) else: form=CommentForm() return render(request, 'comments/add_new_comment.html', {'form': form}) def blog_new_comment(request, pk): post = get_object_or_404(Entry, pk=pk) if request.method == "POST": form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.post … -
Django : Update ImageField from OneToOne relation
After several hours to try to update a ImageField in the views.py, I need your helps : MODEL : class ImageTeam(models.Model): image = models.ImageField(upload_to="imageTeam/", null=False) team = models.OneToOneField(Team,on_delete=models.CASCADE,related_name="theImage", null=False) VIEW : def update_team(request, idTeam): try : team = Team.objects.get(id = idTeam) except Team.DoesNotExist : return redirect(teams) ... if request.method == "POST" : form = updateTeamForm(request.POST, request.FILES) if form.is_valid() and form.has_changed() : team.name = form.cleaned_data["name"] ... imageForm = form.cleaned_data["name"] if imageForm : if hasattr(team, 'theImage') : team.theImage.image = imageForm team.theImage.save() #save doesn't works! else : #works! ImageTeam.objects.create(image = imageForm, team=team) ... TEMPLATE : <form method="POST" enctype="multipart/form-data" action="{% url 'update_team' team.id %}" class="form-signin"> {% csrf_token %} ... <div class="row"> {{ form.image }} </div> ... FORM : class updateTeamForm(forms.ModelForm): image = forms.ImageField(widget=forms.ClearableFileInput(attrs={'id':'image_team'})) ... class Meta : model = Team exclude = ['image',...] I have tried many solutions (get the instance and save it, use request.FILES['image'], write directly in path...) So why the imageField is not updated ? I will very happy if I can fix this problem today -
Django: ImportError: cannot import name 'User'
I'm new to django and I'm facing some difficulties in creating a user from the AbstractBaseUser model. Now I'm starting wondering if my user model is not being build in the right way. This is my User model from django.db import models from django.contrib.auth.models import AbstractBaseUser class User(AbstractBaseUser): ''' Custom user class. ''' username = models.CharField('username', max_length=10, unique=True, db_index=True) email = models.EmailField('email address', unique=True) joined = models.DateTimeField(auto_now_add=True) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) and user is only referenced in this other model from django.db import models from user_profile import User class Tweet(models.Model): ''' Tweet model ''' user = models.ForeignKey(User) text = models.CharField(max_length=160) created_date = models.DateTimeField(auto_now_add=True) country = models.CharField(max_length=30) is_active = models.BooleanField(default=True) then when I try to migrate my new model into db Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/myuser/django-book/lib/python3.5/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/home/myuser/django-book/lib/python3.5/site-packages/django/core/management/__init__.py", line 341, in execute django.setup() File "/home/myuser/django-book/lib/python3.5/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/home/myuser/django-book/lib/python3.5/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models(all_models) File "/home/myuser/django-book/lib/python3.5/site-packages/django/apps/config.py", line 199, in import_models self.models_module = import_module(models_module_name) File "/home/myuser/django-book/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 958, … -
Django is failing to save data related to User table. It says it doesn't have `mymodel_set` attribute
I have a model linked to Django User model but when I try saving to that model using User instance, it says 'User' object has no attribute 'mymodel_set' My models.py: from django.contrib.auth.models import User from django.db import models class MyModel(models.Model): user = models.OneToOneField(User, blank=True, null=True, related_name='mymodel') name = models.CharField(max_length=14, blank=True, null=True) My views.py: from django.contrib.auth.models import User from myapp.models import mymodel def register(request): #gets data here from template user = User(username=reg_username, password=reg_password) user.save() user.mymodel_set.create(name= display_name) return HttpResponse('Success') -
Getting Error on Django Admin logon screen
I am new to Web Development with Django, and I am following the Django tutorials (PollsApp) for learning. When I am trying to launch the Django Admin panel, I am getting an exception 'can't multiply sequence by non-int of type 'tuple'. Can someone please suggest what I am missing? Below is the traceback: ***Environment: Request Method: POST Request URL: http://127.0.0.1:8000/admin/login/?next=/admin/ Django Version: 1.10.1 Python Version: 3.4.3 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'polls.apps.PollsConfig'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "E:\Python34\lib\site-packages\django\core\handlers\exception.py" in inner 39. response = get_response(request) File "E:\Python34\lib\site-packages\django\core\handlers\base.py" in _legacy_get_response 249. response = self._get_response(request) File "E:\Python34\lib\site-packages\django\core\handlers\base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "E:\Python34\lib\site-packages\django\core\handlers\base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "E:\Python34\lib\site-packages\django\views\decorators\cache.py" in _wrapped_view_func 57. response = view_func(request, *args, **kwargs) File "E:\Python34\lib\site-packages\django\contrib\admin\sites.py" in login 377. return login(request, **defaults) File "E:\Python34\lib\site-packages\django\contrib\auth\views.py" in inner 47. return func(*args, **kwargs) File "E:\Python34\lib\site-packages\django\views\decorators\debug.py" in sensitive_post_parameters_wrapper 76. return view(request, *args, **kwargs) File "E:\Python34\lib\site-packages\django\utils\decorators.py" in _wrapped_view 149. response = view_func(request, *args, **kwargs) File "E:\Python34\lib\site-packages\django\views\decorators\cache.py" in _wrapped_view_func 57. response = view_func(request, *args, **kwargs) File "E:\Python34\lib\site-packages\django\contrib\auth\views.py" in login 82. auth_login(request, form.get_user()) File "E:\Python34\lib\site-packages\django\contrib\auth\__init__.py" in login 109. request.session.cycle_key() File "E:\Python34\lib\site-packages\django\contrib\sessions\backends\base.py" in cycle_key 311. self.create() File "E:\Python34\lib\site-packages\django\contrib\sessions\backends\db.py" in create 54. … -
What is the equivalent of autotest/guard for django
When I code in Ruby on Rails, I rely on Guard to listen for changes to the code base so when I'm writing tests, I don't need to manually run the tests in the file I'm working on each time. https://github.com/guard/guard-rspec What is the closest thing to thing for django so I can enjoy the same workflow? Specifically, what I want to do is be able to have tests run, based on: what run tests based on files I have changed, and not know whether to run the test command based on whether a test run is currently taking place work with existing tests written with unittest work with something like factory boy to let me use factories instead of fixtures I've used nose before, and pytest and I'm comfortable using both - but I haven't used many of pytests extensive set of libraries. What are my options for this? -
How do I override django admin's default file upload behavior?
I need to change default file upload behavior in django and the documentation on the django site is rather confusing. I have a model with a field as follows: class document (models.Model): name = models.CharField(max_length=200) file = models.FileField(null=True, upload_to='uploads/') I need to create a .json file that will contain meta data when a file is uploaded. For example if I upload a file mydocument.docx I need to create mydocument.json file within the uploads/ folder and add meta information about the document. From what I can decipher from the documentation I need to create a file upload handler as a subclass of django.core.files.uploadhandler.FileUploadHandler. It also goes on to say I can define this anywhere I want. My questions: Where is the best place to define my subclass? Also from the documentation found here https://docs.djangoproject.com/en/1.8/ref/files/uploads/#writing-custom-upload-handlers looks like the subclass would look like the following: class FileUploadHandler(object): def handle_raw_input(self, input_data, META, content_length, boundary, encoding=None): # do the acctual writing to disk def file_complete(self, file_size): # some logic to create json file Does anyone have a working example of a upload handler class that works for django version 1.8? -
Django simple tag doesn't work in if condition
I want to customize django-admin's change form for video objects by adding block with moderation tools. When I use custom simpletags in if condition - it doesn't work. models.py: class Video(models.Model): class Meta: db_table = 'video' DRAFT = 1 MODERATION = 2 PUBLISHED = 3 REJECTED = 4 HOSTING_UPLOADING = 5 SUSPICIOUS = 6 PUBLICATION_STATUSES = ( (DRAFT, 'draft'), (MODERATION, 'moderation'), (PUBLISHED, 'published'), (HOSTING_UPLOADING, 'hosting uploading'), (REJECTED, 'rejected'), (SUSPICIOUS, 'suspicious') ) video_pk = models.AutoField(primary_key=True) name = models.CharField(max_length=150, blank=True) hosting_id = models.CharField(max_length=20, blank=True) publication_status = models.PositiveSmallIntegerField(choices=PUBLICATION_STATUSES, default=MODERATION) templatetags video_publication_statuses.py: from api.models import Video from django import template register = template.Library() @register.simple_tag def moderation(status): return status == Video.MODERATION @register.simple_tag def suspicious(status): return status == Video.SUSPICIOUS @register.simple_tag def published(status): return status == Video.PUBLISHED @register.simple_tag def hosting_uploading(status): return status == Video.HOSTING_UPLOADING @register.simple_tag def rejected(status): return status == Video.REJECTED change_form.html: {% extends "admin/change_form.html" %} {% load video_publication_statuses %} {% suspicious original.publication_status as suspicious_status %} {% moderation original.publication_status as moderation_status %} {% hosting_uploading original.publication_status as hosting_uploading_status %} {% published original.publication_status as published_status %} {% rejected original.publication_status as rejected_status %} {% block after_related_objects %} {% if original.pk %} {% for fieldset in adminform %} {% if fieldset.name == 'Moderation' %} {% include "admin/includes/fieldset.html" %} {% endif %} … -
Django Test: error creating the test database: permission denied to copy database "template_postgis"
I am am working on setting up Django Project tests. But I am getting below error: Got an error creating the test database: permission denied to copy database "template_postgis" Complete stack trace is as: moin@moin-pc:~/workspace/mozio$ python manage.py test --verbosity=3 nosetests --verbosity=3 nose.config: INFO: Ignoring files matching ['^\\.', '^_', '^setup\\.py$'] Creating test database for alias 'default' ('test_my_db')... Got an error creating the test database: permission denied to copy database "template_postgis" Type 'yes' if you would like to try deleting the test database 'test_mozio_db_test', or 'no' to cancel: yes Destroying old test database 'default'... Got an error recreating the test database: must be owner of database test_mozio_db_test Below is the DATABASE configuration of setting.py: POSTGIS_VERSION = (2, 2, 2) DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': 'my_db', 'USER': 'my_user', 'PASSWORD': 'my_pass', 'HOST': '<HOST_IP', 'PORT': '', 'TEST': { 'NAME': 'test_my_db', }, } } Any help regarding this? Below are the steps I tried: Grant create DB access to user: ALTER USER my_user CREATEDB; Grant all privileges to user for test_my_db database: GRANT ALL PRIVILEGES ON DATABASE test_mozio_db_test to mozio; -
Django how to create table for custom session backend?
After following the brief tutorial on extending database backed sessions in Django (here) I copy and pasted the entire following code into my_project/my_app/sessions.py from django.contrib.sessions.backends.db import SessionStore as DBStore from django.contrib.sessions.base_session import AbstractBaseSession from django.db import models class CustomSession(AbstractBaseSession): account_id = models.IntegerField(null=True, db_index=True) @classmethod def get_session_store_class(cls): return SessionStore class SessionStore(DBStore): @classmethod def get_model_class(cls): return CustomSession def create_model_instance(self, data): obj = super(SessionStore, self).create_model_instance(data) try: account_id = int(data.get('_auth_user_id')) except (ValueError, TypeError): account_id = None obj.account_id = account_id return obj Then in my project configuration file my_project/my_project/settings.py I set SESSION_ENGINE = 'my_app.sessions' django.db.utils.OperationalError: no such table: account_customsession Running python manage.py makemigrations yields No changes detected -
Django 1.9, how to POST multiple select value from html
I have a tempate: div class="panel"> <div class="large-12 columns"> <div class="row collapse"> <div class="small-10 columns"> <input class="input-append date fdatepicker" id="date" type="text" name="date" value="" data-date-format="dd/mm/yyyy"> </div> <div class="small-2 columns"> <input type="button" name="add" id="btn_AddToList" value="dodaj" class="button postfix" /> </div> </div> </div> <br> <select multiple="multiple" size="10" style="height: auto; width: auto" name="dates" id="dates" tabindex="2"> </select> </div> and I add dates to #dates select using this little code: $('#btn_AddToList').click(function () { var val = $('#date').val(); $('#dates').append('<option value="'+val+'">' + val + '</option>'); $('#date').val(''); event.preventDefault(); event.stopPropagation(); }) in my view i want to read dates so i thought i would use: for d in request.POST.getlist('dates'): if d is not None: print(d) But I get None. I tried to use request.POST.getlist('dates[]'): request.POST.get('dates'): but with no success. I am recieving None all the time. What I am doing wrong? -
django unicode url for multibyte special characters
I am trying to create and edit share folder using these special mutibyte characters @@, ああ,@@ , ##. I am able to create but for editing i am receiving 400 request as it is redirecting to another view. Please help on this. -
jquery 500 (Internal Server Error)
I keep getting a 500 server response, it sends item_id but can't load function, so i can't get resp status and message. var remove_item_request = function(item_id){ $.post( '/remove/item/', { item_id:item_id, }, function(resp){ console.log(resp) if(resp.status==200){ alert('Removed!!'); document.location = 'buy-requests/show/'; } else{ alert(resp.message); } } ); } and here is my view.py: def remove_item(request): if request.method == "POST": item_id = int(request.POST.get('item_id', None)) if item_id is None: return HttpResponse(status=400) else: a = CartItem.objects.filter(id=item_id).delete() a.save() return JsonResponse({'status': 200, 'message': 'item Removed'}) else: return JsonResponse({'status': 400, 'message': 'invalid request type'}) -
Django migrations in subfolders
I have the following project structure: bm_app_1 | contents here bm_app_2 | contents here bm_common | __init__.py | deletable | | __init__.py | | behaviors.py | | models.py | timestampable | | __init__.py | | behaviors.py The files in app bm_common define managed models, that I want in migration files. When I run python managepy makemigrations however, the files inside the subfolders of the app bm_common are not taken into account. Is there a way to change the behavior of makemigrations to look into subfolders as well? If not, what would be a good suggestion to make this split? I do not want to have all behaviors in one behaviors.py, because it grows too big and was causing circular references for me. -
How to populate a dropdown in Django?
I want to build a simple view using Django. There will be a dropdown of 'customer site's and then, after one customer site is selected the view will populate a dropdown of competitors of previously selected customer. My trouble is with the second part: when I select the customer from the first dropdown and press 'choose' the page reloads but the competitors dropdown is empty: I debugged the code and there are values returned for the competitors dropdown and they are correct. I have this single view: def index_unify_brands(request): class CustomerSiteDropDown(forms.Form): customer_site_id = forms.ChoiceField(Site.objects.filter(site_type='customer').exclude( crawl_groups='').values_list('id', 'site_name').order_by('site_name'), required=True) class OptionsForm(forms.Form): competitors_site_ids = forms.ChoiceField() def populate_competitors_in_dropdown(self,customer_site_id): competitors_ids = get_competitors_positions(customer_site_id)[ customer_site_id].keys() # todo: if no competitors print competitors_ids competitors_for_dropdown = Site.objects.filter(id__in=competitors_ids).exclude(crawl_groups='') \ .values_list('id', 'site_name').order_by('site_name') print competitors_for_dropdown self.competitors_site_ids = forms.ChoiceField(competitors_for_dropdown, required=True) if request.method == 'POST': # received request for a specific customer site id customer_dropdown_form = CustomerSiteDropDown(request.POST) options_form = OptionsForm(request.POST) options_form.populate_competitors_in_dropdown(int(request.POST['customer_site_id'])) if customer_dropdown_form.is_valid(): return render_to_response('manage/unify_brands/unify_brands.html', {'customer_dropdown_form': customer_dropdown_form, 'options_form': options_form}, context_instance=RequestContext(request) ) else: customer_dropdown_form = CustomerSiteDropDown() return render_to_response('manage/unify_brands/unify_brands.html', {'customer_dropdown_form': customer_dropdown_form}, context_instance=RequestContext(request)) It seems that when I instantiate the OptionsForm object, the options_form.populate_competitors_in_dropdown(....) method doesn't change the dropdown inside this object that is represented by competitors_site_ids variable. Any idea what I do wrong here? -
Project Setup with Django 1.10, mongodb and Python 3.4.3
Initially I have built projects with Django 1.5, django-mongoengine, python 2.7.8. I have started a project with an idea came up to my mind. I want to make it using latest versions of technologies therefore I stick with: Django 1.10, python 3.4.3 I want to use mongodb as my database. To run my project I am facing an error when I tried to connect mongodb with Django. Code in the settings.py is given as follow to connect database (The only change I made yet in file): DATABASES = { 'default': { 'ENGINE': 'django_mongodb_engine', 'HOST': '127.0.0.1', 'PORT':'27017', 'NAME': 'Demo', } } Please help me out to setup project so that I can proceed with my work. Also the environment I have setup for my project is: Django 1.10.1 django-mongodb-engine 0.6.0 django-mongodb-engine-py3 0.6.0.1 django-nonrel-enuff 0.4 django-toolbox 0.1 djangotoolbox 1.8.0 mongoengine 0.10.6 pip 8.1.2 pymongo 3.3.0 setuptools 27.2.0 Error that I am facing is: File "/home/username/Documents/Projects /ProjectsENV/lib/python3.4/site- packages/django_mongodb_engine/base.py", line 272 raise ImproperlyConfigured, exc_info[1], exc_info[2] ^ SyntaxError: invalid syntax -
Play an audio file from server django
I am planning to make a dropbox like app using django.I could achieve uploading file into server and showing it on the browser.I want users to be able to download or view it.I am trying it for an audio file initially.Ive attached my views.py and index.html file from django.shortcuts import render from django.http import HttpResponse from django.shortcuts import render_to_response from polls.models import Files from os import walk from os.path import isfile, join def index(request): return render(request,"index.html", {}) def upload(request): for x in request.FILES.getlist("files"): def process(f): with open(r'C:\Users\rdoshi\storage\%s ' %f.name , 'wb+') as destination: b = Files(file_name= f.name) b.save() for chunk in f.chunks(): destination.write(chunk) process(x) q = Files.objects.all() return render(request, "index.html", {'q' : q}) def play_file(request) : file=Files.objects.get(id=37) fsock = open(r'C:\Users\rdoshi\storage\%s' %file.file_name, 'r') response = HttpResponse(fsock, content_type='audio/mpeg') return response Index.html <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <script> $(document).ready(function(){ //$("#playlink").click(function(e){ // e.preventDefault(); $.ajax({ method: 'GET', url: '/polls/play_file', //data: {'id': 37}, success: function (recvd_file) { //this gets called when server returns an OK response console.log("success"); var asd = '<audio id="myaudio" src="recvd_file.mp3" preload="auto"></audio>'; document.write(asd); }, }); }); </script> <table id='filetable' border = '1'> {% for i in q %} <tr> <td>{{i.id}}</td> <td> {{i.file_name}} <button type="button" id='playlink' value = 'Download'>Download</button> </td> </tr> {% endfor %} </table> <form method = … -
setting up nginx with django
I have created a django project called "yo" in my /home/ubuntu/test directory. These are my nginx files: nginx/sites-available/yo server { listen 80; server_name 52.89.220.11; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/ubuntu/test/yo/static; } location / { include uwsgi_params; uwsgi_pass unix:/home/ubuntu/test/yo/yo.sock; } } nginx/sites-enabled/yo_nginx.conf: # mysite_nginx.conf # the upstream component nginx needs to connect to upstream django { # server unix:///home/Ubuntu/test/yo/yo.sock; # for a file socket server 127.0.0.1:8001; # for a web port socket (we'll use this first) } # configuration of the server server { # the port your site will be served on listen 80; # the domain name it will serve for server_name 52.89.220.11; # substitute your machine's IP address or FQDN charset utf-8; # max upload size client_max_body_size 75M; # adjust to taste # Django media # location /media { # alias /path/to/your/mysite/media; # your Django project's media files - amend as required # } #location /static { # alias /path/to/your/mysite/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/test/yo/uwsgi_params; # the uwsgi_params file you installed } } /home/ubuntu/test/yo/uwsgi_params: uwsgi_param QUERY_STRING $query_string; … -
Django null option for fields based off CharField/TextField
According to the Django documentation Avoid using null on string-based fields such as CharField and TextField because empty string values will always be stored as empty strings, not as NULL. What about fields that are derived or based off of CharField and TextField (such as GenericIPAddressField) Can we use nulls then? -
In django how can I make the result of the background program as a record and then insert it to mysql
In django, I want to make the result of the program in server as a record and then insert it to the mysql, how can I do this? -
Why do I get IntegrityError during user creation in Django?
I made a view where a school staff can create other users of the school from his panel. But I keep getting IntegrityError. Here is my code: view @transaction.atomic() def create_user(request): if request.method == "POST": username = request.POST['username'] password1 = request.POST['password1'] password2 = request.POST['password2'] form = CreateUserForm(request.POST) if form.is_valid: if password1 == password2: user_created = User.objects.create_user(username=username, password=password2) profile = Profile(user=user_created) <-- ERROR line in my opinion my_profile = Profile(user=request.user) profile.school = my_profile.school profile.save() else: form = CreateUserForm() context = { "form": form, } return render(request, "core/create_user.html", context) Here is the error: IntegrityError at /create/user/ UNIQUE constraint failed: core_profile.user_id -
How to keep django app running in the background within the vagrant?
I have a Ubuntu 14.04 host headless Server. Using root user, I vagrant up a VM that is using VirtualBox. Inside this VM, is a Django Python 3 app. Every time I vagrant up and vagrant ssh this VM, I need to run sudo service gunicorn start. If I exit from the vagrant ssh, and then switch to another user, the app dies. How do I maintain this Django app running from the VM permanently? If the host machine has to reboot for whatever reason, how can the Django app automatically run itself? In summary: how to allow vagrant and the gunicorn inside the VM run for a very long time while I switch between users in the host OS? Is there a way to automatically revive the vagrant and the gunicorn inside, whenever the host OS is rebooted?