Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django and bootstrap modals
I'm stuck developing a Django web which works with bootstrap modals. I have 2 modals, one with a form and another that shows data to user. Can someone explain me how to render the form into the modal and how to send data into a modal? How many views and url I have to write? Thank you! -
How to load dynamic events in correct order inside a static page with AJAX and Django
The context I am currently working on a Website which main purpose is to display statistics. I would like the statistics to be shown in a Facebook-like style but without using Node, meaning most recent statistics are shown first and other statistics are shown one after another, ordered by age. These statistics are inserted periodically inside the Stats table which contains a timestamp and various values concerning a MonitoredObject. This is another table which is linked to Stats and describes what is actually being monitored. What I have from django.db import models class Stats(models.Model): id = models.AutoField(primary_key=True) object = models.ForeignKey('MonitoredObject') timestamp = models.DateTimeField() # more fields class MonitoredObject(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=255) To display the statistics, I am using 2 differents templates: home.html and stats_item.html. My home is displaying the object's single attribute : name, here is how it looks like after rendering: <div class="content"> <div class="title">{{ object.name }}</div> <div class="statistics"></div> </div> Now I would like to populate the <div class="statistics"></div> with a bunch of statistics. Here is what I've been using : function loadData(container, i) { $.ajax({ /* Retrieve the i-th most recent item */ url: '/object/{{ object.id }}/stats/' + i, success: function (data) { container.append(data); } … -
How to configure static and media files with django and nginx?
I have next settings.py on my local server. STATICFILES_DIRS = ( os.path.join(BASE_DIR, "static"), ) STATIC_URL = '/static/' STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static_root") MEDIA_URL = '/media/' MEDIA_ROOT= os.path.join(os.path.dirname(BASE_DIR), "media_root") I know that in production Nginx should handle static and media. Okay. I use gunicorn and supervisor on my prod server. My nginx config: server { listen 8000; server_name 194.87.95.46; access_log /var/log/nginx/example.log; location /static { alias /home/split/static_root/; } location /media { alias /home/split/media_root/; } location / { proxy_pass http://127.0.0.1:8003; proxy_set_header Host $server_name; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } } But nginx doesnt handle static and media, what's the problem? -
How to implement login page of an android app to python django rest api
I am developing an android app which requires login and register and i chosen python as backend language.I am using volley package for networking stuff.I know this could be easier if I use php as backend language.I am able to get the json data from django rest api server.But for login i need to some data to server and query database accordingly to check whether that particular user exists or not in the DB.Please help me. -
Run Django on Apache server on Windows 7
Yes, I know that Windows is not good for running Apache, but I have no choice, since the server runs other things that I don't control.. Here's my problem: I've setted Django on Apache, on localhost (localhost:8000), the application runs perfectly, all libraries are there, etc.. But when I use the Apache host(say localhost/textmining), I have two problems: My static files doesn't work, so none of the bootstrap and javascript of the project works It keeps getting this error on NLTK: LookupError at /select_text Resource [93mpunkt[0m not found. Please use the NLTK Downloader to obtain the resource: [31m>>> import nltk nltk.download('punkt') [0m Searched in: - 'C:\Windows\system32\config\systemprofile/nltk_data' - 'C:\nltk_data' - 'D:\nltk_data' - 'E:\nltk_data' - 'c:\program files (x86)\python36-32\nltk_data' - 'c:\program files (x86)\python36-32\lib\nltk_data' - 'C:\Windows\system32\config\systemprofile\AppData\Roaming\nltk_data' - '' But, as I've said, I've done the nltk.download('punkt') on and admin prompt of command, on localhost it works fine..already restarted the apache and still nothing ;/ I think that the part of static files are missing configuration, but can't find how to do it..so if someone can help me with the static and media configuration on apache, I really would apprechiate. -
Django: Moving data from SQLite to PostgreSQL
I've recently inherited a production codebase for a webapp written using Django. Up until now, the database the project has been using has been the default SQLite3 database, but now that more people are using the app, moving to Postgres is necessary. I've been able to set up an empty postgres database with the project that works fine. The problem I'm encountering is in moving the data from the old project to the new one. I can run python manage.py dumpdata --natural-foreign > dump.json to dump the data, which works fine, but when I switch to postgres in settings.py and run python manage.py loaddata dump.json I get the following error: Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/mnt/d/Code/MCJobTrack/_VENV/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line utility.execute() File "/mnt/d/Code/MCJobTrack/_VENV/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 330, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/mnt/d/Code/MCJobTrack/_VENV/local/lib/python2.7/site-packages/django/core/management/base.py", line 390, in run_from_argv self.execute(*args, **cmd_options) File "/mnt/d/Code/MCJobTrack/_VENV/local/lib/python2.7/site-packages/django/core/management/base.py", line 441, in execute output = self.handle(*args, **options) File "/mnt/d/Code/MCJobTrack/_VENV/local/lib/python2.7/site-packages/django/core/management/commands/loaddata.py", line 60, in handle self.loaddata(fixture_labels) File "/mnt/d/Code/MCJobTrack/_VENV/local/lib/python2.7/site-packages/django/core/management/commands/loaddata.py", line 90, in loaddata self.load_label(fixture_label) File "/mnt/d/Code/MCJobTrack/_VENV/local/lib/python2.7/site-packages/django/core/management/commands/loaddata.py", line 147, in load_label obj.save(using=self.using) File "/mnt/d/Code/MCJobTrack/_VENV/local/lib/python2.7/site-packages/django/core/serializers/base.py", line 173, in save models.Model.save_base(self.object, using=using, raw=True) File "/mnt/d/Code/MCJobTrack/_VENV/local/lib/python2.7/site-packages/django/db/models/base.py", line 738, in save_base updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) File "/mnt/d/Code/MCJobTrack/_VENV/local/lib/python2.7/site-packages/django/db/models/base.py", … -
Django 1.8. Can't show an image in form
I'm using this package https://github.com/tomwalker/django_quiz to make a web quiz app. I need to add images to the multiplechoice answers. So, I added to the Answers model: image = models.ImageField(upload_to='uploads/%Y/%m/%d', blank=True, null=True, verbose_name=_("Image")) Images are uploading and saving into the DB. The part that shows choosable answers are shown in template like this: {% for answer in form.answers %} <li class="list-group-item"> {{ answer }} </li> {% endfor %} I changed it to: {% for answer in form.answers %} <li class="list-group-item"> {{ answer }} <img src="{{ answer.image.url }}" alt="" /> </li> {% endfor %} But it's doesn't work. It renders This is forms.py: class QuestionForm(forms.Form): def __init__(self, question, *args, **kwargs): super(QuestionForm, self).__init__(*args, **kwargs) choice_list = [x for x in question.get_answers_list()] self.fields["answers"] = forms.ChoiceField(choices=choice_list, widget=RadioSelect) And this is model: def get_answers_list(self): return [(answer.id, answer.content) for answer in self.order_answers(Answer.objects.filter(question=self))] -
Django migration sql for conditional triggers
I want to create a trigger that only inserts into table when the condition is met. I've tried using various combinations of IF/BEGIN/END and WHERE, but Django returns me an SQL syntax error each time. Here, type_user_id refers to the person who triggers the like, and user_id refers to the person who receives the notification. It should only trigger when they are not the same person. operations = [ migrations.RunSQL( "DROP TRIGGER like_notification", """ CREATE TRIGGER like_notification AFTER INSERT ON user_likes_article FOR EACH ROW IF (select user_id from channel WHERE channel_id IN (SELECT channel_id FROM article WHERE article_id = NEW.article_id)) <> NEW.user_id BEGIN INSERT INTO notification (type, type_id, article_id, is_read, type_user_id, user_id) VALUES ('like', NEW.article_id, NEW.article_id, false, NEW.user_id, (SELECT user_id from channel WHERE channel_id IN (SELECT channel_id FROM article WHERE article_id = NEW.article_id) ) ) END; """ ) ] and CREATE TRIGGER like_notification AFTER INSERT ON user_likes_article FOR EACH ROW BEGIN DECLARE @user_same Boolean; SELECT 1 into @user_same FROM channel WHERE channel_id IN (select channel_id FROM article where article_id = NEW.article_id) AND user_id = NEW.user_id; IF @user_same <> 1 THEN INSERT INTO notification (type, type_id, article_id, is_read, type_user_id, user_id,) VALUES ('like', NEW.article_id, NEW.article_id, false, NEW.user_id, ( SELECT user_id from channel … -
what is the use of django DRF Mixins, where i can use it in my django projects
What is the best use case for Django Rest Framework(DRF) Mixins?DRF documentation. This Documentation is giving just an overview. So please give me a code snippet or an example where Mixins plays a Major role to solve the problem. -
How access a context value from a variable in django template
I have a Question model that I am passing as a context to the template class Question(models.Model): possible_answer1 = models.TextField( 'Possible Answer 1', max_length=1000, default='none' ) possible_answer2 = models.TextField( 'Possible Answer 2', max_length=1000, default='none', blank=True ) possible_answer3 = models.TextField( 'Possible Answer 3', max_length=1000, default='none', blank=True ) possible_answer4 = models.TextField( 'Possible Answer 4', max_length=1000, default='none', blank=True ) possible_answer5 = models.TextField( 'Possible Answer 5', max_length=1000, default='none', blank=True ) possible_answer6 = models.TextField( 'Possible Answer 6', max_length=1000, default='none', blank=True ) I can access all the answer object no problem if I use {{ context.this_question.question.possible_answer1 }} {{ context.this_question.question.possible_answer2 }} . . {{ context.this_question.question.possible_answer6 }} The problem is that I don't need all 6 answers to be displayed all the time so I was trying to build for loop that would only dispay what I need at a certain time based on the following thread using the with tag How to concatenate strings in django templates?1 . In the example below mylist contain four elements so I tried this {% for x in mylist %} {% with possible_answer='context.this_question.question.possible_answer'|add:forloop.counter %} {{ possible_answer }} {% endwith %} {% endfor %} In the hope that it would generate {{ context.this_question.question.possible_answer1 }} {{ context.this_question.question.possible_answer2 }} {{ context.this_question.question.possible_answer3 }} {{ context.this_question.question.possible_answer4 … -
Is there a way to elegantly "swap" rows in all foreign key and many to many fields in django?
I have a class let's call it Entity it's a container for a label and a type and then I have many other models like Store, Purchase... And they have a relationship like so: class Store(Model): store_name = TextField() entities = ManyToManyField(Entity) class Purchase(Model): datetime = DatetimeField(auto=True) entity = ForeignKeyField(Entity) In this case, say that I have an entity that I end up wanting to "swap" for instance, at some time I had "CocaCola" and then I have "Coca Cola", the user decides hey these two are the same, let's "merge them", effectively what I need to do is delete CocaCola or Coca Cola and swap all the keys out so.... for p in Purchase.objects.filter(entity=cocacola_entity): p.entity = coca_cola_entity p.save() for s in Purchase.objects.filter(entities=cocacola_entity): s.entities.remove(cocacola_entity) s.entities.add(coca_cola_entity) s.save() cocacola_entity.delete() Is there a better way to handle this in a global context? I.e. "Django magically fetch me EVERYTHING with this row as a foreign key and swap it with the other one) -
what is the point of 'timeline' in array or param for get_news_feed?
I went through all tutorials and docs which stream-django provided. And there was one thing that I could't understand. I can't find the differences between these feed_manager methods. # (1) feed = feed_manager.get_news_feed('timeline’, request.id) # (2) feed = feed_manager.get_news_feed(request.id)[‘timeline’] # (3) feed = feed_manager.get_news_feed(request.id) Could you explain the difference? Are they doing exactly same thing? timeline means flat feed, then why do we put timeline in param? Thank you -
Gcloud app deploy. Stopping Master
I am trying to deploy my app to the app engine but for some reason, I can't do so. My logs says Shutting down master Reason: worker failed to boot I think it has something to do with gunicorn. How do I go about this? -
Django writing view with sudomain
With my (Django v 1.17) project I am using django-subdomains. I have no problem to call index view and when I open my url https://subdomain.domain.com I will get index.html. My issue that I wrote a new view called example for the sub-domain but when I open the url https://subdomain.domain.com/exmaple I will get error Page not found (404). Hete is my code: settings.py INSTALLED_APPS = [ 'subdomain' ] SUBDOMAIN_URLCONFS = { 'subdomain': 'subdomain.urls', } subdomain/urls.py from django.conf.urls import url, include from . import views from django.contrib.auth import views as auth_views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^$example', views.example, name='example'), ] subdomain/views.py from django.shortcuts import render from django.template import loader from django.http import HttpResponse def index(request): template = loader.get_template('subdomain/index.html') return HttpResponse(template.render()) def example(request): template = loader.get_template('subdomain/example.html') return HttpResponse(template.render()) Error: Page not found (404) Request Method: GET Request URL: https://subdomain.domain.com/example Using the URLconf defined in subdomain.urls, Django tried these URL patterns, in this order: 1. ^$ [name='index'] 2. ^$example [name='example'] The current path, econ, didn't match any of these. Please Advice how to fix this issue and write view for sub-domain. Here is the documents for the django-subdomains library django-subdomains -
Get error in django project?
Get this error. NoReverseMatch at /account/login/ Reverse for 'dashboard' not found. 'dashboard' is not a valid view function or pattern name This is my github project https://github.com/Loctarogar/Django-by-Example -
Configuration Logging in Django for print in console
I am following these instructions from https://docs.djangoproject.com/en/1.11/topics/logging/ In view.py I added: import logging logger = logging.getLogger(__name__) def update(request): if request.method == 'POST': logger.info('test') and settings.py (because I want to print info in console) LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console': { 'level': 'INFO', 'class': 'logging.StreamHandler', 'stream': sys.stdout }, }, 'loggers': { 'django': { 'handlers': ['console'], 'level': 'INFO', 'propagate': True, }, }, } -
unable to upload image via ModelForm in django
when i try to submit my form it said "This field is required." for an image even though i provide the image and other details to it. forms.py file from django.forms import ModelForm from .models import Status class CreatePost(ModelForm): class Meta: model=Status fields = ["username","text","privacy","image"] models.py file class Status(models.Model): title=models.CharField(max_length=20,default="updated status") username = models.ForeignKey('User',on_delete=models.CASCADE) #username = models.CharField(max_length=20) text = models.TextField(blank=True, null=True) image = models.ImageField(upload_to="media/image",null=True) time = models.DateTimeField(auto_now=True) privacy = models.CharField(max_length=5, blank=True, null=True) gid = models.IntegerField(blank=True, null=True) dp = models.SmallIntegerField(blank=True, null=True) class Meta: #unique_together = (('username', 'dp'),) #managed = False db_table = 'status' view.py def create_post(request): form=CreatePost(request.POST or None) if request.method=="POST": if form.is_valid(): instance=form.save(commit=False) instance.time=time.time() instance.save() return redirect('post',) return render(request,"uposts/createpost.html",{'form':form}) createpost.html {% extends "friendsbook/structure.html" %} {% block content %} <form action="" method="post"> {%csrf_token %} {{ form.as_p }} <input type="submit" value="Save"> </form> {% endblock %} look what it said after clicking on save button enter image description here i am only taking 4 fields in form because all other fields can be null.For time field i took care of that in views.py by giving the time there. Please help me.I tried everything by myself but nothing helped !. -
Django doesnt show media
Production server doesn't show media. settings.py: MEDIA_URL = '/media/' MEDIA_ROOT= os.path.join(os.path.dirname(BASE_DIR), "media_root") ways (venv) split@ubuntu:~$ ls logs media_root mysite requirements.txt static_root venv (venv) split@ubuntu:~$ cd media_root/ (venv) split@ubuntu:~/media_root$ ls 1 2 None (venv) split@ubuntu:~/media_root$ inside None there are pictures I go to ip/media/None/dd.jpg and got Not Found The requested URL /media/None/dd.jpg was not found on this server. All work good on the local machine. -
I dont know what is wrong with my django
I dont know what is wrong, and I am desperates with no sleep int two days because of this error. I dont know where does it come from, and it wouldn let me know what did i do wrong. for your information I am learning using django with python, my version of django is 1.11 and my version of python is 2.7 . Please help me, this is what i got from my code Traceback (most recent call last): File "./manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/juunnn/env/lib/python3.5/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/home/juunnn/env/lib/python3.5/site-packages/django/core/management/__init__.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/juunnn/env/lib/python3.5/site-packages/django/core/management/base.py", line 294, in run_from_argv self.execute(*args, **cmd_options) File "/home/juunnn/env/lib/python3.5/site-packages/django/core/management/base.py", line 345, in execute output = self.handle(*args, **options) File "/home/juunnn/env/lib/python3.5/site-packages/django/core/management/commands/check.py", line 68, in handle fail_level=getattr(checks, options['fail_level']), File "/home/juunnn/env/lib/python3.5/site-packages/django/core/management/base.py", line 374, in check include_deployment_checks=include_deployment_checks, File "/home/juunnn/env/lib/python3.5/site-packages/django/core/management/base.py", line 361, in _run_checks return checks.run_checks(**kwargs) File "/home/juunnn/env/lib/python3.5/site-packages/django/core/checks/registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "/home/juunnn/env/lib/python3.5/site-packages/django/core/checks/urls.py", line 14, in check_url_config return check_resolver(resolver) File "/home/juunnn/env/lib/python3.5/site-packages/django/core/checks/urls.py", line 28, in check_resolver warnings.extend(check_resolver(pattern)) File "/home/juunnn/env/lib/python3.5/site-packages/django/core/checks/urls.py", line 30, in check_resolver warnings.extend(check_pattern_name(pattern)) File "/home/juunnn/env/lib/python3.5/site-packages/django/core/checks/urls.py", line 120, in check_pattern_name if pattern.name is not None and ":" in pattern.name: TypeError: argument of type 'function' is not iterable See? it would not let … -
how constantly run a script beside django
I have a Django website running and i am looking for a way to run a script that constantly fetch some data from the Internet and insert them into my Django app database. how can i keep script running as long as server is up ? (no need to start it manually - and don't want to stop it at all!!) i guess celery is not what i want !?! ,and how can i use Django ORM in this script for inserting data into db? i tried threading but think its should be started by calling the script or .. -
ValueError while making db migrations in django
I am new to django and i tried changing tag field from char field to TaggableManager() models.py class UserBookmark(models.Model): user = models.ForeignKey(User) bookmark = models.URLField() tag = TaggableManager() def __str__(self): return '%i %s %s'%(self.id,self.user,self.bookmark) when i run python manage.py migrate, i get this error: ValueError: Cannot alter field bookmark.UserBookmark.tags into bookmark.UserBookmark.tags - they are not compatible types (you cannot alter to or from M2M fields, or add or remove through= on M2M fields) How can i remove this error? -
Django Generic Model Formsets
So I have a site where users are capable of registering devices and then registering commands to those devices. These commands have an associated widget (button, slider, etc) that determine the unique properties that the command has. I am trying to figure out the most generic way to use the model formsets in my application. I have things working, where I create a model_formset for each ModelForm, and get data from each model to place in the formset, and then show it in my template. What I would really like to do is something like this: command_formset = modelformset_factory(Command, extra=0, fields='__all__') formset = command_formset(queryset=Command.objects.filter(device_id=device_id)) Where I get all of my commands (which returns both buttons and sliders) and then make a single command_formset, which has all command objects. In this case it does part of what I am looking for, where I can query my model and get all button and slider commands, but the formset only includes the fields from command - so the min and max value for the slider are lost. Is something like this possible? Here is my more complete code: Models class Command(models.Model): command_name = models.CharField(max_length=100) command = models.CharField(max_length=100) command_url = models.CharField(max_length=100) command_type = models.CharField(max_length=100) … -
22003 8115 error with overflow bigint id
My code runs good in a single test. The id starts with 1 and increment with 1. However when I test the whole run in django, I've got this error. For example an id 601193234094856941 that was inserted. In the whole run I have not more than 10000 inserts. We only have this problem in our development environment. We have an work around but we want to understand how it works and a solution. ('22003', '[22003] [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Arithmetic overflow error converting expression to data type int. (8115) (SQLExecDirectW)')", -
Handling many admins in django?
If a company has departments A, B, C, D ...and each have to have a admin different . Only admins of the particular department can create, update and delete the information of their respective departments. My question is how to implement to create API ? -
Check for duplicates in pandas df from Django db
I have a Django db that I want to only add to if it the new input is different from the data already in there. I have a function to check for duplicate rows that should: read the current db put the current db into a pandas dataframe current_df if that dataframe is empty, it should just return the whole of the new input weatherstats_df that was passed to the function for checking without changing it if the df current_df is not empty, try an inner merge with weatherstats_df and return that if that doesn't work, return an empty df I'm getting a problem where my function is changing the data at the first stage, when it should just pass back an unaltered df. The function add_to_db(weatherstats_df) should be calling checkforduplicates(weatherstats_df), but when there's nothing in my db it should be returning the unaltered db. def checkforduplicates(weatherstats_df): qs = WeatherStatistics.objects.all() current_df = read_frame(qs) if current_df.empty: return weatherstats_df else: current_df = current_df.drop(current_df.columns[0], axis=1) print(current_df) try: weatherstats_df = pd.merge(current_df,weatherstats_df, how='inner') return weatherstats_df except: weatherstats_df = pd.DataFrame() return weatherstats_df def add_to_db(weatherstats_df): print(weatherstats_df) weatherstats_df = checkforduplicates(weatherstats_df) if not weatherstats_df.empty:... What am I doing wrong?