Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
wsgi.py is missing and manage.py is there instead
so I'm trying to follow this: http://uwsgi-docs.readthedocs.io/en/latest/WSGIquickstart.html and it says "If the file /home/foobar/myproject/myproject/wsgi.py (or whatever you have called your project) does not exist, you are very probably using an old (< 1.4) version of Django. In such a case you need a little bit more configuration:" but I'm using 1.10.5 version of Django and instead of wsgi.py it has manage.py ...... what should I do to complete that step in the tutorial? should i just use manage.py? -
How do I get django-debug-toolbar to only display on my ip address hosted on python anywhere?
I am trying to use django-debug-toolbar on python anywhere in a django app. It requires me to set my ip address in the settings which i've done, but the toolbar is not showing up. Upon further investigation I found that the django-debug-toolbar is looking for the REMOTE_ADDR attribute. The problem is that the REMOTE_ADDR attribute is not my ip address as normal. It would appear they're using a load balance or something, and so it doesn't actually give the IP that the request is coming from. If I use the IP address from REMOTE_ADDR the toolbar displays, but it displays for EVERY user that goes to the site, not just me. How can I get the IP address of the client making the request? -
Django 1.10 is not detecting changes in my models, and won't create migrations
I'm just getting started with Django. I like to hack at things, so alongside the polls tutorial I'm also building my own experimental application. It has come to pass that I want to change the name of the experimental application and its associated project. In the course of working on that, I decided to drop my current database and start over fresh. Something went wrong, I can't remember what. It's been several hours now, making progress here, googling that there. The situation I now seem to be in is that Django refuses to notice changes in my models.py. Currently, there are no migrations listed for the app when I run manage.py showmigrations, although the app is itself listed. I have tried deleting the migrations directory, changing the contents of the models.py file, and combinations thereof, and also trying out various manage.py commands that looked promising. So far, nothing has worked. So, what might I be doing wrong? Remember that I have changed the name of the app, which includes changing the name of directory it is stored in, as well as the name of the database. Search and replace has been performed on the files in the project and app. … -
How should i implement this database-heavy function?
i'm working on a django application, i'm very new to django and to coding as a whole. I'm working on a voting app where people first submit images and then they get displayed random images to vote on, i'm currently implementing a duplicate report function, where the person chooses two submission displayed, then they return to the database as a duplicate report object, here's how i want it to work: First, the person reports the two duplicates in the template. Then, the two duplicates return as a duplicate report object, this is what the table looks like in my models.py file: class RepReport(models.Model): count = models.IntegerField() oldersub = models.ForeignKey('Submission', on_delete=models.CASCADE, related_name='older_sub') newersub = models.ForeignKey('Submission', on_delete=models.CASCADE, related_name='newer_sub') Then, in the view, if there are no RepReport rows with the selected combination, a new RepReport row is created, containing the combination and with the starting count amount of 1, if there already is one with the combination, the count of that row is increased by 1. After the count of a given RepReport row reaches 5, the submission that was sent the lates gets deleted, and the oldes one's vote count gets converted to the sum of their vote counts divided by … -
How to Install Django with command sudo
I want to install django into my CentOS virtual machine. When I search on the Internet for the solutions, I found tutorial page like this image of downloading command But I when I type the command sudo, and then type Linux virtual machine password, It does not work image of sudo error So I look forward a lot to your help. Thanks in advanced -
Can I filter records I loop through in for loop? Python Template
Currently, I am using a for loop in my Django template like this: {% for item in itemlist.items.all %} <!-- do something --> {% endfor %} Now this works great for looping through all records in my itemlist, but I would like to add a filter, for example let's say that my items have a price and I would like to only loop through the items where the price is >5. How can I achieve this? Is there a way to slice like there is with if statements? I tried something like this but that didn't work" {% for item in itemlist.items.all|price > 5 %} Thanks for the help! -
Benefit of using logging over print() to log information to Papertrail in a Django Heroku app
I have a Django app that I'm hosting on Heroku and logging to Papertrail via the Papertrail Heroku add-on. There are numerous places where I'm logging information to Papertrail directly, currently by: logger = logging.getLogger('papertrail') logger.info('important text') I set up the logging configuration according to this link: import sys LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console': { 'level': 'INFO', 'class': 'logging.StreamHandler', 'stream': sys.stdout, }, }, 'loggers': { 'django': { 'handlers': ['console'], 'level': 'ERROR', }, 'papertrail': { 'handlers': ['console'], 'level': 'INFO', }, }, } Together, this logs to Papertrail like so: Feb 07 06:10:56 app_name app/worker.1: important text However, I noticed that using print('important text') accomplishes the same thing here. Is there any benefit to continuing to use logging over print to log the "important text" in this situation? I read through this article and none of it seemed to apply here. -
Data in child / detail form not displaying
I have the following view with an inlineformset for two models: Orders, the master / parent model LineitemInfo, the detail / child model. FormSet LineFormSet = inlineformset_factory(Orders, LineitemInfo, can_delete=True, exclude = ('ordernotes',)) The edit order_edit view works fine for the master / parent form, but does not display the child records. I can add records to the child form and they will save, they do not display however when I select that record (I checked the database separately). def order_edit(request, pk): order = get_object_or_404(Orders, pk=pk) if request.method == "POST": form = OrderForm(request.POST, instance=order) if form.is_valid(): order = form.save(commit=False) lineitem_formset = LineFormSet(request.POST, instance=order) if lineitem_formset.is_valid(): order.save() lineitem_formset.save() return redirect('order_list') else: form = OrderForm(instance=order) lineitem_formset = LineFormSet(instance=Orders()) return render(request, "orders/order_edit.html", {"form": form, "lineitem_formset": lineitem_formset, }) I just get the empty fields on the child / detail form where the data should display. What am I missing? TIA -
Django form input and action linking
How do you pass form inputs to a form action in Django? I tried this but it's not working <form action="/search?sear_term=q" method="get"> <input type="text" name="q"> <input type="submit" value="Search"> </form> -
Is it appropriate to use Django's abstract classes for simple code reuse?
I am learning Django and writing my first semi-complex model. Many of my tables are made with a similar view style in mind, so many objects have a name, a description and an image. Ex: class Ingredient(models.Model): # Standard to many classes name = models.CharField(max_length=50) description = models.TextField() image_url = models.URLField(max_length=200) # Unique to this class foodgroup = ..... etc. Since name, description and url will be common to many objects (that are otherwise totally different), I was considering defining a base class that each can inherit from: class BaseObjectWithImage(models.Model): # Standard to many classes name = models.CharField(max_length=50) description = models.TextField() image_url = models.URLField(max_length=200) class Meta: abstract = True class Ingredient(BaseObjectWithImage): # Unique to this class foodgroup = ..... etc. My question - which may be closer to a simple OOP Best Practices question - is whether this is a silly use of Django's abstract class, or if is worthwhile for stripping out 3xN lines of code and allowing me to treat most model classes as a generic type. -
Django aggregation with foreign key
I use Question.objects.filter(owner_id=1).annotate(total_votes=Sum('votes')) to compute the total votes number for each question asked by one user. The model is class Question(models.Model): question_text = models.CharField('Question',max_length=200) pub_date = models.DateTimeField('date published') owner = models.ForeignKey(User,default=DEFAULT_USER_ID) class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) The code I use is get from the official documentation.https://docs.djangoproject.com/en/1.10/topics/db/aggregation/ . I don't understand why this doesn't work for me. from django.db import models class Author(models.Model): name = models.CharField(max_length=100) age = models.IntegerField() class Publisher(models.Model): name = models.CharField(max_length=300) num_awards = models.IntegerField() class Book(models.Model): name = models.CharField(max_length=300) pages = models.IntegerField() price = models.DecimalField(max_digits=10, decimal_places=2) rating = models.FloatField() authors = models.ManyToManyField(Author) publisher = models.ForeignKey(Publisher) pubdate = models.DateField() class Store(models.Model): name = models.CharField(max_length=300) books = models.ManyToManyField(Book) registered_users = models.PositiveIntegerField() -
Django: customusate m2m inline or class Meta for through model
If I want change label for InlineAdmin, I shuld set: class Meta: verbose_name = "One" verbose_name_plural = "Many" for Model, but usually it looks good as is. But now I use m2m Inline, and labels look like "Mymodel1-mymodel2 relationships" fore many and "Mymodel1-mymodel2 relationship: MyModel1 mymodel2 object" for one. And I can't translate it, it's really frustrating me. How I can fix this? -
Pip is not installing packages on docker
So i have a docker image created with django cookiecutter and i need to install additional python packages for my app to work. The package im trying to install is django markdown, so i edited the base.txt in the requirements folder, and when i run the command sudo docker-compose -f dev.yml run django pip install -r requirements/base.txt it shows me this output: So it looks like it actually installed the package but if i run it again it looks like its the first time and tries to install it again, also if i try to run my django project i get ImportError: No module named 'django_markdown'. What could be causing this issue and what is the workaround i should do?. I've tried installing different packages even with the sudo docker-compose -f dev.yml run django pip install [package name] command with the same results -
How can I upload mutlple images at same time in Django?
I need upload multiple images in my form but I have just one imagefield, i don't want to have more imagefields the main idea is do a for each in the save method or something like that, but I don't have any idea to do that, please help. This is my model: class Archivos(models.Model): id_archivo = models.AutoField(primary_key=True) id_unidad = models.IntegerField() nombre_archivo = models.CharField(max_length=255, blank=True) imagen = models.ImageField(upload_to='img', null=True, blank=True) this is def post in my view def post(self, request, *args, **kwargs): self.object = self.get_object form = self.form_class(request.POST, request.FILES) if form.is_valid(): form.save() return HttpResponseRedirect(self.get_success_url()) else: print('tas chabelo'); return self.render_to_response(self.get_context_data(form=form)) this is part of my form in a template: the multiple imagefield -
How to use custom Django backend?
I'm developing an app in Django which uses an existing database with created users. I set my database configuration parameters to a PostgreSQL server and I perform my custom queries through "connections" library. The problem comes when I want to use my own table to authenticate users. I saw many tutorials and blog posts and I rewritten my authentication backend. But when I want to use my own table to authenticate users and set sessions, Django's Framework only allows me to use User object. I think these object is linked to Django tables in database and when I want to authenticate an user shows me a message saying the relation "auth_user" doesn't exists. This means that User object is linked to this table. My question is ¿Does exist some method to use my own table with Django Authentication Backend or should I use it? -
Django REST Framework Serializing One to One Models
I'm trying to convert from using Django forms to just using REST Framework serializers for the forms. My models are: class UserDetails(models.Model): user = models.OneToOneField(User, related_name='details', on_delete=models.CASCADE) date_of_birth = models.DateField(default=None, blank=True, null=True) class Employee(models.Model): user = models.OneToOneField(User, related_name='employee', on_delete=models.CASCADE) company = models.ForeignKey(Company, on_delete=models.CASCADE) class Company(models.Model): name = models.CharField(verbose_name='Company Name', max_length=50, unique=True) info = models.CharField(verbose_name='Company Information', max_length=300, blank=True) I have serializers for User, UserDetails, and Company. class UserSerializer(serializers.ModelSerializer): class Meta: model = models.User fields = ('id', 'username', 'email', 'first_name', 'last_name', ) class UserDetailsSerializer(serializers.ModelSerializer): user = UserSerializer() class Meta: model = models.UserDetails fields = ('user', 'date_of_birth') read_only_fields = ('is_verified',) class CompanySerializer(serializers.ModelSerializer): class Meta: model = models.Company fields = ('name', 'info') When users register, they will also specify company information and will become an employee of that company. How do I go about creating a form to create all three records atomically? Here's my attempt: class RegistrationSerializer(serializers.Serializer): details = UserDetailsSerializer(label='') password = serializers.CharField( label='Password', style={'input_type': 'password'} ) password2 = serializers.CharField( label='Password Confirmation', style={'input_type': 'password'} ) company = CompanySerializer() I also want a password confirmation field, which will cause the form to be invalid if it does not match. Django forms had a clean() method which I used to valid the data. I'm not … -
__str__(self): TabError: inconsistent use of tabs and spaces in indentation
So I am just trying Django as a beginner.and got into this trouble.I know this will be another stupid mistake that normally people do.but this is causing me trouble for the big time.as far as I know m not making any tab mistakes.but if I am, I would love to solve this.help me please.thank you in advance. from django.db import models # Create your models here. class Courses(models.Model): created_at=models.DateTimeField(auto_now_add=True) title=models.CharField(max_length=255) description=models.TextField() def __str__(self): return self.title enter image description here -
NodeJS how to set csrf token correctly?
This is a continuation of this question: Rest-auth still reports the error of "CSRF cookie not set", but I've set the csrf The code I used for server.js is: const cookieParser = require('cookie-parser'); const csrf = require('csurf'); app.use(cookieParser()); app.use(csrf({ cookie: true })); app.use(function (req, res, next) { res.cookie('csrfmiddlewaretoken', req.csrfToken()); next(); }); However, the result is The reason I think is that I didn't set the cookie correctly. I tried to remove app.use(csrf({ cookie: true }));, but then it shows an error of csrf misconfigured. In fiddler, there are two tokens, one default, one set by res.cookie('csrfmiddlewaretoken', req.csrfToken());, how can I set the cookie in the correct way? -
How can I install or open in windows, a web application made in python?
I am a beginner in python, I really need help, I am trying to install / open a web application in python, it is scrumdo-master, but I do not get how to do it, a few days ago I was reading a tutorial on how to create a web application In python, but apparently it does not help me enough to open a more extensive application. I hope you can help me. -
Django CSRF failure, using React forms
I'm having a problem with CSRF with Django and React. I have read through the already high number of questions around this, as well as the django docs naturally. I have tried every possible combination of different things that should address the issue but am still struggling with it. Firstly I tried to create a register page, but when I POST to register/ I get CSRF cookie not set, 403. I have gone so far as disabling the CSRF middleware [bad I know, just trying to get somewhere] and I am getting 405s, method not allowed [attempting to post]. I just thought maybe this is something someone has run into before or sounds familiar and could give some guidance? I have tried: - adding the decorator @csrf_exempt, - adding the CSRF to the header of a request, - attaching the whole cookie, - attaching a hidden form field with the token. I am using this seed project: https://github.com/Seedstars/django-react-redux-base if anyone wants to have a look, I've done a bit in React, but not a lot on the Django side, so it isn't far off what's there -
CeleryBeat with Django has an empty schedule
os.environ.setdefault('DJANGO_SETTINGS_MODULE','proj.settings') app = Celery('proj') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() @app.on_after_finalize.connect def setup_periodic_tasks(sender, **kwargs): # Calls test('hello') every 10 seconds. sender.add_periodic_task(10.0, test.s('hello'), name='add every 10') # Calls test('world') every 30 seconds sender.add_periodic_task(30.0, test.s('world'), expires=10) @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) I'm trying to run the 2 periodic tasks. I'm using RabbitMQ. I'm running: celery -A fetchcore_server beat -l debug celery -A fetchcore_server worker -l info This is the output of my debug log: [2017-02-07 22:30:24,013: DEBUG/MainProcess] Setting default socket timeout to 30 [2017-02-07 22:30:24,013: INFO/MainProcess] beat: Starting... [2017-02-07 22:30:24,017: WARNING/MainProcess] /usr/local/lib/python2.7/dist-packages/celery/backends/amqp.py:68: CPendingDeprecationWarning: The AMQP result backend is scheduled for deprecation in version 4.0 and removal in version v5.0. Please use RPC backend or a persistent backend. alternative='Please use RPC backend or a persistent backend.') [2017-02-07 22:30:24,018: DEBUG/MainProcess] Current schedule: [2017-02-07 22:30:24,018: DEBUG/MainProcess] beat: Ticking with max interval->5.00 minutes [2017-02-07 22:30:24,018: DEBUG/MainProcess] beat: Waking up in 5.00 minutes. The schedule looks blank -
ValidationError invalid date format
I am attempting to pull data from a csv file and read the entries into my database. Traceback: File "/home/paragoncdn/webapps/hdcportal/lib/python2.7/Django-1.8.2-py2.7.egg/django/core/handlers/base.py", line 132, in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/paragoncdn/webapps/hdcportal/lib/python2.7/Django-1.8.2-py2.7.egg/django/contrib/auth/decorators.py", line 22, in _wrapped_view return view_func(request, *args, **kwargs) File "/home/paragoncdn/webapps/hdcportal/myproject/contracts/views.py", line 445, in csv_import errors_found = csvtools.process_csv(request, csv_file) File "/home/paragoncdn/webapps/hdcportal/myproject/contracts/csvtools.py", line 143, in process_csv line_sample.save() File "/home/paragoncdn/webapps/hdcportal/lib/python2.7/Django-1.8.2-py2.7.egg/django/db/models/base.py", line 710, in save force_update=force_update, update_fields=update_fields) File "/home/paragoncdn/webapps/hdcportal/lib/python2.7/Django-1.8.2-py2.7.egg/django/db/models/base.py", line 738, in save_base updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) File "/home/paragoncdn/webapps/hdcportal/lib/python2.7/Django-1.8.2-py2.7.egg/django/db/models/base.py", line 822, in _save_table result = self._do_insert(cls._base_manager, using, fields, update_pk, raw) File "/home/paragoncdn/webapps/hdcportal/lib/python2.7/Django-1.8.2-py2.7.egg/django/db/models/base.py", line 861, in _do_insert using=using, raw=raw) File "/home/paragoncdn/webapps/hdcportal/lib/python2.7/Django-1.8.2-py2.7.egg/django/db/models/manager.py", line 127, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/paragoncdn/webapps/hdcportal/lib/python2.7/Django-1.8.2-py2.7.egg/django/db/models/query.py", line 920, in _insert return query.get_compiler(using=using).execute_sql(return_id) File "/home/paragoncdn/webapps/hdcportal/lib/python2.7/Django-1.8.2-py2.7.egg/django/db/models/sql/compiler.py", line 973, in execute_sql for sql, params in self.as_sql(): File "/home/paragoncdn/webapps/hdcportal/lib/python2.7/Django-1.8.2-py2.7.egg/django/db/models/sql/compiler.py", line 931, in as_sql for obj in self.query.objs File "/home/paragoncdn/webapps/hdcportal/lib/python2.7/Django-1.8.2-py2.7.egg/django/db/models/fields/__init__.py", line 710, in get_db_prep_save prepared=False) File "/home/paragoncdn/webapps/hdcportal/lib/python2.7/Django-1.8.2-py2.7.egg/django/db/models/fields/__init__.py", line 1322, in get_db_prep_value value = self.get_prep_value(value) File "/home/paragoncdn/webapps/hdcportal/lib/python2.7/Django-1.8.2-py2.7.egg/django/db/models/fields/__init__.py", line 1317, in get_prep_value return self.to_python(value) File "/home/paragoncdn/webapps/hdcportal/lib/python2.7/Django-1.8.2-py2.7.egg/django/db/models/fields/__init__.py", line 1287, in to_python params={'value': value}, ValidationError: [u"'2/7/2017' value has an invalid date format. It must be in YYYY-MM-DD format."] Migration: migrations.CreateModel( name='Sample', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('sample_number', models.CharField(help_text=b'Depends on the group of samples … -
How django aggregation with foreign key work?
I have a model: from django.db import models class Author(models.Model): name = models.CharField(max_length=100) age = models.IntegerField() class Publisher(models.Model): name = models.CharField(max_length=300) num_awards = models.IntegerField() class Book(models.Model): name = models.CharField(max_length=300) pages = models.IntegerField() price = models.DecimalField(max_digits=10, decimal_places=2) rating = models.FloatField() authors = models.ManyToManyField(Author) publisher = models.ForeignKey(Publisher) pubdate = models.DateField() class Store(models.Model): name = models.CharField(max_length=300) books = models.ManyToManyField(Book) registered_users = models.PositiveIntegerField() I could not understand how the following code work This is from the django official Documentation, in the cheat sheet. https://docs.djangoproject.com/en/1.10/topics/db/aggregation/ What I am trying to do is count the total votes for the following model I use Question.objects.filter(owner_id=1).annotate(total_votes=Sum('votes')) as in the documentation. But this not work for me. class Question(models.Model): question_text = models.CharField('Question',max_length=200) pub_date = models.DateTimeField('date published') owner = models.ForeignKey(User,default=DEFAULT_USER_ID) class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) -
On Django, how to connect to MySQL database on remote server through SSH?
I've looked around, and can't find any answers that specifically address what I'm wondering: In the Mac terminal, I can access a remote server through ssh: ssh [my_username]@[server.host.com] which prompts me for a password, and after I enter my password, it brings me to the remote server. Once I've logged into the remote server, I can access MySQL: mysql -u [other_username] -h [mysql.host.com] -p which prompts me for another password, and after entering the password, I'm in the MySQL console and can show databases located there, etc. We can call the database I'm interested in [database]. My question is, how do I hook up Django, run on my localhost, to [database], so that my app uses that [database]? -
Sorting ForiegnKey Objects in Django
I have a Model that has two main classes. The first is the book model and the second is the page model The pages have a foreign key field to the books which lets me access them but what I am curious about is, how would you implement page numbers such that when creating a new page object, the number is limited only to be within the current length of pages? Furthermore, if it is inserted, how would you shift the following pages down one in number? Right now I just have an integer field that I manually type in the page number but if I want to allow users to add pages themselves later, that won't do. UPDATED: class Textbook(models.Model): founder = models.CharField(max_length=256) title = models.CharField(max_length=256) cover = models.ImageField(upload_to=get_image_path, blank=True, null=True) def __str__(self): return self.title class Page(models.Model): textbook = models.ForeignKey(Textbook,related_name="pages") page_title = models.CharField(max_length = 256) def __str__(self): return self.page_title class Section(models.Model): page = models.ForeignKey(Page,related_name="sections") section_title = models.CharField(max_length=256) text = RichTextField(config_name='awesome_ckeditor') def __str__(self): return self.section_title So above is my model, what I am trying to do is make it so that you can keep track of pages, which are contained in TextBooks, in order. Furthermore, you can insert a new …