Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
remove from cart using form in template not working in Django
I'm building an Ecommerce App using Django, I'm storing my cart object in Django Sessions, Add to cart, reduce quanity & increase quantity seem to work perfectly on the products page but the same logic isnt working on the cart page. Django isnt throwing any errors. Below is the snippet of code of my form located inside a table on the Cart page & the view function handling its post request: FORM: <div class="container"> <div class="border rounded p-4 m-4"> <p class="display-4 pl-4 ml-4">Your Cart</p> <hr> <table class="table"> <thead> <tr> <th>Sno.</th> <th>Image</th> <th>Product</th> <th>Price</th> <th>Quantity</th> <th>Total</th> <th> </th> </tr> </thead> <tbody> {% for product in products %} <tr> <td>{{forloop.counter}}</td> <td>___</td> <td>{{product.name}}</td> <td>{{product.price}}</td> <td>{{product|cart_quantity:request.session.cart}}</td> <td>{{product|price_total:request.session.cart}}</td> <td> <form action="/cart/#{{product.id}}" method="POST"> {% csrf_token %} <input hidden type="text" name="product" value="{{product.id}}"> <input hidden type="text" name="remove" value="True"> <input type="submit" value=" * " class="btn btn-block btn-light border-right"> </form> </td> </tr> {% endfor %} </tbody> <tfoot> <tr> <th colspan="4"></th> <th class="" colspan="">Total</th> <th>{{products|total_cart_price:request.session.cart}}</th> </tr> </tfoot> </table> VIEW FUNCTION: class Cart(View): def get(self, request): ids = list(request.session.get('cart').keys()) products = Product.get_products_by_id(ids) return render(request , 'cart.html' , {'products' : products} ) def post(self, request): product = request.POST.get('product') remove = request.POST.get('remove') cart = request.session.get('cart') if remove: cart.pop(product) else: pass return redirect('cart') -
django search returns a blank page
I have designed my search box in my django app but the search only returns the extended html page, not the search results. #View class SearchListProject(ListView): paginate_by = 4 template_name = 'website/search_project.html' def get_queryset(self): search_project = self.request.GET.get('q') return Project.objects.filter(description__icontains=search_project) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['search_project'] = self.request.GET.get('q') return context #url path('search_project/', SearchListProject.as_view(), name='search_project'), path('search_project/page/<int:page>', SearchListProject.as_view(), name='search_project') #html {% extends 'website/project_list.html' %} <h3 class="alert alert-primary text-center">Search: {{ search_project }}</h3> {% block previous_page_url %} {% url 'website:search_project' page_obj.previous_page_number %}?q={{ search_project }} {% endblock %} {% block next_page_url %} {% url 'website:search_project' page_obj.next_page_number%}?q={{ search_project }} {% endblock %} #my form <form action="{% url 'website:search_project' %}"> <input type="text" name="q"> <button type="submit"><i class="icofont-search"></i></button> </form> -
Django templates and pages not updating when viewed in browser
I don't have experience in web development at all, but I know python a bit. I developed a dashboard that shows few stats and graphs with Django templates and pages. I know nothing about using DBs or anything. So what I do is, I run a python script(let's say data_update.py) that updates .html and .js files in the repo to reflect the changes in webview. When an user access the pages, he views the latest pulled data on his browser. This is all working fine when I host the application on local machine or a server, with "python manager.py runserver" The problem is this isn't working on PCF. The webviews are showing the stale data from the time I pushed the app to pcf. I tried running data_update.py as task and worker. The .html and .js files are updating fine, except the updated data isn't reflected when accessed in browser. -
how can i log every time a user has logged in and logged out in django?
i am trying to log every time a user has logged in or logged out in django, i am using the defualt login and logout views by django how can i implement logging these easly without the need for a model to store them. only using logging also if possible that i can edit these defualt views in my views.py this can be much easier here is my views.py code from django.shortcuts import render,redirect from django.contrib.auth.models import User from django.contrib.auth.decorators import login_required from django.contrib import messages from django.db.models import Q from .models import * from .forms import * import logging logger = logging.getLogger('django') def TransactionQuery(request): userAccounts = Account.objects.filter(Account_User = request.user).all() allTransactions = Transaction.objects.filter( Q(Transaction_From__in = [account.Account_ID for account in userAccounts]) | Q(Transaction_To__in = [account.Account_ID for account in userAccounts])).all() return allTransactions def about (request): ip = get_client_ip(request) print(ip) return render(request, 'website/about.html',{'title': 'About'}) def home (request): return render(request, 'website/home.html',{'title': 'Home'}) @login_required def profile (request): return render(request, 'website/profile.html',{'title': 'Profile'}) @login_required def dashboard (request): contex = { 'accounts': Account.objects.filter(Account_User=request.user).all(), 'transactions':TransactionQuery(request), 'title': 'Dashboard' } return render(request, 'website/dashboard.html',contex) def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username1 = form.cleaned_data.get('username') usr= User.objects.filter(username=username1).first() acc=Account(Account_User=usr) acc.save() logger.info(f'Account created for {username1}') messages.success(request, f'Account created for {username1}! … -
OperationalError at /admin/myforms/uploadedfile/add/ while adding data to Table using django admin
I have got a problem while adding data to table using django admin , I am clearly new to django concept and i don know what mistake i did . it says "OperationalError at /admin/myforms/uploadedfile/add/ " while adding data to table manually . and says the table doesn't exist . But while migrating it shows the table name as uploadedfiles . I just want to add data manually and save it inside django admin . so screenshots attached I deleted all the migration files inside Migration , and tried performing in the way as shown in OperationalError at /admin/products/product/add/ no such table: main.auth_user__old but after i performed all the operation still am getting the same error , and my migration folder is empty . here is my models.py class Uploadedfile(models.Model): def file_path(self, filename): return f'uploaded_files/{self.server}/{self.path.replace(":", "$", 1)}/{filename}' files_to_upload = models.FileField( upload_to=file_path, default=None, validators=[validate_file] ) path = models.CharField(max_length=100) server = MultiSelectField(choices=server_list) Can anyone of you help me solve this issue . -
Django After-deployment errors
i recently made a site, following this tutorial https://pythonprogramming.net/django-web-development-python-tutorial . I have uploaded it, however now it shows me this: "For full functionality of this site it is necessary to enable JavaScript. Here are the instructions how to enable JavaScript in your web browser" The site is made from django.Do you know where the mistake might be? The site is http://birminghamcleaner.co.uk/ . -
How to stay on the same page after submitting the form in django?
Basically I have this page whereby I want django to simply just stay there after passing data in 2 input tags by clicking the button. The button only runs the script in the server and then outputs the result from it. The result for the input tags should be what the user has keyed in earlier. Web Page Here is my code def checkSSLValidity(request): command = "script test > test_result" hostname = request.POST['hostname'] port = request.POST['port'] with open(tempfilePath ,'w') as file: file.write("{0} {1}\n".format(hostname,port)) subprocess.call(command,shell=True) file = open(temp_resultfilePath,"r") result = file.read() file.close() return render(request,'test.html',{'result':result,'hostname': hostname, 'port':port}) -
Error in viewing a product on my django project
error imageHey guys I get this error thrown up at me when I click a product on my Django project. I assume its a spelling mistake in either my view or models but I cant see anything. I've attach both an image of the error and my code. Any help would be appreciated. apologies if my post does not contain the correct information needed I'm new to coding. Views from django.shortcuts import render, get_object_or_404 from .models import Category,Product def allProdCat(request, category_id=None): c_page = None products = None if category_id != None: c_page = get_object_or_404(Category, id=category_id) products = Product.objects.filter(category=c_page, available=True) else: products = Product.objects.all().filter(available=True) return render(request,'shop/category.html',{'category':c_page, 'products':products}) def prod_detail(request,category_id,product_id): try: product = Product.objects.get(category_id=category_id,id=product_id) except Exception as e: raise e return render(request,'shop/product.html', {'product':product}) models import uuid from django.db import models from django.urls import reverse class Category(models.Model): id = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=250, unique=True) description = models.TextField(blank=True) class Meta: ordering = ('name',) verbose_name = 'category' verbose_name_plural = 'categories' def get_absolute_url(self): return reverse('phoneshop:products_by_category', args=[self.id]) def __str__(self): return self.name class Product(models.Model): id = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=250, unique=True) description = models.TextField(blank=True) category = models.ForeignKey(Category, on_delete=models.CASCADE) price = models.DecimalField(max_digits=10, decimal_places=2) image = models.ImageField(upload_to='product', blank=True) stock = models.IntegerField() available = models.BooleanField(default=True) … -
Initialize form with request.user in a ModelForm django and hide that value
I have a problem when populating the form, I want to initial the form with request.user and hide that value ! I try to use it but appear an error : "IntegrityError at /create NOT NULL constraint failed: auctions_listings.listed_by_id" models.py class User(AbstractUser): pass class Categories(models.Model): name = models.CharField(max_length=20) def __str__(self): return f"{self.name}" class Listings(models.Model): title = models.CharField(max_length=64) description = models.TextField(max_length=150) price = models.FloatField() image_url = models.CharField(max_length=150) category = models.ForeignKey(Categories, on_delete=models.CASCADE, related_name='category_tag') listed_by = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return f"{self.title} {self.description} {self.price} {self.image_url} {self.category}" forms.py class NewListingForm(forms.ModelForm): class Meta: model = Listings exclude = ['listed_by'] views.py def create(request): user = request.user.username if request.method == "POST": form = NewListingForm(request.POST) if form.is_valid(): form.save() messages.success(request,'Created Success') else: return render(request, "auctions/create.html", { "form":form }) return render(request, "auctions/create.html", { "form": NewListingForm(initial={'listed_by': user}) }) -
Deploying an application in local server and prod a specific url endpoint
How to deploy an application in local server? I have a django project, ready for production but can't risk it to upload in the web hosting. I only need 1 specific URL endpoint to be live on public. Now I want to happen is: I need to deploy the django webapp in a local server, that when a user wants to access the webapp, the user don't need to run 'python manage.py runserver 127.0.0.1:8000' into the terminal to access it. I want it automatically running like attached to the local server. I only need this endpoint to be live on public to receive an external data. '127.0.0.1:8000/api/data' I'm thinking of using ngrok. is it possible? what library or packages I need to do it. Thanks! -
Where is page social_django.views.auth?
I'm trying to make auth with google. But get Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/account/login/google/ Raised by: social_django.views.auth Backend not found settings.py INSTALLED_APPS = [ ..., 'social_django', ] SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = '...' SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = '...' SOCIAL_AUTH_URL_NAMESPACE = 'social' urls.py(root) urlpatterns = [ path('admin/', admin.site.urls), path('', include('books.urls')), path('account/', include('account.urls')), path('comments/', include('django_comments.urls')), path('account/', include('social_django.urls', namespace='social')) ] login.html <a href="{% url "social:begin" "google" %}">Login with Google</a> I did migrations for social_django -
How do I solve this syntax error in manage.py?
I'm running a django app with mariadb. It used to work just fine, however I have left this project idle for a while and now I'm just coming back to it and I can't figure out why it's now breaking. I get the following error when trying to run python manage.py makemigrations: File "manage.py", line 16 ) from exc ^ SyntaxError: invalid syntax Here's my manage.py: #!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main(): os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'MooringsDB.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': main() Now I'll be honest. I may have a clue what the issue is. I'm not using a venv. And I have multiple installations on this system. The problem being I can't remember what I used for this project. I have python 2.7 and python 3. Python 2.7 runs Django 1.11 and python 3 runs django 2.2.7. When I run manage.py in python 3 it returns the following: Traceback (most recent call last): File … -
Expiring Django application in a particular period of time
I have a Django application that I want to deploy soon. But I want the app to display the message that the 'license expired' at a particular time (for example after 2 months or 6 months). This message should display every time the user try to login. Please assist ! -
How To Create Heroku App With Specific Region
please help me. I first tried to deploy an Django Site on Heroku with Free Plan, It went with default Region (US). And now I'm trying to deploy with Asia Tokyo Region, but I couldn't find a way to do it even I'm willing to goes with paid plan. Many thanks in advance, -
How do I access Google Sheets from Django Web App?
I'm trying to access Google Sheets from a Django web app. I am using the following code to create a copy of a base sheet. It is basically a copy of the code Google provide as an introduction from __future__ import print_function import pickle import os.path from googleapiclient.discovery import build from google_auth_oauthlib.flow import InstalledAppFlow from google.auth.transport.requests import Request from django.contrib.staticfiles.templatetags.staticfiles import static from django.conf import settings from scheduler.google_auth_views import SCOPES, CLIENT_SECRETS # If modifying these scopes, delete the file token.pickle. # The ID and range of a sample spreadsheet. SAMPLE_SPREADSHEET_ID = 'some-code-to-the-base-spreadsheet' SAMPLE_RANGE_NAME = 'Sheet1!A1:J' CREDENTIALS_FILE = CLIENT_SECRETS def copy_base_spreadsheet(name): """ Create Copy of Base Spreadsheet """ creds = None # The file token.pickle stores the user's access and refresh tokens, and is # created automatically when the authorization flow completes for the first # time. if os.path.exists('token.pickle'): with open('token.pickle', 'rb') as token: creds = pickle.load(token) # If there are no (valid) credentials available, let the user log in. if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: creds.refresh(Request()) else: flow = InstalledAppFlow.from_client_secrets_file( CREDENTIALS_FILE, SCOPES) creds = flow.run_local_server(port=0) # Save the credentials for the next run with open('token.pickle', 'wb') as token: pickle.dump(creds, token) service = build('sheets', 'v4', … -
I am trying to get from my User: first_name and last_name, and noting is hapening in my html code
This is my model.py, you can see that I add field postUser, from User in ForingeKey: class Post(models.Model): postUser = models.ForeignKey(User,on_delete=models.CASCADE) task_title = models.CharField(max_length=250) task_discription = models.CharField(max_length=250) task_category = models.ForeignKey(TaskCategory, on_delete=models.CASCADE) recommended_tools = models.CharField(max_length=250) budget = models.IntegerField(default=0) def __str__(self): return str(self.postUser) + ' | ' +self.task_title + ' | ' + self.task_discription + ' | ' + str(self.task_category) + ' | ' + self.recommended_tools + ' | ' + str(self.budget) + ' | ' + str(self.id) def get_absolute_url(self): return reverse('post_detail', args=[str(self.id)]) After this I create a view in view.py: class PostDetail(DetailView): model = Post template_name = 'post_detail.html' And finally my post detail page in HTML file: {% extends "nav_footer.html" %} {% load static %} {% block content %} <section class="section gray-bg" id="blog"> <div class="container"> <div class="row justify-content-center "> <div class="col-sm-4"> <div class="blog-grid"> <div class="blog-info"> <h3 class="text-center"> Job title:</h3> <p class="text-center">{{ post.task_title }}</p> <h3 class="text-center"> Author:</h3> <p class="text-center">{{ post.postUser }}</p> <h3 class="text-center"> Author:</h3> <p class="text-center">{{ post.postUser.first_name }}</p> </div> </div> </div> </div> </div> </section> {% endblock %} Noting seems to show up in p class="text-center"{{ post.postUser.first_name }}p? -
How can I retain the Fields value after a Sign-up failed?
this is from views.py, in else: (in if form.is_valid():) statement should be the code for retaining fields value. SOS!! def register(request): if request.method == 'POST': submitbutton= request.POST.get("submit") form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get("username") password = form.cleaned_data.get("password1") new_user = authenticate(username=username, password=password) login(request, new_user) return redirect('home') else: messages.info(request, form.errors) form = UserRegisterForm(request.POST) args = {'form': form} return render(request, 'register.html', args) else: form = UserRegisterForm() return render(request, 'register.html', {'form': form}) -
Manual Integration of TinyMCE with Django
I don't want to use any third party app such as django-tinymce. I have searched Google and this site and didn't find any help about how to integrate TinyMCE with my Django's admin panel. I also prefer to load TinyMCE from the CDN and not to host it locally. Is this possible at all? -
Django Querying Related Models
I'm working on To-Do App where I want to create an n number of tasks under a to-do item. Example: Chemistry is my to-do item and under this I want to create tasks like chapter-1, chapter-2 and each task should have update, completed and delete function(button). If all the items completed the Chemistry to-do item should move to completed items. I don't know how add tasks under inside chemistry item by clicking Add New button. I should get input box and submit button in bootstrap modal or in new page. Image-1 To-Do App models.py class Todo(models.Model): date_created = models.DateTimeField(auto_now_add=True) completed = models.BooleanField(default=False) title = models.CharField(max_length=200) user_id = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) def __str__(self): return self.title class Task(models.Model): heading = models.CharField(max_length=100) todo = models.ForeignKey(Todo, on_delete=models.CASCADE) date_created = models.DateTimeField(auto_now_add=True) completed = models.BooleanField(default=False) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) def __str__(self): return self.heading views.py from django.shortcuts import render, redirect, get_object_or_404 from django.http import HttpResponse, Http404, HttpResponseNotFound, JsonResponse, HttpResponseRedirect from .models import Todo, Task from .forms import * from django.utils import timezone from django.contrib import messages from django.contrib.auth.forms import UserCreationForm from django.views.decorators.csrf import csrf_protect from django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators import login_required from django.views.generic import View from django.contrib.auth.models import User from django.core.paginator import Paginator def register(request): … -
Form with multiple selections to one field + ability to delete selected
There is a table of permissions edit_user = 'edit_user' view_all = 'view_all' create_user = 'create_user' delete_user = 'delete_user' add_user = 'add_user' permissions_choice = [ (edit_user, 'Can edit user '), (view_all, 'Can view all'), (create_user, 'Can create user'), (delete_user, 'Can delete user'), (add_user, 'Can add user'), ] There is a model. class Perm(models.Model): user_perm = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True, related_name='user_perm') choices_perm = models.CharField(max_length=150, choices=permissions_choice, null=True,) def __str__(self): return f"{self.user_perm} {self.choices_perm}" class Meta: unique_together = ['user_perm', 'choices_perm'] verbose_name_plural = 'Разрешения' verbose_name = 'Разрешение' FOrm class PermForm(forms.ModelForm): choices_perm = forms.MultipleChoiceField( required=False, widget=forms.CheckboxSelectMultiple, choices=permissions_choice) class Meta: model = Perm fields = "__all__" Views.py def add_user_perm(request): user_permissions = Perm.objects.filter(choices_perm='choices_perm').delete if request.method == "POST": form = PermForm(request.POST) try: if form.is_valid(): perm = form.save(commit=False) perm.save() messages.info(request, ttrans("PermissionsDodano")) return redirect('permissions:add_user_perm') if request.POST.get('delete'): user_permissions.delete() messages.info(request, ttrans("AdresUsunietoPomyslnie")) return redirect('account:info_company') else: messages.info(request, ttrans("PermissionsDontSaved")) return redirect("permissions:add_user_perm") except Exception as e: messages.info(request, str(e)) else: form = PermForm() context = { 'breadcrumb': [ {'url': reverse('permissions:add_user_perm'), 'title': ttrans("Dodać uchwały ")}, ], 'form': form, "choices": permissions_choice, } return render(request, 'permissions/add_user_perm.html', context) and HTML <div class="card"> <div class="card-content"> <h6>Add perm</h6> <form method='post'> {% csrf_token %} {{ form.as_p }} <button type="submit" class="save btn btn-default">Save</button> <button type="submit" name="delete" class="waves-effect waves-light btn red-button white-text">Delete</button> </form> </div> I wanted to make … -
CSS in not working well after the deployment of my DJANGO project on HEROKU
My Django site was working fine at localhost:8000 but when I uploaded it to Heroku, the CSS of my project is not working well. I haven't received any error while uploading the project on Heroku, but still the webpages are not following some CSS styles. I am putting my files here, please let me know if there is any mistake. this is settings.py file import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) 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') # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '616_nq7wz9et^2thr#k+)5b(g4uk#nv%a2wwqo5jlx-cbjfos+' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ["*"] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'website', 'paypal.standard.ipn', ] 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 = 'Tech_Speed.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATE_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', ], }, }, ] WSGI_APPLICATION = 'Tech_Speed.wsgi.application' # Database # https://docs.djangoproject.com/en/2.2/ref/settings/#databases # DATABASES = { # 'default': { # 'ENGINE': 'django.db.backends.mysql', # 'NAME': 'techspeed', # 'USER': 'root', # 'PASSWORD': '', … -
Using npm run build in capistrano for React Project
I have a Django project which has a React frontend Folders are like this below djangoProject/ - djangoProject/ config/ frontend/ ( React Project) static/ manage.py . . . For Django project I use manage.py collectstatic after deployment. namespace :deploy do desc 'Collec Static Files' task :collectImg do on roles(:app) do execute "source activate myenv;/home/ubuntu/anaconda3/envs/myenv/bin/python /var/www/html/djangoProject/current/manage.py collectstatic --noinput" end end after :publishing, :collectImg end So I add the npm run build command here, but it doesn't work. namespace :deploy do desc 'Collec Static Files' task :collectImg do on roles(:app) do execute "source activate myenv;/home/ubuntu/anaconda3/envs/myenv/bin/python /var/www/html/djangoProject/current/manage.py collectstatic --noinput" execute "cd /var/www/html/current/frontend/; npm run build" # add here end end after :publishing, :collectImg end -
Postgresql order by out of order
I have a database where I need to retrieve the data as same order as it was populated in the table. The table name is bible When I type in table bible; in psql, it prints the data in the order it was populated with, but when I try to retrieve it, some rows are always out of order as in the below example: table bible -[ RECORD 1 ]----------------------------------------------------------------------------------------------------------------------------------------- id | 1 day | 1 book | Genesis chapter | 1 verse | 1 text | In the beginning God created the heavens and the earth. link | https://api.biblia.com/v1/bible/content/asv.txt.txt?passage=Genesis1.1&amp;key=dc5e2d416f46150bf6ceb21d884b644f -[ RECORD 2 ]----------------------------------------------------------------------------------------------------------------------------------------- id | 2 day | 1 book | John chapter | 1 verse | 1 text | In the beginning was the Word, and the Word was with God, and the Word was God. link | https://api.biblia.com/v1/bible/content/asv.txt.txt?passage=John1.1&amp;key=dc5e2d416f46150bf6ceb21d884b644f -[ RECORD 3 ]----------------------------------------------------------------------------------------------------------------------------------------- id | 3 day | 1 book | John chapter | 1 verse | 2 text | The same was in the beginning with God. link | https://api.biblia.com/v1/bible/content/asv.txt.txt?passage=John1.2&amp;key=dc5e2d416f46150bf6ceb21d884b644f Everything is in order, but when I try to query the same thing using for example: select * from bible where day='1' or select * from bible … -
Is it possible to have a media url and a satic url in django
This is my main urls.py file urlpatterns = [ path('admin/', admin.site.urls), path('', include('base.urls')) ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) can I have a url pattern for static files as well as a url pattern for media files?. Thanks -
How to populate forms in formset with model data?
I got Questions and Answers as models. So on one page users can create a new question and some answers for it. To do so a QuestionModelForm will be loaded and a formset with the desired number of AnswerModelForms: class AnswerCreateForm(forms.ModelForm): answertext = forms.CharField(max_length=500, widget=forms.TextInput(attrs={"class": "max"}), label="Antworttext") field_order = ["answertext", "iscorrect"] #views.py AnswerFormSet = formset_factory(AnswerCreateForm, extra=ac) formset = AnswerFormSet(request.POST) #html template <form action="" method="post"> {% csrf_token %} {{ formset.management_data }} {{ formset.as_p }} <input type="submit" value="add question." /> </form> This formset will be send to the html-Template. So far no problem. Now I want to add the option for the user to edit previously created questions and their answers. When one goes to the edit page I want the same forms loaded as before, but prepopulated with the data of the object to edit. With the question form its no problem, cause I can just do form_question = QuestionCreateForm(instance=question) How can I do the same with my formset for the answers? There will be a query to the DB which loads all answer-objects for that question. Then I want to create a formset with the amount of forms as answers were returned and each of those populated with the answer …