Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to add User objects to manytomany fields?
I am trying to add the currently logged in user to a m2m field in my model: class(models.Model): name = m.cfield(...) admin = m.m2m(User, related_name="admin+",...) members = m.m2m(User, related_name="members+",...) creator = m.FKEY(User, related_name="creator+",...) While I'm trying to create an object using this views: if request.method == "POST": user = User.objects.get(id=request.user.id) clss = Class() clss.creator = user clss.admin.add(user) clss.members.add(user) clss.save() return redirect('...') I am thrown with FOREIGN KEY constraint failed error. The traceback is: Traceback (most recent call last): File "C:\Users\mowli\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\base\base.py", line 243, in _commit return self.connection.commit() sqlite3.IntegrityError: FOREIGN KEY constraint failed The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\mowli\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\mowli\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\mowli\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\mowli\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "C:\Users\mowli\Desktop\Projects\gcepac\app\views.py", line 49, in new_classroom clss.admin.add(user) File "C:\Users\mowli\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\fields\related_descriptors.py", line 951, in add self._add_items( File "C:\Users\mowli\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\transaction.py", line 232, in __exit__ connection.commit() File "C:\Users\mowli\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\mowli\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\base\base.py", line 267, in commit self._commit() File "C:\Users\mowli\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\base\base.py", line 243, in _commit return self.connection.commit() File "C:\Users\mowli\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\utils.py", line 90, in __exit__ raise dj_exc_value.with_traceback(traceback) … -
rendering plotly dash in Django template
I am using https://django-plotly-dash.readthedocs.io/en/latest/ to serve my plotly dash in Django. At the moment the chart is rendered ok in my template. However, it displays very small, I try to adjust the size of the div but it doesn't seem to work. {%load plotly_dash%} <div style="height: 100%; "> {%plotly_app name="simple_example" %} </div> -
Django 2.1.5: Storing the current username in a blog entry
I am very new to Django and try to build a little app for my family with some basic features, one of which is a blog app. In this now I want to store the author of a blog entry in the article model to save it in the database. In the end in the blog entry I want a header that displays the author and the datetime. I found several approaches to that but some how none of them worked for me so far. The last thing I did now was to try and grab the username in the view with requests.user.get_username() and then populate the field in my form with this string as initial value. Somehow it just doesn't come through, I always get the "field is required" error message... Here is my blog-create-view.py: def blog_create_view(request): user = request.user.get_username() data = {'author': user} form = BlogForm(request.POST, data) if form.is_valid(): form.save() return HttpResponseRedirect('/blog/blog-create/thanks') else: print(form.errors) form = BlogForm() context = { 'articleform' : form, } return render(request, "blog-create.html", context) this is the form: class BlogForm(forms.ModelForm): title = forms.CharField(label='', widget=forms.TextInput(attrs={"placeholder":"Titelfeld"})) text = forms.CharField( label='', widget=forms.Textarea( ) ) author = forms.CharField(widget=forms.HiddenInput()) class Meta: model = Article fields = [ 'title', 'text', … -
Remove 1 Form from Formset Dynamically Django
I am using the below to dynamically add a form to my formset: .html {{ form2.management_form }} <div id="form_set"> {% for form2 in form2.forms %} <table class="table table2" width=100%> <tr> <td width = 17.5%>{{form2.ProductCode}}</td> <td width = 32.5%>{{form2.DescriptionOfGoods}}</td> <td width = 12.5%>{{form2.UnitQty}}</td> <td width = 12.5%>{{form2.Type}}</td> <td width = 12.5%>{{form2.Price}}</td> <td width = 12.5%>{{form2.Amount}}</td> </tr> </table> {% endfor %} </div> <button id="add_more" class="btn aqua-gradient">Add</button> <button id="delete" class="btn aqua-gradient">Delete</button> <div id="empty_form" style="display:none"> <table class='table table2' width=100%> <tr> <td width = 17.5%>{{form2.empty_form.ProductCode}}</td> <td width = 32.5%>{{form2.empty_form.DescriptionOfGoods}}</td> <td width = 12.5%>{{form2.empty_form.UnitQty}}</td> <td width = 12.5%>{{form2.empty_form.Type}}</td> <td width = 12.5%>{{form2.empty_form.Price}}</td> <td width = 12.5%>{{form2.empty_form.Amount}}</td> </tr> </table> </div> $('#add_more').click(function() { var counter=0; var form_count = $('#id_form-TOTAL_FORMS').val(); counter++; $('#form_set').append($('#empty_form').html().replace(/__prefix__/g, form_count)); $('#id_form-TOTAL_FORMS').val(parseInt(form_count) + 1); }); This works perfectly - however I need to be able to delete a line dynamically as well when the Delete button is clicked, and I'm struggling with working through the best way to do that. Any suggestions? I had tried this below - but of course that will only delete all forms and only if they are empty. I want to just delete one form at a time. I feel I may need to add a counter to the id above? Please … -
IntegrityError at /collection/order/ FOREIGN KEY constraint failed error while adding a new object
Hi I was just learning django and trying to create a model form with manaytomany relationship between item and order below is my code snippet. models.py class Item(models.Model): name = models.CharField(max_length=25,default="",primary_key=True) weight = models.FloatField() def __str__(self): return self.name class Order(models.Model): customername = models.CharField(max_length=25,default="") item = models.ManyToManyField(Item,default="") metal = models.ForeignKey(Material,on_delete=models.CASCADE) price = models.IntegerField() place = models.CharField(max_length=25) orderdate = models.DateTimeField(auto_now_add=True) def __str__(self): return self.customername forms.py: from django import forms from .models import Order, Material, Item class ItemForm(forms.ModelForm): class Meta: model = Item fields = '__all__' class OrderForm(forms.ModelForm): class Meta: model = Order fields = '__all__' views.py: def ItemSaveorUpdate(request): if request.method == 'POST': form = ItemForm(request.POST) if form.is_valid(): form.save() messages.add_message(request,messages.SUCCESS,"Movie rating submitted succesfully") else: form = ItemForm() return render(request,'addItem.html',{"form":form}) def OrderSaveorUpdate(request): if request.method == 'POST': form = OrderForm(request.POST) if form.is_valid(): form.save() messages.add_message(request,messages.SUCCESS,"Order added succesfully") return redirect('material') elif request.method == 'PUT': item = Item.objects.get(pk=id) form = OrderForm(instance=item) form.save() else: #item = Item.objects.get(pk=id) form = OrderForm() return render(request,'addOrder.html',{"form":form}) Template additem.html: <form action="{% url 'item' %}" request="post"> {% csrf_token %} {{form.as_p }} <input type="submit" value="add"> </form> urls.py: urlpatterns = [ path('item/', views.ItemSaveorUpdate, name="item"), path('material/', views.MaterialSaveorUpdate, name="material"), path('order/', views.OrderSaveorUpdate, name="order"), I am trying to select multiple items while creating an order and after clicking add it is … -
Django+Supervisor+NGINX on Ubuntu server 18.04. Problems with dynamic content
I am trying to deploy my website in Django+Supervisor+NGINX on Ubuntu server 18.04 from Hetzner. gunicorn.conf.py bind = '127.0.0.1:8000' workers = 3 user = "nobody" Here is my .conf (supervisor): [program:ako] command=/home/oleg/dj/venv/bin/gunicorn ako.wsgi:application -c /home/oleg/dj/ako/ako/gunicorn.conf.py directory=/home/oleg/dj/ako user=nobody autorestart=true redirect_stderr=true stdout_logfile=/home/oleg/dj/ako/ako_supervisor.log stderr_logfile=/home/oleg/dj/ako/ako_supervisor.log autostart=true autorestart=true startsecs=10 conf. NGINX server { listen 80; server_name 95.217.187.37; access_log /var/log/nginx/example.log; location /static/ { root /home/oleg/dj/ako/rsf/; expires 30d; } location / { proxy_pass http://127.0.0.1:8000; proxy_set_header Host $server_name; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } } with a stopped supervisor: sudo service supervisor stop When I try to launch gunicorn on the root of my project gunicorn ako.wsgi:application everything properly works : Welcome to Ubuntu 18.04.4 LTS (GNU/Linux 4.15.0-91-generic x86_64) (venv) root@t-20200417:~/dj/ako# gunicorn --bind 0.0.0.0:8000 ako.wsgi [2020-04-18 13:44:15 +0200] [1768] [INFO] Starting gunicorn 20.0.4 [2020-04-18 13:44:15 +0200] [1768] [INFO] Listening at: http://0.0.0.0:8000 (1768) [2020-04-18 13:44:15 +0200] [1768] [INFO] Using worker: sync [2020-04-18 13:44:15 +0200] [1771] [INFO] Booting worker with pid: 1771 the test website can be properly reached in browser under http://95.217.187.37/rsf/f_size_water/ and it properly works. When I start supervisor sudo service supervisor start the website is still reachable http://95.217.187.37/rsf/f_size_water/, static links are still working, but the dynamic content does not work. In Menu "homepage language change" the … -
Wagtail form file upload
I have an issue when I add file upload field to Wagtail Forms Builder I get this error: Exception Type: TypeError Exception Value: Object of type InMemoryUploadedFile is not JSON serializable This is my code: class FormField(AbstractFormField): CHOICES = FORM_FIELD_CHOICES + (('fileupload', 'File Upload'),) page = ParentalKey('FormPage', on_delete=models.CASCADE, related_name='form_fields') field_type = models.CharField( verbose_name='field type', max_length=16, # use the choices tuple defined above choices=CHOICES ) api_fields = [ APIField('page'), ] class CustomFormBuilder(FormBuilder): def create_fileupload_field(self, field, options): return forms.FileField(**options) class FormPage(AbstractEmailForm): form_builder = CustomFormBuilder intro = RichTextField(blank=True) thank_you_text = RichTextField(blank=True) content_panels = AbstractEmailForm.content_panels + [ FieldPanel('intro', classname="full"), InlinePanel('form_fields', label="Form fields"), FieldPanel('thank_you_text', classname="full"), MultiFieldPanel([ FieldRowPanel([ FieldPanel('from_address', classname="col6"), FieldPanel('to_address', classname="col6"), ]), FieldPanel('subject'), ], "Email"), ] # Export fields over the API api_fields = [ APIField('intro'), APIField('thank_you_text'), ] This is my template: {% load wagtailcore_tags %} <html> <head> <title>{{ page.title }}</title> </head> <body> <h1>{{ page.title }}</h1> {{ page.intro|richtext }} <form action="{% pageurl page %}" method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <input type="submit"> </form> </body> </html> Wagtail version 2.8.1 Django version 3.0.5 any idea with this issue ? -
Will I be able to use celery tasks during model migrations in Django?
I have a requirement to modify an existing db model called Alert and create new alerts with new functionality. I also need to take care of the existing alerts in the data base which were created with old model fields. After adding the new fields to Alert model, I'm trying to re-create the alerts with new functionality which has new columns. Basically taking existing rows and re-inserting them in data base with updated new columns with some extra information in the new columns. For this I'm trying to run a celery task in the function which is called as soon as the migration is applied. migrations.RunPython(function which does some operation and then run celerytask.delay(with_some_args) to create new alerts) I'm really concerned whether I can run a celery task inside the function which is passed to migrations.RunPython(). Even for testing this functionality, I don't have an existing data in our lower environment and the required migrations are already applied before even including this function. I don't want to mess with existing DB as everyone is using already. Can someone please confirm if I can actually run long running celery tasks when applying the migrations? in python manage.py migrate appname? Django: 1.11.15 … -
Print django filter context to template
I have a django view as follows tabledata = Entity.objects.filter(id=2) context = { 'table_data': tabledata, } return render(request, 'viewer.htm', context) I tried printing the values in viewer.htm like so {{table_data}} This gives the output <QuerySet [<Entity: Entity object (6)>]> I also tried printing the values using {{table_data.A}} which is one of the fields. This simply gives a blank output. 1.How do I print the values? 2.If the filter returns multiple rows, how do I print them individually in the template? -
Open Edx Third Party Login Integration with Keycloak
I am using edx-ironwood.2-6 in ubuntu 18.08. I am also running keycloak 9.0.0. To enable third-party login using Keycloak I am using the python-social-auth library suggested in edx documentation. Since by default keycloak.py was not available in the edx-ironwood, I copied this keycloak.js file at the location edx-ironwood.2-6/apps/edx/venvs/edxapp/lib/python2.7/site-packages/social_core/backends Followed all steps written in comments to setup keycloak and added following information in keycloak.py SECRET = 'client secret' PUBLIC_KEY = 'publick key from keycloak' AUTHORIZATION_URL = 'http://127.0.0.1:8080/auth/realms/neoscript/protocol/openid-connect/auth' ACCESS_TOKEN_URL = 'http://127.0.0.1:8080/auth/realms/neoscript/protocol/openid-connect/token' USER_DETAILS_URL = 'http://localhost:8080/auth/realms/neoscript/protocol/openid-connect/userinfo' Added following line in the lms.env.json "THIRD_PARTY_AUTH_BACKENDS":[ "social_core.backends.keycloak.KeycloakOAuth2", "social_core.backends.google.GoogleOAuth2", "social_core.backends.linkedin.LinkedinOAuth2" ] In the Django Admin App, Added a Provider Name: Keycloak slug: keycloak site: localhost:81 backend: keycloak client Id: 'mooc' Client Secret: 'secret key' Also Added client secret in lms.auth.json "SOCIAL_AUTH_OAUTH_SECRETS": { "keycloak":"14f89ef1-02ff-48ad-825f-8160e515ec8e" } In Keycloak client settings, added access type 'confidential', and redirect uri 'http://localhost:81/auth/complete/keycloak/' After server restart, In edx login page, login button for keycloak appearing but when I am clicking on it in the browser a message is coming There has been a 500 error on the Open Edx Server In the apache2 log file following error is coming [Sat Apr 18 17:09:21.212377 2020] [:error] [pid 8143] Traceback (most recent call last): [Sat Apr 18 … -
Query to get related data from a multiple tables using foreign key in Django 2.2
I've below models and I want to get all products of the logged in user(vendor) and the product variant and image of the related products. I've heard about the select_related, but don't know how to use it. What will be my query to get all products of vendor and its related images and variants. models.py class Product(models.Model): vendor = models.ForeignKey(User, on_delete = models.CASCADE, related_name = 'products') name = models.CharField(max_length = 250) class ProductImage(models.Model): product = models.ForeignKey(Product, on_delete = models.CASCADE, related_name = 'product_images') image = models.FileField(upload_to = 'products') class ProductVariant(models.Model): product = models.ForeignKey(Product, on_delete = models.CASCADE, related_name = 'product_variants') name = models.CharField(max_length = 250) Thanks -
django - How can I prevent a tenant from accessing an app in my django project
I'm using Django-tenant-schemas for a multi-tenancy application. I'm trying to limit the access of some tenants to some apps based on subscription options. Is there a way to prevent a specific tenant from accessing a specific app in the project. -
How to run a external python script that is run infinitely in Django and print all the outputs in html?
I have a python script that in an infinite loop get some data from a URL and saves it in a database. it prints some logs and sometimes it throws some errors. my script is as follow: dbclient = MongoClient('127.0.0.1') db = dbclient.shell while True: url = "http://example.com/api" print("request has been sent====================") response = requests.get(url).json() print("data has been downloaded====================") db.api_backup.insert_many(response) print("data has been saved in MongoDB====================") Now, I have created a Django project for monitoring. So, I want to able to start and stop it by a button on an Html page and see its status and outputs(like what is seen in the terminal). It should be noted that this script is independent of Django and is running in the background when Django is not running, and when I go to the Monitoring page, its status will be displayed on the page. I have no idea how to do it. thanks in advance. -
Django zappa application's modular path to app's function? Don't know which one it is
I'm new to django and aws and I'm trying to get my project deployed. I have a similar filestructure as in the project here: https://github.com/divanov11/crash-course-CRM/tree/Part-8---data-to-templates-and-template-tags/crm1_v7_database_queries Now when I'm initializing zappa and they ask "What's the modular path to your app's function?" I have no idea which path I should put. Could anyone help me with this? -
add utf-8 encoding to postgresql - postgis extension for django (UnicodeDecodeError)
i've created a database in postgresql with the following command create database "gisdb" with owner 'geo_user' encoding 'UTF8' LC_COLLATE='C.UTF-8' LC_CTYPE = 'C.UTF-8' TEMPLATE template0; my locale-a are just found C, C.UTF-8 and POSIX , after locale-gen en_US.UTF-8 this is my seetings.py file in django-python DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': 'db_name', 'PASSWORD': 'pass', 'USER': 'user', 'PORT': '5432', 'HOST': 'localhost', } } postgresql version : 10 makemigrations and migrate worked fine and created the tables , but when i try to run runserver the output is A server error occurred. Please contact the administrator. and in the terminal ubuntu subsystem it raise this error UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb1 in position 233732: invalid start byte -
How do I integrate oscar's product render template tags with my own template?
I am developing an ecommerce website with the help of django-oscar. I decided to use the template tags and dashboard of oscar while trying to only change the templates with my own. I am sorry that the description of the question is so long but I assume you would need to understand my work process to understand the problem. In the description below, I start with my basic settings and template integration and work my way to the catalogue.html which is where I am facing the problem. My main problem statement is in bold I have forked the oscar's catalogue app with my own. Right now my settings.py looks like this: # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATES_DIR = os.path.join(BASE_DIR, 'templates/local') OSCAR_TEMP_DIR = os.path.join(BASE_DIR, 'templates/oscar') TEMP_DIR = os.path.join(BASE_DIR, 'templates') STATIC_ROOT = os.path.join(BASE_DIR,'allstatic') STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static_in_env'),] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'django.contrib.flatpages', #Custom Made Apps 'appdir.catalogue.apps.CatalogueConfig', #Oscar Apps 'oscar', 'oscar.apps.analytics', 'oscar.apps.checkout', 'oscar.apps.address', 'oscar.apps.shipping', # 'oscar.apps.catalogue', 'oscar.apps.catalogue.reviews', 'oscar.apps.partner', 'oscar.apps.basket', 'oscar.apps.payment', ... ] SITE_ID = 1 TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATES_DIR, OSCAR_TEMP_DIR, TEMP_DIR], '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', 'oscar.apps.search.context_processors.search_form', … -
Problem loading static content to Web App using Django
I have difficulty displaying static content in my web, I can't figure out where's the issue Here's my browser enter image description here this is my settings.py file: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATE_DIR = os.path.join(BASE_DIR,"templates") STATIC_DIR = os.path.join(BASE_DIR,"static") ..... INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'first_app', ] .... STATIC_URL = '/static/' STATICFILES_DIR = [ STATIC_DIR, ] views.py file: from django.shortcuts import render from django.http import HttpResponse # Create your views here. def index (request): my_dict={'insert_me':"Hello I am from views.py!"} return render(request,'first_app/index.html', context=my_dict) url.py file: from django.conf.urls import url from first_app import views urlpatterns=[ url(r'^$', views.index, name='index') ] and my templates file: <!DOCTYPE html> {% load static %} <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>Django Page</title> </head> <body> <h1>Hi this is a picture from Zakopane</h1> <img src= "{% static "images/picture1.jpg" %}" alt="Picture not found"> </body> </html> I get an error saying ""GET /static/images/picture1.jpg HTTP/1.1" 404 1683" on the terminal. Would appriciate any help Thank you in advance! -
I have set all settings for CORS but it blockes APIs when I'm using VPN, it allows when VPN is off
I have a website with django, nginx and gunicorn. settings.py: INSTALLED_APPS = [ 'corsheaders', ... ] ... MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', ... ] ... CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True CORS_ALLOW_METHODS = ['DELETE','GET','OPTIONS','PATCH','POST','PUT'] and for nginx: location / { add_header 'Access-Control-Allow-Origin' '*' always; } when I use the website without VPN, it will be loaded. when I activate VPN it raises this error: Access to XMLHttpRequest at '' from origin 'front\url' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. how can I solve this issue and see my website with and without VPN? -
$ is not defined error in jquery and javascript
For many days I am making a big django project.For the project I needed jquery. linked many jquery recources.I even kept the jquery file near my templates folder. But an error is coming: Uncaught ReferenceError: $ is not defined I looked for it on google,youtube,on this site and many other sites.But I can't find the solution. <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script> <!--<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.0.min.js"></script>--> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <script src='templates\jquery-3.5.0.min.js' -
Django annotate with related_name from A->C where A->B and B->C where '->' is reverse relationship
I searched a lot on internet but could not find a similar question. I have 3 models : Domain, Topic, Post Each Domain can have many Topics and each Topic can have many Posts. Topic has a foreign key to Domain and Post has a foreign key to Topic. So I can include count of Posts in Topic by annotate(Count('posts')) and I can include count of Topics in Board by annotate(Count('topics')) Is there any way to include count of Posts in Board by annotate ? -
Error with setting DJANGO_SETTINGS_MODULE variable while running debug in PyCharm
I am trying to run my project in PyCharm to debug it but i get this error: django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. I know there have been lot of discussion in stackoverflow and on internet about this topic a lot and i have carefully read through django docs many times now https://docs.djangoproject.com/en/dev/topics/settings/. I have tried next. Also my project is called 'fitex', so i use it as 'mysite': 1)Setting environment variables in my shell as so: set DJANGO_SETTINGS_MODULE = fitex.settings 2). Tried also in shell: export DJANGO_SETTINGS_MODULE=fitex.settings 3). Tried in shell something like this: from django.conf import settings, from fitex import settings, settings.configure(default_settings=settings, DEBUG=True) unfortunately, didn't work. Error: AttributeError: module 'fitex.settings' has no attribute 'configure' 4)Tried adding in my settings.py file: os.environ['DJANGO_SETTINGS_MODULE'] = 'fitex.settings' Also my debug configurations: screenshot Maybe someone is able to help out, thanks! -
login_required and logout is not working in django
here's my views.py from django.shortcuts import render, get_object_or_404,redirect from .models import Post,Author from django.contrib.auth.decorators import login_required from django.contrib.auth import authenticate,get_user_model,login,logout from .forms import UserLoginForm,UserRegisterForm def login_view(request): next = request.GET.get('next') form = UserLoginForm(request.POST or None) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(username=username, password=password) login(request,user) if next: return redirect(next) return redirect('/') context = { 'form': form, } return render(request, "login.html", context) def register_view(request): next = request.GET.get('next') form = UserRegisterForm(request.POST or None) if form.is_valid(): user = form.save(commit=False) password = form.cleaned_data.get('password') user.set_password(password) user.save() new_user = authenticate(username = user.username, password = password) login(request,user) if next: return redirect(next) return redirect('/') context = { 'form': form, } return render(request, "signup.html", context) def logout_view(request): logout(request) return redirect('/') @login_required def home(request): return render(request,"home.html", {}) def posts_list(request): all_posts = Post.objects.all() context = { 'all_posts': all_posts } return render(request,"post_list.html",context) def posts_detail(request, slug): unique_post = get_object_or_404(Post, slug=slug) context = { 'post': unique_post, } return render(request,"posts_detail.html",context) and my url.py is from django.contrib import admin from django.urls import path from posts import views urlpatterns = [ path('admin/', admin.site.urls), path('login/', views.login_view), path('signup/', views.register_view), path('logout/', views.logout), path('', views.home), path('post/',views.posts_list), path('post/<slug:slug>/', views.posts_detail,name='post'), ] so,the problem the home.html directly redirected without going form login route and the logout function is not workig i am … -
How to add a 'new' button for a ForeignKey in a modelForm
I want to add a 'NEW' button for a ForeignKey in ModelForm just like in admin area, here is my medical_report model class Medical_report(models.Model): Immunisation = models.ForeignKey(Immunisation, on_delete=models.DO_NOTHING) Name_of_examining_health_officer = models.CharField(max_length=50) Name_of_the_Health_facility = models.CharField(max_length=50) Date_of_medical_examination_of_child = models.DateField() def __str__(self): return self.Name_of_the_Health_facility Here is my Immunisation model class Immunisation(models.Model): Date_of_immunisation = models.DateField() def __str__(self): return str(self.Immunisation_type) And here is my form.py file class MedicalReportForm(forms.ModelForm): class Meta: model = Medical_report fields = 'Name_of_examining_health_officer','Name_of_the_Health_facility','Date_of_medical_examination_of_child','Immunisation' -
ModelForm is creating a new record inspite of providing an instance
I am creating a ToDo list where I can create a ToDo item and provide a button against each item to update it. I am using ModelForm to save my data to DB. The update button takes me to 'update.html' with the instance of selected task. But when I update the task information and click on 'Submit', it creates a new task with the updated information and does not update the same task. Please helo me, I am stuck. views.py from django.shortcuts import render, redirect from .models import Task from .forms import * def index(request): tasks = Task.objects.all() form = TaskForm() if request.method == 'POST': form = TaskForm(request.POST) if form.is_valid(): form.save() return redirect('/') else: context = {'tasks':tasks,'form':form} return render(request,'TaskList/list.html',context) def update(request, pk): task = Task.objects.get(id = pk) if request.method == 'POST': form = TaskForm(request.POST, instance=task) if form.is_valid(): form.save() return redirect('/') else: form = TaskForm(instance = task) context = {'task':task, 'form':form} return render(request,'TaskList/update.html', context) urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name = 'list'), path('update/<str:pk>/', views.update, name = 'update') ] update.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <form method = 'POST' action = ''> {% csrf_token … -
Python Django views .home dividing into sub classes
I'm trying to do a platform which is querying some data from different social media channels. My "Home" Class is now full of these queries and it takes up to 10 seconds to load the page. My question would be how I can divide the Home class into sub classes like this. Currently my code looks like this: def Home(Request): function1() function2() function3() function4() context{ query1: "query1", query2: "query2", query3: "query3", } return render(request, 'base.html', context) But I want to do like this: def Home(Request): function1() context{ query: "query" } return render(request, 'base.html', context) def Home-query2(Request): function2() context{ query2: "query2", } return render(request, 'base.html', context) def Home-query3(Request): function3() context{ query3: "query3", } return render(request, 'base.html', context) Other question would be, how can I first load the home class and then load each query all at the same time. So that I that load time totally is decreased.