Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
JS extract parameter and save in database
I am using in my Django project JS script in order to make elements on one list sortable by drag&drop functionality. However the issue I obtain is that new order of elements is saved only locally. The JS library of script is available: https://github.com/SortableJS/Sortable The function called on template: {% extends 'base.html' %} {% block content %} <div class="container-fluid"> <div id="simpleList" class="list-group"> {% for issue in backlog.issue_set.all %} <div class="list-group-item"> <div style="float:left;"><strong><a href="{% url 'issue-edit' issue.pk %}">{{ issue.title }}</a></strong></div> <div style="float: right;"><a href="#" class="btn btn-success btn-circle btn-sm"><i class="fas">{{ issue.remaining_estimate }}</i></a></div> <br /><br /><hr style="border-top: dashed 1px;"></hr> <div style="float: left;"><small>Assignee: <strong>{{ issue.assignee }}</strong></small></div> <div style="float: right;"><small>Initiative: <strong>{{ issue.initiative }}</strong></small></div><br /> <div style="float: left;"><small>Priority: <strong>{{ issue.priority }}</strong></small></div> <div style="float: right;"><small>Epic: <strong>{{ issue.epic }}</strong></small></div> </div> {% endfor %} </div> </div> <!-- JS Script for Drag&Drop --> <script> Sortable.create(simpleList, { group: "localStorage-example", store: { /** * Get the order of elements. Called once during initialization. * @param {Sortable} sortable * @returns {Array} */ get: function (sortable) { var order = localStorage.getItem(sortable.options.group.name); return order ? order.split('|') : []; }, /** * Save the order of elements. Called onEnd (when the item is dropped). * @param {Sortable} sortable */ set: function (sortable) { var order = … -
Get current logged in user in Django forms
I need to get the current logged in user in Django form. I need it to get the domain from his email and accordingly fetch the list of other users with similar domain. Here is my code so far: forms.py class AuthUserCheckbox(forms.Form): choice = forms.MultipleChoiceField(choices=[], widget=forms.CheckboxSelectMultiple, required=True) def __init__(self, *args, **kwargs): self.user = kwargs.pop('user') self.user_email = self.user.email.split('@')[1] super(AuthUserCheckbox, self).__init__(*args, **kwargs) self.fields['choice'] = forms.MultipleChoiceField(choices=[(i.id, i.email) for i in User.objects.all() if not i.is_active and self.user_email in i.email ]) views.py @login_required def auth_users(request): form = auth_users(data=request.POST, user=request.user) return render(request, 'todoapp/auth_users.html', context={'form': AuthUserCheckbox()}) -
Django - render only partial / change context / change form after POST without refresh
I need some help with django I have kind of landing page with form, which need to have 3 different states. Flow looks like this: enter email -> check database for user with that email -> render login or register form, still in same template. Code looks like this: .html // lots of code <form method="POST" id="form"> {{ form.as_p }} {% csrf_token %} <input type="submit" value="send"> </form> // lots of code and in views.py i have render method with context return render( request, 'apply.html', context, ) where in context i placed simple standard django form like: class ApplyForm(forms.Form): email = forms.CharField() phone = forms.CharField() Is there and way to change ApplyForm to LoginForm or RegisterForm after sending POST from first one, without refreshing whole page? I though about injecting all three forms to context, sending some ajax request, and then differentiate which form should be displayed, but I'm not sure how could it be done... thanks in advance! -
django forms {{from.as_p}} not rendering any text box or input
I'm sorry to ask something simple, but i'm just trying to add forms into my Django project I'm just following this tutorial on forms, from: https://www.youtube.com/watch?v=6oOHlcHkX2U&t=115s Here's my form in HTML <div class="form-popup" id="myForm"> <form class="form-container" method="post">{% csrf_token %} {{ form.as_p }} <input type="submit" value="save"> <button type="button" class="btn cancel" onclick="closeForm()">Close</button> </form> </div> Here's my code in forms.py: from django import forms from .models import Stream class CameraForm(forms.ModelForm): class Meta: model = Stream fields = ( 'name', 'RTSP', ) my views.py from django.shortcuts import render, get_object_or_404 from CGI.models import tank_system, ambient, Limit from CGI.basicfun import selectDates, weekSelect import logging logger = logging.getLogger(__name__) from .forms import CameraForm def index(request): forms = CameraForm(request.POST or None) if forms.is_valid(): forms.save() tank = tank_system.objects.latest('datetime') room = ambient.objects.latest('datetime') limit, created = (Limit.objects.get_or_create()) return render(request, 'CGI/Pages/DashBoard.html', {'tank':tank,'room':room, 'limit':limit, 'forms':forms}) Now problems is {{from.as_p}} is supposed to create an html text box form me input and post which ever data(here how its support to look: ), but when I open up local test, I see nothing(here the exmple: ), leaving me stumped and confused. I really appreciate if you could help. -
What is the meaning of bind = True keyword in celery?
What is the meaning of bind=True in below celery code? When to use it and when not? @app.task(bind=True) def send_twitter_status(self, oauth, tweet): try: twitter = Twitter(oauth) twitter.update_status(tweet) except (Twitter.FailWhaleError, Twitter.LoginError) as exc: raise self.retry(exc=exc) -
How can I process json file and display some data in form of charts in django
Basically, I have implemented Sentiment analysis for the Amazon review dataset in python. Now I want to make a web app for it. I try to look on google for it but all the projects are for Twitter data. Till now I make a Django app which can take json file from the user and display the success message. Any ideas on how to load the json file in my script and put these data on the charts -
How to update() values in Django by manipulating column data usign F()
I want to call QuerySet.update() with for certain column field. The update value will be manipulated with one function call which has arguments of other column field values. Those other column field values are of string type. I am trying to evaluated other column values usign F(), passed to function call which is going to manipulate the value. But it is giving me error, because F() is not returning the actual value of field. Model: TestQAMap: answer = models.TextField(_('Answer'), null=False, blank=False, db_column='answer') section_question = models.ForeignKey('SectionQuestionMap', null=False, blank=False,db_column='section_question_id') ae_score = models.DecimalField(_('Auto Evaluated Score'), null=True, blank=True, db_column='ae_score', max_digits=5) Execution: test_qa_map.update(ae_score=start_predicting(F('section_question__question__code'), F('answer'))) Method start_predicting() is my method which return decimal value, expecting 2 string inputs. -
Model Inheritance of ManyToMany Through
Suppose I have following models: class Author(Model): name = CharField() class Publication(Model): name = CharField() authors = ManyToManyField(Author) class Meta: abstract = True class Book(Publication): pass class Article(Publication): pass class Journal(Publication): pass How to change code so that I can add through table to authors? If I write authors = ManyToManyField(Author, through='Relationship'), it will not work. -
How to see the console of a django server running with nohup command?
I am coming from java background so please bear with my question, for normally applications running on tomcat there is a file named catalina.out which contains all the information written to Tomcats System.in and System.out. There is a django project running on a production server and I need to see logs, so far no logger has been configured so I have no idea where to look for server console. Can some one help me with this? -
MultipleObjectsReturned: get() returned more than one object on DetailView
class ArticleDetail(DetailView): model = Article def get_queryset(self): public_articles = Article.objects.filter(is_public=True) authored_articles = Article.objects.filter(author=self.request.user) return public_articles.union(authored_articles) I want users to be able to see a detail view of an article. The articles that should be viewable are ones that are public and ones that the user has published themselves regardless of being made public or not. Author is a foreign key to my user model. I have this same get_queryset logic in my ListView and it gives me exactly what I want however when I click on any of the articles to request the detail view I get the MultipleObjectsReturned exception. -
Dynamically add choices in MultipleChoiceField in Django
I new to Django and working on creating an app where I need to display a checkbox for users email. The problem is, the tuple is populated when the server is started but new users emails do not show up directly and I need to restart the server. How do I go about it ? This is all I was able to get from the internet: class AuthUserCheckbox(forms.Form): def __init__(self, *args, **kwargs): super(AuthUserCheckbox, self).__init__(*args, **kwargs) -
Django Cassandra pagination
How can we paginate the Django Rest API with Cassandra, there is no offset to paginate, the only solution preferred so far is to use greater than(>) or less than(<) on primary keys with the limit. This will work to an extent, but only if I know the last or first item of the current page, What if I need to move from 1st page to 7th page directly? What if my starting index gets deleted in another user session? -
how to superimpose image on an existing pdf using django (if there is a sol using javascript i can do that also in the browser)
I have a task to automate a form filling task, I have a pdf form with everything fields, I have to superimpose user's photo and signature on this form. How to do this? I know how to put image on pdf using jspdf, but it gives me a new pdf, is there a way I can edit existing pdf using jsPDF. -
How to securely update model from form in Django
In my app I want to prompt the user to answer a question. Before the user sees the question, I have it already stored in my database where the user_answer field is null. When a user wants to answer a question a form will pop up in the template and then the answer provided will be updated in the model. The code below does this. However, I'm currently injecting the question_id as a hidden field within my form. I'm suspecting this isn't a best practice as this field could be tampered by an attacker who could change the id and potentially make me modify a different question in the model. How can I pass back the question_id field from the template form back to the model in a secure and reliable manner? This is my model: class Question(models.Model): question = models.CharField(max_length=50) user_answer = models.CharField(max_length=50, null=True) is_correct = models.BooleanField(null=True) My form: class QuestionForm(forms.Form): question_id = forms.IntegerField() user_answer = forms.CharField(max_length=100) My view: def question(request, question_id): if request.method == 'POST': form = QuestionForm(request.POST) if form.is_valid(): q = Question.objects.get(id=form.cleaned_data['question_id']) q.user_answer = form.cleaned_data['user_answer'] q.save() return render(request, 'done.html', {'form':form.cleaned_data}) else: return render(request, 'home.html') else: question = get_list_or_404(Question, id=question_id) form = QuestionForm({'question_id':question.id}) return render(request, 'quiz.html', {'question':question, 'form':form}) … -
Project that has predifined tasks list
First off, I am relatively new to Django. Apologies if this may same as a trivial question. I'm building an app where one project has a set of predefined tasks that are to be completed by the user with fields like date started, date ended, status etc. There are 13 of said tasks and upon creation of a new project. I am having trouble thinking of the ideal tables required. I am thinking that I'll have to have 13 separate tables for each of the tasks with a foreign-key relationship with the projects table. If that is the case would I have to utilize signals to instantiate the default task list? How would you recommend going about this? -
Why does Sentry's recommended Django logging configuration silence logging from django.db.backends?
The Sentry Django integration documentation recommends the following LOGGING configuration (https://docs.sentry.io/clients/python/integrations/django/): LOGGING = { 'version': 1, 'disable_existing_loggers': True, 'root': { 'level': 'WARNING', 'handlers': ['sentry'], }, 'formatters': { 'verbose': { 'format': '%(levelname)s %(asctime)s %(module)s ' '%(process)d %(thread)d %(message)s' }, }, 'handlers': { 'sentry': { 'level': 'ERROR', # To capture more than ERROR, change to WARNING, INFO, etc. 'class': 'raven.contrib.django.raven_compat.handlers.SentryHandler', 'tags': {'custom-tag': 'x'}, }, 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'verbose' } }, 'loggers': { 'django.db.backends': { 'level': 'ERROR', 'handlers': ['console'], 'propagate': False, }, 'raven': { 'level': 'DEBUG', 'handlers': ['console'], 'propagate': False, }, 'sentry.errors': { 'level': 'DEBUG', 'handlers': ['console'], 'propagate': False, }, }, } I am particularly interested in this logger definition: 'django.db.backends': { 'level': 'ERROR', 'handlers': ['console'], 'propagate': False, }, To me, this reads that log entries originating from django.db.backends (and descendants) are sent to the console only, and do not propagate up to the root logger (which is configured to send log entries >= WARNING to Sentry. The Sentry documentation does not seem to even acknowledge the existence of this logger. This configuration is presented as-is as a means of getting Django to log to Sentry. Is my reading of this correct? Can you think of any justification for … -
ModuleNotFoundError: No module named 'DEGNet' while attempting >Python manage.py makemigrations|python 3.7, django 2.1.7
I'm using python-anywhere to make a web app and while trying to makemigrations for a new Profile model, I got the error: ModuleNotFoundError: No module named 'DEGNet' I've tried to look around the Settings.py and others like it and I found nothing that could lead to this error. Also while listing Python manage.py help I am faced with an error below the help message that states, Note that only Django core commands are listed as settings are not properly configured (error: No module named 'DEGNet'). My Settings file goes like this: ALLOWED_HOSTS = ['*myusername*.pythonanywhere.com'] # Application definition INSTALLED_APPS = [ 'users.apps.UsersConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'products.apps.ProductsConfig', 'crispy_forms' ] 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.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'pyshop.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, "templates") ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = '*myusername*_pythonanywhere_com_wsgi.py' # Database # https://docs.djangoproject.com/en/2.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/2.1/topics/i18n/ LANGUAGE_CODE = 'en-us' … -
Geodjango OSMWidget is not returning actual coordinates
I am using the OSMWIdget in my PointField form. I am able to get the values returned by the widget { "type": "Point", "coordinates": [ 13468873.706852857023478, 1639089.007222681771964 ] } But the thing is, these are not 'standard' coordinates. I had already set my defaults to 'default_lon' : 120.993173,'default_lat' : 14.564752 so I expected to get these as results. Also I am not saving any 'spatial' objects to spatialite because I only need the lon and lat as primitive dataypes and I would rather stick to having a single database in our project and that db is not a spatial db. -
How to take lock on mysql db table for as long as i like through django
I would like to test issue "Lock wait timeout exceeded" that arrises when some part of the code has a lock on db table and other part of code is waiting for the lock to be open. To reproduce this issue, i need to take lock on db table manually as long as i like. So, is there any way in django to perform this scenario? This is the issue that i am trying to reproduce: OperationalErrorMySQLdb.connections in defaulterrorhandler error(1205, 'Lock wait timeout exceeded; try restarting transaction') -
How do I get an image from class Account, and use it in PostListView?
I got the images working on my template, but the image being displayed is the current logged in user's image. How do I filter it so that Profile.objects.get(user=[the owner of the post's user])? class PostListView(ListView): model = Post def get_context_data(self, **kwargs): context = super(PostListView, self).get_context_data(**kwargs) context['user_post'] = Post.objects.filter(user_id=self.request.user.id) # context['user_profile'] = Profile.objects.get(user=self.request.user.id) context['user_profile'] = Profile.objects.get(user=1) return context The error code says: 'PostListView' object has no attribute 'user'. I don't understand this error code because from my understand PostListView's model is set to Post which has the following models: class Post(models.Model): user = models.ForeignKey(to=settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=200) text = models.TextField() ... So in other words every post made to the blog has a user. def get_context_data(self, **kwargs): context = super(PostListView, self).get_context_data(**kwargs) context['user_post'] = Post.objects.filter(user_id=self.request.user.id) # context['user_profile'] = Profile.objects.get(user=self.request.user.id) context['user_profile'] = Profile.objects.get(user=1) return context What I believe self is doing here is represents the current object in PostListView right? Can you please ELI5? I am having some trouble understanding the documentation since the language used in there is difficult for me. -
Django: How to redirect or disconnect the user when he came back to the previous page or coming back to the login page
I thank you in advance for any help you could give to me about this question. I would like the user to be redirect automatically to another page in my Django web application in the case he click on the button in order to coming back to the last page, or when he came back to the login page again I would like to disconnect it and when he still logged and he try to access to the register page, I would to disconnect it or redirect to another page from my website. I have already tried LoginMixin and redirect but nothing. when I am already logged and backing to the previous page I mean the login page I am still logged and I am have the login page even when I am already logged, the same I can go back to the register page but I am already logged. I am using Django 2.1.7 the latest version. So help any help will be appreciated. Thank you again. -
Django - Variable deleting itself prior to Object Create?
Consider this snippet: if fire_prim is not None: print('Fire Primary is definitely not Null, here is proof: {}'.format(fire_prim)) fire_primary_obj = LifeSafety.objects.create( name='Fire Primary', store=store_obj, phone_line=fire_prim, phone_line_provider=an_provider) We get the following output: Fire Primary is definitely not Null, here is proof: +16077244546 Traceback (most recent call last): File "C:\Python\lib\site-packages\django\db\backends\utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "C:\Python\lib\site-packages\django\db\backends\sqlite3\base.py", line 298, in execute return Database.Cursor.execute(self, query, params) sqlite3.IntegrityError: NOT NULL constraint failed: stores_lifesafety.phone_line The above exception was the direct cause of the following exception: Traceback (most recent call last): File "<console>", line 1, in <module> File "C:\Users\admin-dksc104694\Desktop\Dev\it-database\scripts\data.py", line 246, in update_lifesafety_devices fire_primary_obj = LifeSafety.objects.create(name='Fire Primary', store=store_obj, phone_line=fire_prim, phone_line_provider=an_provider) File "C:\Python\lib\site-packages\django\db\models\manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Python\lib\site-packages\django\db\models\query.py", line 413, in create obj.save(force_insert=True, using=self.db) File "C:\Python\lib\site-packages\django\db\models\base.py", line 718, in save force_update=force_update, update_fields=update_fields) File "C:\Python\lib\site-packages\django\db\models\base.py", line 748, in save_base updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) File "C:\Python\lib\site-packages\django\db\models\base.py", line 831, in _save_table result = self._do_insert(cls._base_manager, using, fields, update_pk, raw) File "C:\Python\lib\site-packages\django\db\models\base.py", line 869, in _do_insert using=using, raw=raw) File "C:\Python\lib\site-packages\django\db\models\manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Python\lib\site-packages\django\db\models\query.py", line 1136, in _insert return query.get_compiler(using=using).execute_sql(return_id) File "C:\Python\lib\site-packages\django\db\models\sql\compiler.py", line 1289, in execute_sql cursor.execute(sql, params) File "C:\Python\lib\site-packages\django\db\backends\utils.py", line 100, in execute return … -
Posts not displaying
I have verified that there are entries in the Books table, but my template is not displaying them for a reason I can't seem to pinpoint. Model: class Book(models.Model): bookTitle = models.CharField(max_length = 100) bookURL = models.SlugField() bookContent = models.TextField() bookAuthor = models.ForeignKey(User, on_delete = models.CASCADE, related_name = 'books') creationDate = models.DateTimeField() Template: {% extends 'base.html' %} {% block content %} {% for p in books %} <div class="post-wrapper col-lg-8 card" style="border: 1px solid black; margin: 20 auto;"> <div class="card-body"> <div class="card-title">{{ p.bookTitle }}</div> <div class="card-body"> {{ p.bookContent }} </div> <em style="margin-left: 10px;"><small>written by {{ p.bookAuthor }} at {{ p.creationDate }}</small></em> </div> </div> {% endfor %} {% endblock %} View: from django.shortcuts import render from django.http import HttpResponse from .models import Book from django.utils import timezone # Create your views here. def viewAll(request): books = Book.objects.all() return render(request, 'viewAll.html', {}) -
How to create Django Custom User model where a single user will have multiple profiles
Hello I am new to programming and learning. I am having some problem in decision making for the user model in Django. Below is the description of my project which i want to do. Please suggest me the best way to go about it. I will have an ecommerce application where customer, shop owner, shop staff and shop delivery man will interact each other and will have the following profiles Individual User profile (register with email as username) Grocery Shop profile ( there will be many grocery shops who will register as shop on the application and will have a bit of admin site for the shop) Shop staffs profile ( working under the shop admin) Delivery man profile ( working under the shop admin) Super admin for the project Admin profile for the entire application with some privileges. The way i want to operate is that each user will register using email as user name and by default will have a user profile. Later suppose a user have a shop and want to register on our app (in another word if anybody want to register his shop, he need to register as a user and then apply/register for shop). … -
how to enable base template on apphook'd page and use footer in static placeholder
I got an application hook to work as explained in the very basic sample of the doc. The application does its job, renders its own templates and does all navigation back and forth. But I am facing 2 problems: After putting the hooked application an a page via the advanced settings... of the cms frontend, I am no longer be able to edit the page over the frontend. If I navigate in /?edit mode to this particular page cms toolbar dismisses and the /?edit mode is taken away. How can I recover editing such apphook'd page? In the site's view mode (published apphook'd page) I have no styling and no base.html template stuff. So I miss the header menu coming from the base template and the footer which is generally added to each page by a static placeholder. Since I am not able to do frontend editing of the apphook'd page (as mentioned in paragraph 1), I am unable to embed the application into my well known page style. How can I get the intimate styling back for such an apphook'd page? I am working with django 1.11.18 djangocms 3.5.3 python 3.7.2