Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to integrate Django into an existing database without using models
I have been asked to provide a web interface to access some scientific data which is being saved in a laboratory. The data are stored in folders, each containing some number of FITS files, and the application collecting the data is already written and functional. The web interface I am supposed to implement should have the following features: View all the data taken so far; Allow the user to make queries; File downloading; Only read-only operations are allowed. I know Django quite well and would like to use it. However, this kind of application is quite different from what I am used to. Usually a Django application implements models which are linked to a database, and this database is completely managed by Django itself. In this case, the database would be the plain tree of folders, which is being modified by an external application while Django is running. Can Django be adapted to this task, or should I turn to other more low-level solutions? (e.g., microframeworks like Flask) -
In what sequence Model.save() and ModelForm.save() called
I understand that both models.Model and forms.ModelForm both contain .save() method that you can override. My question is how and when are they used to save an object and in what sequence. -
Django: why Using a custom user model when starting a project is not made compulsory?
I was working on a project and after the mid way, i wanted to work on the users. That time i decided to use email as the login. I found that custom user migration should be done only in the start of the project. Using a custom user model when starting a project If you’re starting a new project, it’s highly recommended to set up a custom user model, even if the default User model is sufficient for you. This model behaves identically to the default user model, but you’ll be able to customize it in the future if the need arises: https://docs.djangoproject.com/en/dev/topics/auth/customizing/#using-a-custom-user-model-when-starting-a-project So why such a thing should not be made as compulsory thing before one starts a project. Assuming I am in the middle of a project. How can i transfer all the database data to my new project with custom_user. -
Redirect user from login page
When the user presses on login, nothing happens. I would like to redirect them to calculator.html where i intend to make some entry fields to obtain parameters from the user to calculate a certain value at the end. Django 1.11.11 Python 3.6.4 Thanks. urls.py from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'', include('webapp.urls')), ] views.py from django.shortcuts import render, redirect from django.contrib.auth.forms import AuthenticationForm from django.contrib.auth.decorators import login_required # Create your views here. def login_view(request): if request.method == 'POST': form = AuthenticationForm(data=request.POST) if form.is_valid(): # log the user in user = form.get_user() login(request, user) return redirect('/calculator/') else: form = AuthenticationForm() return render(request, 'registration/login.html', { 'form': form }) @login_required(login_url="/login/") def calculator(request): return render(request, 'webapp/calculator.html') app urls.py from django.conf.urls import url from . import views from django.contrib.auth.views import login from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.conf.urls.static import static from django.conf import settings from django.views.generic.base import RedirectView urlpatterns = [ url(r'^login/$', views.login_view, name='login'), url(r'^calculator/$', views.calculator, name='calculator'), url(r'^.*$', RedirectView.as_view(pattern_name='login', permanent=False)), ] urlpatterns += staticfiles_urlpatterns() urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) login.html {% extends 'webapp/base_layout.html' %} {% block content %} <h1>Log in</h1> <p></p> <p></p> <form class="site-form" action="/registration/login" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Login" /> </form> {% endblock … -
checking celery task queue on local running django heroku application
I am running a django app. I use redis as a broker for celery. I boot redis separately with redis-server /usr/local/etc/redis.conf Once redis has started, I run my Django code in the CLI of heroku heroku local I have tasks that I can process, the set-up works I would like to monitor the tasks from the "bash"/"Shell"/"console" to see which tasks are running. I have some scheduled tasks but no idea if they eventually get scheduled or not. probably this is some kind of one-liner but I have no clue where to start looking for it. What i have tried: reading heroku documentation on the shell and running heroku locally I have tried to run a separate python shell inside the virtualenv where I run the django app I also tried accessing tasks from a separate shell but that didn't worked out either thanks for the help! -
How to get an image from HttpRequest in Django without using HTML form?
I picked up Django just a few days ago, so I only have a very limited knowledge of how it works, and I can't figure out how to get file a POST. All tutorials, SO questions, etc. focus on images being uploaded from HTML forms, then saving those files, or using Django rest framework and so on, however I need none of those things. I use Postman to send an image to Django, so naturally HttpRequest.FILES dict is empty. The file is encoded in HttpRequest.body as a byte stream. In theory, I could parse that byte stream into an image, but that would require accounting for different image headers(png, jpg, gif...) and also cut out irrelevant parts of the stream, such as Content-Disposition: form-data; name=""; filename="image.png"\r\nContent-Type: image/png. which is quite annoying to work with. Is there simply no other way to access the file in the HttpRequest that would result in an actual image object, say PIL.Image? -
Heroku generates Server Error (500) in Django application
I have deployed a Django application on Heroku and attached PostgreSQL database to it successfully. On running the application I have observed that it behaves unexpectedly Sometimes it produces Server Error (500) Sometimes only half of the page is loaded Sometimes jQuery ajax call gets failed all these problems only appear on Heroku, when I run the same application on my system locally it runs smoothly without any problem. These errors are appearing only on 2 pages of my projects all other pages work fine. To overcome this problem, I followed these posts Post 1, Post 2, Post 3, Post 4 and tried changing the parameters in settings.py but nothing worked. settings.py import os #from .base import import dj_database_url # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '***' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [".herokuapp.com", "127.0.0.1"] # Application definition INSTALLED_APPS = [ 'blog', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', … -
Django Action RedirectView need to go with querystring
I have a RedirectView where action redirects specific Url. But I need to filter and click action also. So when I filter the items and click action it redirects me to a specific page. But I want now that action will redirect me to current page always no matter what happens. If the current page is included in query string it redirects me with a query string. If there is no query string its redirect me without the query string, But on the current page. I am using Django FSM for state management and when I click action it changes the state. Here is my code of redirect. class OrderStateChangeView(LoginRequiredMixin,RedirectView): state_change_method: str = None reverse: str = 'orders:manager-orderfilter-search' @property def reverse_kwargs(self): return {} def get_redirect_url(self, *args, **kwargs): obj = get_object_or_404(Order, pk=self.kwargs['pk']) self.obj = obj try: getattr(obj, self.state_change_method)() obj.save() except: messages.add_message( self.request, messages.ERROR, extra_tags='alert alert-error', message='Unable to process your request.' ) return reverse(self.reverse, kwargs=self.reverse_kwargs) -
Django Rest framework conditional delete
I want to add some condition when DELETE data. Here is my models.py and serializers.py [serializers.py] class articleSerializer(serializers.ModelSerializer): userkey = serializers.CharField(write_only=True) password = serializers.CharField(write_only=True) class Meta: model = article fields = ('articleNo', 'content', 'date', 'userkey', 'password') [models.py] class article(models.Model): articleNo = models.AutoField(primary_key=True) userkey = models.CharField(max_length=50, null=False) content = models.CharField(max_length=500, null=False) password = models.CharField(max_length=20, null=False, default='1234') date = models.DateTimeField(auto_now_add=True) For example, below data is in database. | articleNo | content | date | userkey |password| --------------------------------------------------------------------------------- | 33 | test article | 2018-03-11 05:00:15.428661 | a1b2c3d4 | 1234 | When "DELETE" method request, I want to compare request's password and article's password. If it is same, data will be deleted. Refer to document, I think I have to override def delete(). But I don't know exactly what should I do. How can I solve this issue? Thanks. -
How to filter 404 errors getting reported in rollbar
Is there any way to filter 404 error reporting in rollbar? I am using rollbar (0.13.18) in django (1.11). -
How to save ArrayField as set in Django
The goal is removing of duplicates from list field while saving model. For example: m = MyModel.objects.create( array_field=['123','123'], ) m.array_field # ['123'] I tried to overwrite save but it doesn't work class MyModel(models.Model): array_field = ArrayField(models.CharField(max_length=5)) def save(self, *args, **kwargs): if self.array_field: self.array_field = list(set(self.array_field)) super(MyModel, self).save(*args, **kwargs) How can I do this? -
Why other docker containers do not see the accepted migrations?
docker-compose.yml version: '3' services: # Django web server web: volumes: - "./app/back:/app" - "../front/public/static:/app/static" - "./phantomjs-2.1.1:/app/phantomjs" build: context: . dockerfile: dockerfile_django #command: python manage.py runserver 0.0.0.0:8080 #command: ["uwsgi", "--ini", "/app/back/uwsgi.ini"] ports: - "8080:8080" links: - async - ws_server - mysql - redis async: volumes: - "./app/async_web:/app" build: context: . dockerfile: dockerfile_async ports: - "8070:8070" # Aiohtp web socket server ws_server: volumes: - "./app/ws_server:/app" build: context: . dockerfile: dockerfile_ws_server ports: - "8060:8060" # MySQL db mysql: image: mysql/mysql-server:5.7 volumes: - "./db_mysql:/var/lib/mysql" - "./my.cnf:/etc/my.cnf" environment: MYSQL_ROOT_PASSWORD: root MYSQL_USER: user_b520 MYSQL_PASSWORD: buzz_17KN MYSQL_DATABASE: dev_NT_pr MYSQL_PORT: 3306 ports: - "3300:3306" # Redis redis: image: redis:4.0.6 build: context: . dockerfile: dockerfile_redis volumes: - "./redis.conf:/usr/local/etc/redis/redis.conf" ports: - "6379:6379" # Celery worker celery: build: context: . dockerfile: dockerfile_celery command: celery -A backend worker -l info --concurrency=20 volumes: - "./app/back:/app" - "../front/public/static:/app/static" links: - redis # Celery beat beat: build: context: . dockerfile: dockerfile_beat command: celery -A backend beat volumes: - "./app/back:/app" - "../front/public/static:/app/static" links: - redis # Flower monitoring flower: build: context: . dockerfile: dockerfile_flower command: celery -A backend flower volumes: - "./app/back:/app" - "../front/public/static:/app/static" ports: - "5555:5555" links: - redis dockerfile_django FROM python:3.4 RUN mkdir /app WORKDIR /app ADD app/back/requirements.txt /app RUN pip3 install -r requirements.txt … -
How To Create A Form In Django That Combines Choice and Text Data
I am working with Django to create a form for a restaurant app where I would need a user to first select type of product that it has from a list and enter the price they would like to have each item set to. This data will then be passed to an API. Right now I have something like this: class Drinks(models.Model): TYPE = ( ('Sizes', ( ('small', 'Small'), ('medium', 'Medium'), ('large', 'Large') )), drink_size = models.CharField(max_length=1, choices=TYPE) I need for the restaurant to be able to select the size of the drink and then place a value on each drink size. So I think I would need a checkbox and a way to record the value for each size. If you have any idea on how to do this, It would truly appreciated. -
Django Rest framework except specific column
I want to exclude specific column in rest framework only for view data. (not for put data) [models.py] class article(models.Model): articleNo = models.AutoField(primary_key=True) userkey = models.CharField(max_length=50, null=False) content = models.CharField(max_length=500, null=False) password = models.CharField(max_length=20, null=False, default='1234') date = models.DateTimeField(auto_now_add=True) [serializers.py] class articleSerializer(serializers.ModelSerializer): class Meta: model = article fields = ('articleNo', 'userkey', 'content', 'password', 'date') After I change fields = ('articleNo', 'content', 'date') from serializers.py, Only articleNo, content, date will be show in rest framework. But, When I PUT data to article, It doesn't inserted properly. After insert data, MySQL data is below. articleNo|content | date |userkey |password 37 | Test | 2018-03-13 08:01:07.424564 | | 1234 userkey is blank and password is default value. Maybe I have to modify serializers.py I think, But I don't know how to fix it. How can I insert data properly? -
How to save model form Data(User input) into a csv or dict in Django
I am trying to set up a Website for Employee Schedulling with Django. Since i am new to Web development, I run into some problems. I need to pass information to a solver using pyomo. For this employees should be able to pass information his availability through a model form. The information has to be saved like this: Available ={(“Employee name”, “shift”, “day”): 0, (“Employee name”, “shift”, “day”): 0, (“Employee name”, “shift”, “day”): 1} 0 means that the employee is not available on that shift on that day and 1 means he is. Right now I get my data from a csv and transform it into a dict using pandas. Is there any way to save the passed information as a csv or a dict into a database? -
Django CSS not working
settings.py STATIC_ROOT = 'static/' STATIC_URL = '/static/' STATICFILES_DIRS = ['guide/static/css', 'guide/static/js', ] base.html {% load staticfiles %} ... <link href="{% static bootstrap.css %}" rel="stylesheet" type="text/css" media="all" /> <link rel="stylesheet" href="{% static flexslider.css %}" type="text/css" media="screen" Department="" /> <link href="{% static services.css %}" rel="stylesheet" type="text/css" media="all" /> <link href="{% static ziehharmonika.css %}" rel="stylesheet" type="text/css"> <link href="{% static JiSlider.css %}" rel="stylesheet"> <link href="{% static style.css %}" rel="stylesheet" type="text/css" media="all" /> <!-- font-awesome icons --> <link href="{% static font_awesome.css %}" rel="stylesheet" type="text/css" media="all"/> Here is the project structure: guide - guide - guideapp - templates - base.html - index.html - static - css - js - fonts - db.sqlite3 - manage.py Here, index extends base.html. The content shows up, but the css does not. -
django hide form after submit
Hello i want to have a link form in my post but i want to have only one link per post so if some user add a link i want the form disabled .How can i achieve this ? model and view --> models.py class Link(models.Model): post = models.ForeignKey(Post,related_name='links',on_delete=models.CASCADE) url_link = models.URLField() created = models.DateField(auto_now_add=True) updated = models.DateField(auto_now=True) active = models.BooleanField(default=True) views.py if request.method == 'POST': link_form = LinkForm(data=request.POST) if link_form.is_valid(): new_link = link_form.save(commit=False) new_link.post =post new_link.save() else: link_form=LinkForm() -
Get requests are not pulling latest data from postgresql: Django and apache
I am running a django project where users are entering data through 11 different forms. It is not mandatory to fill all the 11 forms. Each form has a view data page where multiple entries submitted by the user through that form are made visible. For example, say, there are Form1, Form2, ..., Form11 forms. Suppose User1 creates 3 entries through form1, then the ViewForm1Data will show 3 entries to User1. Similarly, there is also a view page for all the data entered by a specific user. For example, if User1 creates 3 entries using Form1, 2 entires using Form3 and 5 entries using Form6, all the entries will be shown to User1 on single page, ViewAllDataUser1. Now the problem is, when user creates an entry, it is not shown immediately to the user. The page requires reload. And if ViewForm1Data is reloaded and entries are seen, it is not guarantee that the ViewAllDataUser1 page will show the entry. This page also requires reload. There seems no problem while posting the data but getting latest data is not working immediately. The project is running since 6 years and I have never faced this problem. Both Postgres and Apache are not … -
Error about bool not being callable in django project [duplicate]
This question already has an answer here: django request.user.is_authenticated is always true? 3 answers I have a djang project and I am trying to use the django authentication within my application. I am getting the following error TypeError at / 'bool' object is not callable Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 2.0.2 Exception Type: TypeError Exception Value: 'bool' object is not callable Exception Location: /Users/omarjandali/Desktop/MySplit/mysplit/users/views.py in user_home, line 283 Python Executable: /Users/omarjandali/anaconda3/envs/MySplit/bin/python for the following code traceback: /Users/omarjandali/Desktop/MySplit/mysplit/users/views.py in user_home if request.user.is_authenticated(): does anyone know why this is happening -
insert query using django-models
DB structure User, user has multiple events, events has multiple attendees. User Model: from django.db import models class User(models.Model): email = models.CharField(max_length=100, unique=True, null=True) firstname = models.CharField(max_length=100, null=True) lastname = models.CharField(max_length=100, null=True) org_url = models.CharField(max_length=100, null=True) office_username = models.CharField(max_length=100, null=True) office_email = models.CharField(max_length=100, null=True) isdeleted = models.BooleanField(default=False) createdon = models.DateTimeField(auto_now_add=True, null=True) modifiedon = models.DateTimeField(auto_now=True, null=True) Event Model: from django.db import models from .user import User class OEvent(models.Model): frk_user = models.ForeignKey(User, on_delete=models.CASCADE) o_event_id = models.CharField(max_length=250, null=True) location = models.CharField(max_length=250, null=True) starts_at = models.CharField(max_length=50, null=True) ends_at = models.CharField(max_length=50, null=True) event_title = models.CharField(max_length=150, null=True) isdeleted = models.BooleanField(default=False) createdon = models.CharField(max_length=50, null=True) modifiedon = models.CharField(max_length=50, null=True) Attendee Model: from django.db import models from .o_events import OEvent class OEventAttendee(models.Model): frk_o_event = models.ForeignKey(OEvent, on_delete=models.CASCADE) email = models.CharField(max_length=200, null=True) name = models.CharField(max_length=200, null=True) I can insert events against a user like this: user.oevent_set.create( o_event_id=nData['Id'], location=nData['Location']['DisplayName'], starts_at=startdt, ends_at=enddt, event_title=nData['Subject'], isdeleted=False, createdon=createdon, modifiedon=modifiedon ) What is the best, easy, short way to add attendees like this? I'm assuming that there must be something We can add event_attendees list = attendees array after modifiedon field. But couldn't find anything like that. -
Django unable to access user profile data from User object
I have a Profile model like this: class UserProfile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, related_name='profile') about = models.TextField() When I try to access UserProfile data from User instance I get this error: In [1]: In [1]: from django.contrib.auth.models import User In [5]: u = User.objects.all()[0] In [6]: u Out[6]: <User: admin> In [13]: u.profile --------------------------------------------------------------------------- RelatedObjectDoesNotExist Traceback (most recent call last) <ipython-input-13-679bed70444a> in <module>() ----> 1 u.profile ~/project/djangoedu/env/lib/python3.5/site-packages/django/db/models/fields/related_descriptors.py in __get__(self, instance, cls) 402 "%s has no %s." % ( 403 instance.__class__.__name__, --> 404 self.related.get_accessor_name() 405 ) 406 ) RelatedObjectDoesNotExist: User has no profile. In [14]: u.author --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-14-327f8c8449fd> in <module>() ----> 1 u.author AttributeError: 'User' object has no attribute 'author' In [15]: -
Can I send two forms as a variable from django render function?
So a page has two buttons. One button should take us to one form and the other to a different form. How we are doing it right now is we are passing the forms structure from the render function- return render(request, 'abc.html', {'contacts': contacts, 'form': form}) I don't think I can pass a 'form2' in render but I need something like that. The html reference is- {% include "form_abc.html" with form_title="Edit" form_btn="Save" form_id="edit" ajax="True" %} Please let know if you have any inputs. -
Django - Add attribute to serializer and order list based on Foreign Key
what I'm trying to get a data based on foreign keys. Let's say I have these models: # Model class Player(models.Model): name = models.CharField(max_length = 64) class Game(models.Model): score = models.IntegerField() player = models.ForeignKey('Player', models.DO_NOTHING, related_name='player', blank=False, null=False) class InjuredPlayer(models.Model): player = models.ForeignKey('Player', models.DO_NOTHING, blank=False, null=False) I'm using REST framework so I have this serializer. And I want to add an attribute that is the sum of all Game scores to the Player serializer. # Serializer class PlayerSerializer(serializers.ModelSerializer): # Get the sum of Game scores of the player # sum_of_scores = ________________ class Meta: model = Player # Use sum_of_scores as a field on the serializer fields = ('activity', 'logo', 'sum_of_scores') Then, what want to do is display the list of players, with their sum of scores, if they are on InjuredPlayer. So in my class: class PlayerList(APIView) The queryset should be something like: # I tried this queryset = Player.objects.filter(injuredplayer__player=id) How you do filter the objects that are not on the other table. And is it possible to order the list based on the sum_of_scores? If so, how? Thank you -
Django: Detailed and List View URLS - Call same function from views?
So basically i know i can call different functions based on urls from the urls.py in django. Now what i want to know is, can i call the same function for two different urls: Eg: urls.py urlpatterns = [ url(r'^v1/ttu/appliance/',views.get_appliances), url(r'^v1/ttu/appliance/(?P<appliance>[-.\w]+)$',views.get_appliances), ] and my get_appliances in views.py is something like this: def get_appliances(request, appliance): if appliance is None: #do something else: #do something else is this possible? Thank you. -
How to find absolute path of uploaded image - Django 1.11
I have a django form in which the user can upload an image that will then be displayed on a page. After the form request is submitted, I'm trying to return an httpresponse to the user of the uploaded image using the following code: image_data = open("/path/to/my/image.png", "rb").read() return HttpResponse(image_data, content_type="image/png") The issue is that I can't get the absolute path from image submitted in the form request. By doing the following, I can get the name of the image, but not the local path to it: name = "" for filename, file in request.FILES.iteritems(): name = request.FILES[filename] imageFileName = name I've tried using the function file_to_string() based on an SO post, but it looks like the function is deprecated now. How can I get the absolute file path so I can pass it to the open function to return the image?