Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - handle two form elements for the same model in one template
I am using the following UpdateView in order to alter some values in the database: class MyUpdateView(UpdateView): model = MyModel fields = ['VideoURL', 'MainDescription'] template_name = 'myapp/edit.html' This is my template: <div class="row"> <div class="col-12 col-lg-7"> <form method='post' class="card shadow-soft border p-4 mb-4"> {% csrf_token %} <h5 class="mb-4">General</h5> <div class="form-group"> <label for="MainDescription">Title</label> {{form.MainDescription|add_class:"form-control shadow-soft"}} </div> <div class="row"> <div class="col"> <button class="btn btn-primary btn-dark mt-2 animate-up-2" type="submit">Update</button> </div> </div> </form> </div> <div class="col-12 col-lg-5"> <form method='post' class="card shadow-soft border p-4 mb-4"> {% csrf_token %} <div class="form-group"> <label for="VideoURL">Video URL:</label> {{form.VideoURL|add_class:"form-control shadow-soft"}} </div> <div class="row"> <div class="col"> <button class="btn btn-primary btn-dark mt-2 animate-up-2 text-right" type="submit">Update</button> </div> </div> </form> </div> </div> However, I am facing some difficulties doing so because although both fields belongs to the same model, I cannot update any of the information. What I have noticed though is that if I place the both fields under the same HTML form, it works: <div class="col-12 col-lg-5"> <form method='post' class="card shadow-soft border p-4 mb-4"> {% csrf_token %} <div class="form-group"> <label for="VideoURL">Video URL:</label> {{form.VideoURL|add_class:"form-control shadow-soft"}} </div> <div class="form-group"> <label for="MainDescription">Main Description:</label> {{form.MainDescription|add_class:"form-control shadow-soft"}} </div> <div class="row"> <div class="col"> <button class="btn btn-primary btn-dark mt-2 animate-up-2 text-right" type="submit">Update</button> </div> </div> </form> </div> What am I … -
Issue with .pyc files on remote server
I had a Django project in which I had a file named itemA.py. Then I deleted that file and instead created a foldern with an identical name in which I placed files. So the new structure looked something like this: itemA itemB.py itemC.py ... Before that change, when itemA was a file, it contained a definition for a serializer which was imported elsewhere. So after the change, when I ran the project on my local PC, I ran into an error saying: ImportError: No module named 'rest_main.serializers.sms'; 'rest_main.serializers' is not a package On my local PC, I fixed the issue instantly removing the itemA.pyc file. But when I pushed the changes to the remote server, the same trick did not help. I also ran the find . -name "*.pyc" -exec rm -f {} \; command. But still no success...In bitbucket, all the pyc files are under gitignore... -
How can I keep javascript file paths the same when changing pages?
I've got a few scripts on my base template and when I change the page, Django affixes the script source path to the end of the url, so for example, the main page url is just 127.0.0.1 and the ajax url is "messaging/check_new" so on the main page the full ajax url is 127.0.0.1/messaging/check_new/?user=1 which works but when I go to, for example, account management. The ajax url changes to 127.0.0.1/acc_manage/manage_account/messaging/check_new/?user=1 which is not where the script is. Do I have to put the script in all of my apps or is there a way I can force it to look in the base directory static folder like you would when trying to access an image? example being the image location is project_level/folder/image and you have to get it from inside of a different app so you would have to do something like <img class="picture" src="{{BASE_DIR}}/{{ post.picture.url }}" width=250px height=300px/> How can I do that but with a script? When I try to prefix the script src with {{BASE_DIR}} it just shows an this url in the error (shown below)127.0.0.1//static/js/msg_num/js. Also when I try to use <script src="{{BASE_DIR}}/static/js/msg_num.js/"></script> it gives me the error below. Console Error for script src "{{BASE_DIR}}/static/js/msg_num.js": … -
Django : local variable 'date' referenced before assignment but I import it
I am building a script that use the datetime module : def workspace_detail(request, token): yesterday = date.today() - timedelta(days=1) tomorrow = date.today() - timedelta(days=1) quicklink = f"{token}start_date={yesterday}&end_date={tomorrow}" w_yesterday = quicklink But I have this error local variable 'date' referenced before assignment I imported it every module from the datetime package from datetime import datetime, date, timedelta If I use datetime.today() it works, but I want to use the date.today() for my url. Thanks -
The view quizapp.views.action didn't return an HttpResponse object. It returned None instead
i need help please tell me how i'll compare the model answer with the selected radio button value.....so i could increase the count and display the result.. it is my ques.py models.py from django.db import models from django.contrib.auth.models import User from django.db.models import Model # Create your models here. class Quiz(models.Model): # Quiz_id=models.AutoField(primary_key=True,default=True) question_text=models.CharField(max_length=255) op1=models.CharField(max_length=100) op2=models.CharField(max_length=100) op3=models.CharField(max_length=100) op4=models.CharField(max_length=100) class Ans(models.Model): question=models.ForeignKey(Quiz,on_delete=models.CASCADE) answer=models.CharField(max_length=100) its my views.py -
Obtaining the blog post like feature and capturing slug of the page
I'm trying to figure out the "Like" feature of this blog, i.e. Liking a particular blog post. Kindly help, I'm really stuck here. Here are the files and the error. models.py class Posts(models.Model): author= models.ForeignKey(settings.AUTH_USER_MODEL, on_delete= models.CASCADE) likes= models.ManyToManyField(settings.AUTH_USER_MODEL, blank= True, related_name='likes') published_time= models.DateTimeField(auto_now_add=True, blank=True) title= models.CharField(blank=False, editable=True, max_length=255) slug= models.SlugField(max_length=255, blank= True, null= True,allow_unicode=True, unique= True) updated= models.DateTimeField(auto_now=True, blank= True) content= models.CharField(default=False, max_length=10000,editable=True) widgets= { 'title': forms.TextInput(attrs={'class' :'textinputclass'}), 'content': forms.TextInput(attrs= {'class':'textinputclass text-area-style' }), } def get_absolute_url(self): return reverse( 'postdetail', kwargs={'slug': self.slug}) def get_like_url(self): return reverse('like', kwargs={"slug": self.slug}) def __str__(self): return self.title def save(self, *args, **kwargs): self.slug = self.slug or slugify(self.title) super().save(*args, **kwargs) Here in the models I've added a field "likes" which will hold the users who have liked this particular post. Notice it has a get_like_url() method. I call the method in the HTML template like this. posts_detail.html <body style="width: 60%; margin: 0 auto; background-color: rgb(205, 249, 255);"> <div class="box-style"> <h1 class="heading-text">{{ posts.title }}</h1> <br> <div class="poem-text"> <pre>{{ posts.content }}</pre> </div> <br> <div class="footer-text"> <p>Author: {{ posts.author.first_name }} {{ posts.author.last_name }} <br> Posted On: {{ posts.published_time }} </p> <br> </div> ***<a href=" {% url 'like' %} " class="btn btn-danger">Like {{ posts.likes.count }} </a>*** </div> </body> It takes me … -
Unable to store all images in the django form
I need to store 3 images from form to the database. I can see image is stored but only 1 not all 3 I am uploading while saving form. I am attaching all code snippets used in the application for storing images into database through a form. Any help is appreciated! Thanks #models.py from django.db import models # Create your models here. class Post(models.Model): # post_img = models.ImageField(upload_to='images/', blank=True, null=True) type = ( ('machine', "MACHINE"), ('accessory', "ACCESSORY") ) post_types = models.CharField(max_length=10, choices=type, default='machine') post_title = models.CharField(max_length=100) post_desc = models.TextField(max_length=1000) name = models.CharField(max_length=50) number = models.BigIntegerField() altnumber = models.BigIntegerField() email = models.EmailField() def __str__(self): return self.post_title class Images(models.Model): post = models.ForeignKey('Post', on_delete=models.PROTECT) image = models.ImageField(upload_to='images/', blank=True, null=True) def __str__(self): return self.post.post_title + " Image" # return self.post_title + " Image" and #forms.py from django import forms from .models import Post class PostForm(forms.ModelForm): class Meta: model = Post fields = "__all__" & #views.py from django.shortcuts import render, reverse, redirect from .forms import PostForm from .models import Post, Images from django.forms import modelformset_factory # Create your views here. def index(request): post = Post.objects.all() return render(request, 'index.html', {'post': post}) def addpost(request): ImageFormset = modelformset_factory(Images, fields=('image', ), extra=3) if request.method == 'POST': form = PostForm(request.POST) … -
CrawlerRunner() not going through pipeline file of scrapy
I am trying to call scrapy spider from Django Views.py file.The spider does gets invoked but its output is shown in command prompt and is not saved in Django models to render it onto the page.I checked running spider separately to verify that scrapy and Django are connected and it does work correctly,but when automated using CrawlerRunner() script it doesn't.So some component is missing in CrawlerRunner() implementation from Django views.py file. Below is the Django Views.py file which calls the spider: @csrf_exempt @require_http_methods(['POST', 'GET']) def scrape(request): import sys from newscrawler.spiders import news_spider from newscrawler.pipelines import NewscrawlerPipeline from scrapy import signals from twisted.internet import reactor from scrapy.crawler import Crawler,CrawlerRunner from scrapy.settings import Settings from scrapy.utils.project import get_project_settings from scrapy.utils.log import configure_logging from crochet import setup setup() configure_logging() runner= CrawlerRunner(get_project_settings()) d=runner.crawl(news_spider.NewsSpider) return redirect("../getnews/") My spider does the work of crawling news website and saves Url,Image and Title of top news.But output is that rather than saving this three fields in models.py file it is printing in cmd. Can Anyone help? -
I need image scan and character recognition for my flutter app
I want to add image scan and character recognition to my flutter app. when some on upload his identity card photo the flutter app must get his name and identity card number by scanning the photo of identity card . and assume those values to flutter signup form fields. (Eg. user name as scanned name , user identity can number as scanned number , user gender as scanned gender detail such as) How can I do it ? I research that and I found using the django Api I can do it .But i have no Idea how I do it -
how to make a payments simulator in Django
Hi community How are you all? I have a theoretical question but if you answer with both code and theory that would be great. I want to make a payments simulator in Django. I know how to work with Django but how would I simulate transactions and etc?. could anyone help me? an example : balance = 1034.66 approve = float(input("how much to withdraw? ")) if approve <= balance: print("Remaining balance : "+str(balance - approve)) -
Django: Override model methods from abstract base class models
I am trying to use an abstract base class model in Django to avoid writing some duplicate code and encountering some unexpected behavior. Here is simplified version of my abstract base class: class AbstractDocument(models.Model): notes = models.CharField(max_length=255) document = models.FileField(upload_to=document_file_path) def document_file_path(instance, filename): pass class Meta: abtract = True I need to define the method document_file_path or the code generates error. I want to define different behavior in the subclasses for the document_file_path. Below is an example: class BookDocument(AbstractDocument): book = models.ForeignKey(Book, on_delete=models.CASCADE) def document_file_path(instance, filename): return f'books/{filename}' It does not appear that the child method is overriding the parent method because I get an error that document_file_path returned NoneType when I run the code above. I tried making the method in AbstractDocument return an actual path, but the child method doesn't override the parent in that scenario either. Is there some reason why what I'm trying to do is not possible? Is there something I'm missing in the implementation? Is there another or better way to accomplish this? Thanks in advance for your help! -
HTTPS resource links in Django Rest Framework
I would like to get https links for resources instead of the current http links. Example currently I get something like this: http://10.16.18.46:9000/media/tds_data/2020/2/1/6328/cat.12233.jpg what should I change in the get request in views.py def get(self, request, format=None): files = Files.objects.all() serializer = FilesSerializer(files, many=True) print(serializer.data) return Response(serializer.data) -
Redirect logged in users from register view
I want logged in user redirect to index when they attempt to go to the register form. I manage to do to that, but I can't validate the register form when the a user who is not logged in complete it. I have a custom view for signup: class SignupView(UserPassesTestMixin, FormView): template_name = 'main/auth/register.html' form_class = forms.UserCreationForm def test_func(self): self.request.user.is_authenticated def handle_no_permission(self): if self.request.user.is_authenticated: return redirect('main:index') return self.get(self.request) def get_success_url(self): redirect_to = self.request.GET.get`enter code here`('next', 'main:index') return redirect_to def form_valid(self, form): response = super().form_valid(form) form.save() email = form.cleaned_data.get('email') first_name = form.cleaned_data.get('first_name') raw_password = form.cleaned_data.get('password1') logger.info('Nuevo registro para email=%s a través de SignupView', email) user = authenticate(email=email, password=raw_password) login(self.request, user) form.send_mail() return response methods test_func(self) and handle_no_permission(self) are used to test if the user is authenticated but I think the problem is in return self.get(self.request) I use it to load the form but when I submit the form with correct data, it doesn't POST it to validate it, just reload it again. I suppose I have to call form_valid but I can't figure out how. Any help would be appreciated!! Regards -
Django - multiple html forms in one template
I am using UpdateView class based view in Django in order to update some info: class MyUpdateView(UpdateView): model = Listing fields = ['VideoURL', 'MainDescription'] template_name = 'myapp/edit.html' This is my template: <div class="row"> <div class="col-12 col-lg-7"> <form method='post' class="card shadow-soft border p-4 mb-4"> {% csrf_token %} <h5 class="mb-4">General</h5> <div class="form-group"> <label for="MainDescription">Title</label> {{form.MainDescription|add_class:"form-control shadow-soft"}} </div> <div class="row"> <div class="col"> <button class="btn btn-primary btn-dark mt-2 animate-up-2" type="submit">Update</button> </div> </div> </form> </div> <div class="col-12 col-lg-5"> <form method='post' class="card shadow-soft border p-4 mb-4"> {% csrf_token %} <div class="form-group"> <label for="VideoURL">Video URL:</label> {{form.VideoURL|add_class:"form-control shadow-soft"}} {% comment %} {{form}} {% endcomment %} </div> <div class="row"> <div class="col"> <button class="btn btn-primary btn-dark mt-2 animate-up-2 text-right" type="submit">Update</button> </div> </div> </form> </div> </div> However, I am facing some difficulties doing so because although both fields belongs to the same model, I cannot update any of the information. What I have noticed though is that if I place the both fields under the same HTML form, it works: <div class="col-12 col-lg-5"> <form method='post' class="card shadow-soft border p-4 mb-4"> {% csrf_token %} <div class="form-group"> <label for="VideoURL">Video URL:</label> {{form.VideoURL|add_class:"form-control shadow-soft"}} </div> <div class="form-group"> <label for="MainDescription">Main Description:</label> {{form.MainDescription|add_class:"form-control shadow-soft"}} </div> <div class="row"> <div class="col"> <button class="btn btn-primary btn-dark mt-2 animate-up-2 text-right" type="submit">Update</button> … -
Web Application User Interface development
I am new in web application development, I would like to know what are the choices for developing the user interface for a an application such as an Inventory management system. for the backend, I am using python Django with MySQL but I would like to know if there are other technologies other than HTML, CSS, and JS for UI development. I know that HTML, CSS, and JS are mostly used for website development but I am not sure if these are the recommended technologies for a web application where lots of user interaction is involved. Thanks -
Cannot resolve keyword 'is_active' into field? Choices are: active, admin, email, full_name, id, etc
After switching into django custom user model reset password is not working and showing these errors.... Internal Server Error: /password-reset/ Traceback (most recent call last): File "/home/nasrullah/.local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/nasrullah/.local/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/nasrullah/.local/lib/python3.6/site-packages/django/core/handlers/base.py", line 124, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/nasrullah/.local/lib/python3.6/site-packages/django/views/generic/base.py", line 68, in view return self.dispatch(request, *args, **kwargs) File "/home/nasrullah/.local/lib/python3.6/site-packages/django/utils/decorators.py", line 45, in _wrapper return bound_method(*args, **kwargs) File "/home/nasrullah/.local/lib/python3.6/site-packages/django/utils/decorators.py", line 142, in _wrapped_view response = view_func(request, *args, **kwargs) File "/home/nasrullah/.local/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1263, in add_q clause, _ = self._add_q(q_object, self.used_aliases) File "/home/nasrullah/.local/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1287, in _add_q split_subq=split_subq, File "/home/nasrullah/.local/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1164, in build_filter lookups, parts, reffed_expression = self.solve_lookup_type(arg) File "/home/nasrullah/.local/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1028, in solve_lookup_type _, field, _, lookup_parts = self.names_to_path(lookup_splitted, self.get_meta()) File "/home/nasrullah/.local/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1389, in names_to_path "Choices are: %s" % (name, ", ".join(available))) django.core.exceptions.FieldError: Cannot resolve keyword 'is_active' into field. Choices are: active, admin, email, full_name, id, image, last_login, logentry, password, post, staff, timestamp [01/Feb/2020 13:03:45] "POST /password-reset/ HTTP/1.1" 500 149279 urls.py from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static from django.contrib.auth import views as auth_views from users import views as user_views urlpatterns = … -
Package deleted from requirements.txt Docker build still download that package
I just started using docker to Docurize my django applications. I am using centos server to host my application. Now when first time I build docker image I got error on 'lxml' package so I removed it from requirements.txt file. But when I rebuild the image again 'lxml' is package still downloading Here is my Dockerfile FROM python:3.7.4-alpine3.10 ADD ConnectOneWeb/requirements.txt /app/requirements.txt RUN set -ex \ && apk add --no-cache --virtual .build-deps libffi-dev build-base \ && apk add mariadb-dev \ && apk add jpeg-dev \ && python -m venv /env \ && /env/bin/pip install --upgrade pip \ && /env/bin/pip install --no-cache-dir -r /app/requirements.txt \ && runDeps="$(scanelf --needed --nobanner --recursive /env \ | awk '{ gsub(/,/, "\nso:", $2); print "so:" $2 }' \ | sort -u \ | xargs -r apk info --installed \ | sort -u)" \ && apk add --virtual rundeps $runDeps \ && apk del .build-deps ADD ConnectOneWeb /app WORKDIR /app ENV VIRTUAL_ENV /env ENV PATH /env/bin:$PATH EXPOSE 8000 CMD ["gunicorn", "--bind", ":8000", "--workers", "3", "ConnectOneWeb.wsgi:applic$ and my requirements.txt file asgiref==3.2.3 bluesnap==1.2019.9.1 certifi==2018.4.16 cffi==1.13.2 chardet==3.0.4 cryptography==2.8 Django==3.0 django-anymail==7.0.0 django-countries==5.5 django-crontab==0.7.1 django-paypal==1.0.0 django-prometheus==1.1.0 gevent==1.4.0 greenlet==0.4.15 idna==2.7 Markdown==3.1.1 mysqlclient==1.4.6 pendulum==2.0.5 Pillow==6.2.1 prometheus-client==0.7.1 pycparser==2.19 pycryptodomex==3.9.4 pyOpenSSL==19.1.0 python-alipay-sdk==2.0.1 python-dateutil==2.8.1 pytz==2019.3 pytzdata==2019.3 requests==2.22.0 sentry-sdk==0.13.5 … -
How can I send data several times by spliting to client, using python flask?
I have a big-data that type of 'csv' file. (about 50,000 rows) I typed the code to send the big-data from python flask server and display that at web-page. I want to send big-data several times by spliting to client(100rows × 500times) with progress bar. How can I implement? (I think, there are two methods; 1st server side Python code, 2nd client side JS code. I want to all of methods.) Below, I share my simple code that data can be interacted between server and client. (When client click 'data load' button, server send just one time request all data.) Referencing this below basic code, please give me advice. thank you. [Server-side : python code] from flask import Flask, render_template, request, jsonify; app = Flask(__name__) @app.route('/', methods=['GET','POST']) def clipboard(): if request.method == 'POST': data = pd.read_csv('bigDataFile.csv', engine='python', encoding='ms949').to_dict('record') # 'bigDataFile.csv' have 50,000 rows data return jsonify(result=data), 201; if request.method == 'GET': return render_template('index.html') if __name__ == '__main__': app.run(host='127.0.0.1', port=5000, debug=True); [Client-Side : html, js code] <!-- index.html --> <body> <button type="submit" id="loadData">Data Load</button> <div class="container"> <div id="DataDisplay"></div> <!-- show requested data at this--> </div> <script> $('button#loadData').bind('click', ()=>{ $.ajax({ url: '/', contentType: 'application/json', method: 'POST', }) .done(data => { let getData … -
Ajax call to view giving me a 404 error but it's the right URL in Django
I am trying to send a post request via Ajax and Django but I keep getting a 404 error even though the POST url is the correct URL I want to use. Here is my form minimised I'm trying to send and value through a button. <form class='my-ajax-form' method='POST'>{% csrf_token %} <div class="btn-group" role="group" aria-label="Basic example"> <button type="text" class="btn btn-danger hard" name="hard" value="HARD">HARD </button> </div> </form> Here is my Ajax form: My CSRF code as I was getting an error before but not now. <script> $(document).ready(function() { function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie != '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) == (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } var csrftoken = getCookie('csrftoken'); var $endpoint = $(location).attr('href') function csrfSafeMethod(method) { // these HTTP methods do not require CSRF protection return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); } $.ajaxSetup({ beforeSend: function(xhr, settings) { if (!csrfSafeMethod(settings.type) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", csrftoken); } } }); My Ajax call: $('.hard').click(function(e) { event.preventDefault(); var $hard = $(".hard").text(); … -
TemplateDoesNotExist at /accounts/ flutter
I am trying to connect Flutter with Django.Flutter and Django alone seems to be fine,working without error.But when i am trying to combine both together,an error pops up that says: TemplateDoesNotExist at /accounts/ Here is the cause of the problem from django.shortcuts import render, HttpResponse def home(request): return render(request, '../screens/login_screen.dart') it says that directory does not exists. enter image description here as you see above the directory exists.What is the problem can somebody help? -
Geeting this error while running python manage.py runserver
Unable to run python manage.py runserver Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Python\Python38\lib\threading.py", line 932, in _bootstrap_inner self.run() File "C:\Python\Python38\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\KiranThakur\PycharmProjects\untitled\venv\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\KiranThakur\PycharmProjects\untitled\venv\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "C:\Users\KiranThakur\PycharmProjects\untitled\venv\lib\site-packages\django\core\management\base.py", line 392, in check all_issues = self._run_checks( File "C:\Users\KiranThakur\PycharmProjects\untitled\venv\lib\site-packages\django\core\management\base.py", line 382, in _run_checks -
django shapeshifter - submitting forms with foreign keys
I have two forms I want to submit as one, Form A and Form B. These are modelforms - Form B has a foreign key into Form A. I'm using django-shapeshifter to construct the form, with the MultiModelFieldView. I have the form rendering OK - but when I try to submit the POST request fails because of the key NOT NULL constraint - in the traceback can see the INSERT INTO modela_modelb contains NONE for both rv_id and modelAid. I have tried adding these to the form as hidden fields, but I don't think this is correct. django-shapeshifter docs: https://pypi.org/project/django-shapeshifter/ example with forms being created manually: django: How to make one form from multiple models containing foreignkeys - I believe this example doesn't apply since shapeshifter actually submits the forms individually. models.py class ModelBdata(models.Model): rv_id = models.IntegerField(primary_key=True) modelAid = models.ForeignKey(ModelA, on_delete=models.CASCADE) formFieldB = models.CharField( max_length=300, blank=True, null=True, verbose_name='form_field') class ModelA(models.Model): modelAid = models.AutoField(primary_key=True) formfieldA = models.CharField( max_length=100, verbose_name='Model A Name', unique=True) forms.py class ModelAForm(ModelForm): class Meta: model = ModelA exclude = ('ModelA_family_id','created_by','ModelAid',) def __init__(self, *args, **kwargs): super(ModelAForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_tag = False def clean(self, **kwargs): data = super(ModelAForm, self).clean(**kwargs) # If this the ModelA is not saving … -
Calling python from django subprocess, mysql not found error
python dbtest1.py ==> work O.K. dbtest1.py : import pymysql.connector dbCon = pymysql.connector.connect(host='...', database='...', user='...', password='...') cursor = dbCon.cursor() cursor.execute("INSERT INTO cm_person (name) VALUES ('고길송')") dbCon.commit() access from Django using subprocess, Not found error... views.py include... def datatest(request): subprocess.call(['python', 'dbtest3.py']) return HttpResponse('Call python...') Error message; ModuleNotFoundError: No module named 'pymysql' Did I miss something? or is there any other methods? Thank you. -
Superset Flask OAuth client no redirect_uri
I am trying to authenticate superset flask user with OAuth (flask-oauthlib) by having Django Oauth server. But, In flask config.py OAUTH_PROVIDERS, there is no redirect_uri for getting the temporary authorization code from django oauth server. How do i fix this? -
Wagtail: Pass a vanilla Django model instance to widget
I have a model based on Django's models.Model which I register via ModelAdmin in the admin view. One of my fields has a custom widget assigned to it. # models.py panels = [ # ... CustomFieldPanel('geom', widget=LeafletWidgetWithMedia) # ... ] I need the widgets context to be aware of the model instance. Here is what I tried so far, based on an answered question I posted before. I updated the FieldPanel to pass the instance to the widget. class CustomFieldPanel(FieldPanel): def on_instance_bound(self): self.widget = LeafletWidgetWithMedia(page_instance=self.instance) Then I updated the __init__ and the get_context functions of the Widget: class LeafletWidgetWithMedia(LeafletWidget): include_media = True template_name = "admin/widget.html" def __init__(self, attrs=None, **kwargs): print("Kwargs: " + str(kwargs)) self.page_instance = kwargs.pop("page_instance", None) print("Instance: " + str(type(self.page_instance))) # ... def get_context(self, name, value, attrs): value = None if value in validators.EMPTY_VALUES else value context = super(LeafletWidget, self).get_context(name, value, attrs) context["page_instance"] = self.page_instance context.update(self._get_attrs(name, attrs)) print("Page instance in context: " + str(self.page_instance)) return context This approach works flawless if my model is based on Wagtails Page model but here the context won't get updated. The print statements in the __init__ show the instance gets passed to the widget: # Kwargs: {'page_instance': <MyModel: 7>} # Instance: <class 'register.models.MyModel'> …