Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
filter query not working when searching on foreign key in django
I've 2 classes in models.py - Users and authUser - 1st has app related info while 2nd has generic user info both are connected with a foreign key on username. I'm getting the user request info from 'request.user.username' and I'm trying to search in my users table to get app related info bsed on the logged in user. It's returning an empty queryset. I've tried - print(Users.objects.filter(username__username = request.user.username)) ----xx--- print(Users.objects.filter(username = request.user.username)) ----xx--- print(Users.objects.filter(Q(username__username = request.user.username))) ----xx--- print(Users.objects.get(username__username = request.user.username)) Even - tmp = (Users.objects.all()) for each in tmp: print(each.username) ----xx--- print(each.username__username) models.py class Users(models.Model): userid = models.AutoField(db_column='UserID', primary_key=True) # Field name made lowercase. username = models.ForeignKey('AuthUser', models.DO_NOTHING, db_column='Username', unique=True) # Field name made lowercase. ownedfridges = models.TextField(db_column='OwnedFridges', blank=True, null=True) # Field name made lowercase. friendedfridges = models.TextField(db_column='FriendedFridges', blank=True, null=True) # Field name made lowercase. personalnotes = models.TextField(db_column='PersonalNotes', blank=True, null=True) # Field name made lowercase. eff_bgn_ts = models.DateTimeField() eff_end_ts = models.DateTimeField() class Meta: managed = False db_table = 'Users' class AuthUser(models.Model): password = models.CharField(max_length=128) last_login = models.DateTimeField(blank=True, null=True) is_superuser = models.IntegerField() username = models.CharField(unique=True, max_length=150) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=150) email = models.CharField(max_length=254) is_staff = models.IntegerField() is_active = models.IntegerField() date_joined = models.DateTimeField() class Meta: managed = False db_table … -
django.core.exceptions.ImproperlyConfigured: DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.?
I created an app called djecommerce. Got an error in urls.py saying ImproperlyConfigured here's the code from django.conf import settings from django.conf.urls.static import static from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('accounts/', include('allauth.urls')), ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) In the 6th line it showing the error near path In the wsgi.py it showing error of no module found 'djecommerce' near application word. Here's the code import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'djecommerce.settings') application = get_wsgi_application() -
Issue with setting the context for Stripe Publishable Key in Django view.py
I am trying to set up stripe in Django. I have set up the context with the publishable_key and am calling the stripe payment screen with this context, but I still get the error "You did not set a valid publishable key. Call Stripe.setPublishableKey() with your publishable key. I've researched other examples and my code seems to be the way to do it, but I'm struggling with this now. def charge(request): publishkey = settings.STRIPE_PUBLISHABLE_KEY if request.method == 'POST': charge = stripe.Charge.create( amount=500, currency='gbp', description='A test charge', source=request.POST['stripeToken'], ) context = {'publishkey':publishkey} return render(request, 'charge.html', context) -
In django which model feilds is required for data which having comma like in csv file 1 colunm having multiple data i.e. French, Japanese, Desserts
I am creating CRUD api in django rest framework sqlite3 database. I want to create model for restaurant which having some feilds which is [Restaurant ID, Restaurant Name, Cuisines, Average Cost for two, Currency, Has Table booking, Has Online delivery, Aggregate rating, Rating color, Rating text, Votes] i have csv file which is already having data but which model feild is required for Cuisines because under Cuisines colunm having multiple list csv file rows and columns please check Cuisines column and what type of model feild is required for this column -
Why extending base HTML to other templates not wokring?
I have a base.html that I want to extend to other templates. I started with contact.html. But the weird situation is that the moment I extend the base.html in contact.html, I loose my form fields. To re-assure that I can re-produce the issue, I removed the {% extends 'base.html' %} from the contacts.html and refresh the browser, I could see my form fields again. I have no idea what's missing. Below is the base.html content. base.html {% load staticfiles %} <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Bootstrap NavBar</title> <!-- Bootstrap --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> <link href="{% static 'css/topics.css' %}" rel="stylesheet"> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script> <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="navbar navbar-expand-md navbar-dark bg-dark mb-4" role="navigation"> <a class="navbar-brand" href="#">Bootstrap NavBar</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarCollapse"> <ul class="navbar-nav mr-auto"> <li class="nav-item active"> <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'BLOG:contact' %}" target="_blank">Contact</a> </li> <li class="nav-item"> <a class="nav-link disabled" … -
Django ORM to get annotated sum of related models records. (trying to use subquery in vain.)
I am currently building an image-based e-commerce website. Images are tagged with some products, and I need to get total revenue made from selling products tagged in each images. """ models.py """ class Image(AbstractImageModel): """ Images are linked to Product model via intermediary LiveProduct table. """ ... products = models.ManyToManyField( "catalogue.Product", through="ProductInImage", related_name="listed_images" ) ... class ProductInImage(TimeStampedModel): """ Intermediary model that connects Image with Products """ image = models.ForeignKey("images.Image", models.CASCADE) product = models.ForeignKey("catalogue.Product", models.CASCADE) class OrderLine(models.Model): """ An order line """ order = models.ForeignKey( 'order.Order', on_delete=models.CASCADE, related_name='lines', verbose_name=_("Order")) ... product = models.ForeignKey( 'catalogue.Product', on_delete=models.SET_NULL, blank=True, null=True, verbose_name=_("Product")) quantity = models.PositiveIntegerField(_("Quantity"), default=1) ... line_price = models.DecimalField(_("Line Price"), decimal_places=2, max_digits=12) What I am trying to get is an Image.objects queryset, annotated with total revenue made from all products tagged on each image. I have been doing something similar to the following lines, but can't seem to get in working. # to use in subquery line_qs = OrderLine.objects \ .filter(product__id__in=OuterRef("product_pk")) \ .values("line_price_excl_tax") \ .aggregate(revenue=Sum("line_price_excl_tax")) # queryset that I need: must be annotated with revenue made from all products, for each image qs = Image.objects.all() qs = qs.annotate(revenue=Subquery(line_qs.values("amount"))) Thank you very much in advance; I really appreciate your help. -
How to filter a ManyToManyfield in Django View
Como filtrar as questões relacionadas com os usuários que façam parte da categoria correspondente? views.py questoes = Questao.objects.filter(idCategoria__in=[request.user.usuario.idCategoria]) models.py class Categoria(models.Model): idCategoria = models.CharField(primary_key=True) class Usuario(models.Model): idCategoria = models.ManyToManyField(Categoria) -
Problems with virtualenv when changing to another computer with Django and Postgresql
Warning: I am very new to Django. I did the following tutorial, which uses a SQLite database. I then created a postgresql database and changed the project so that it uses this instead. Everything works well when I am on a Mac: https://realpython.com/get-started-with-django-1/ There are 2 potential problems that may be linked. FIRST PROBLEM: When I run the Django Project, I keep getting an error message on the Mac saying: You have 17 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions. Run 'python manage.py migrate' to apply them. After running 'python manage.py migrate' and then restarting the Django server, the message does not go away. This seems a bit weird but doesn't stop it from working. SECOND PROBLEM: I then check the code into GitHub. This excludes the virtual environment (venv) and the pycache files. I am using parallels. I have checked the IP address of the Mac and I can ping it from windows, so there shouldn't be any problems connecting to the database. I change the HOST setting in the setting.py file to point to the Mac. I install the code onto windows and try to recreate … -
django form action url 'abc' is redirect to abc twice
In django index.html, I have below code <form class="selectedPizza" action="{% url 'cost' %}" method="POST"> <!--Do some action here--> <form> In my app(order) urls.py from django.urls import from . import views urlpatterns = [ path("", views.index, name="index"), path("cost/", views.cost, name="cost") ] In main site(pizza) urls.py from django.contrib import admin from django.urls import include, path urlpatterns = [ path("", include("orders.urls")), path("cost/", include("orders.urls")), path("admin/", admin.site.urls), ] In views.py def index(request): #some action here return render(request, 'orders/index.html', context) def cost(request): if (request.method == 'POST'): #some action here return render(request, 'orders/cost.html', context) After submitting the form I am redirected to "http://127.0.0.1:8000/cost/cost/". I am learning Django and not able to find a possible way to get this form to redirect to cost.html page after submitting -
Deleting objects in formset django
I am going to delete one object in forms as you can see in the picture that minus button should delete existing element but it does not working. def form_valid(self, form): form.save() context = self.get_context_data() instance = self.get_object() formset = product_forms.SizeFormset(self.request.POST) if formset.is_valid(): product_sizes = product_models.Size.objects.filter(product_id=instance.id) default_item = 0 if product_sizes.exists(): product_sizes.delete() for formitem in formset: # only save if title and price is present if formitem.cleaned_data.get('title') and formitem.cleaned_data.get('price'): size = formitem.save(commit=False) size.product_id = instance.id if default_item == 0: size.default = True else: size.default = False default_item = default_item + 1 formitem.save() and in the template this code is <div class="size-add"> <button class="{% if formitem.id.value %}remove-form-row {% else %}add-form-row {% endif %} btn btn-primary"> How can I get it work? Any help? Thanks in advance! -
Get a random object of a Django Queryset but not the current one
So I have this template context processor: from cases.models import CasePage def random_case(request): case = CasePage.objects.live().order_by('?') return {'random_case': case} And in the template I do this: {% for entry in random_case %} {% if request.get_full_path != entry.get_url %} {% if forloop.first %} <a class="ajax-link project-next" href="{{ entry.get_url }}"> <div class="nav-project-title">{{ entry.title }}</div> <div class="nav-title">next</div> </a> {% endif %} {% endif %} {% endfor %} And this works but the problem is sometimes the object is the same as the page so nothing is displayed. It would be great if that one would be skipped in favour of the next entry. And it's also too much logic in the template for me. What would be the best way to move this logic into the context processor and make it work? -
Celery beat incorrectly spawns periodic tasks multiple times filling up queue
I'm developing Django application with celery task manager to perform 6 periodic tasks with following schedule: { 'daily_full_import_provider1': { 'task': 'update_data.tasks.import_full_provider_data', 'schedule': '<crontab: * */2 * * * (m/h/d/dM/MY)>', 'kwargs': { 'provider': 'provider1' } }, 'daily_full_import_provider2': { 'task': 'update_data.tasks.import_full_provider_data', 'schedule': '<crontab: * */2 * * * (m/h/d/dM/MY)>', 'kwargs': { 'provider': 'provider2' } }, 'daily_full_import_provider3': { 'task': 'update_data.tasks.import_full_provider_data', 'schedule': '<crontab: * */2 * * * (m/h/d/dM/MY)>', 'kwargs': { 'provider': 'provider3' } }, 'daily_full_import_provider4': { 'task': 'update_data.tasks.import_full_provider_data', 'schedule': '<crontab: * */2 * * * (m/h/d/dM/MY)>', 'kwargs': { 'provider': 'provider4' } }, 'daily_full_import_provider5': { 'task': 'update_data.tasks.import_full_provider_data', 'schedule': '<crontab: * */2 * * * (m/h/d/dM/MY)>', 'kwargs': { 'provider': 'provider5' } }, 'daily_full_import_provider6': { 'task': 'update_data.tasks.import_full_provider_data', 'schedule': '<crontab: * */2 * * * (m/h/d/dM/MY)>', 'kwargs': { 'provider': 'provider6' } } } Every task calls same python function with different parameters: def provider_shadow_name(task, args, kwargs, options): return "celery.import.{}".format(kwargs['provider']) @celery.task(shadow_name=provider_shadow_name) def import_full_provider_data(provider=None): return ImportWorker( ProviderService.UPDATE_OP, provider=[provider] if provider else provider )() I'm running one worker/beat/flower instance in screen: screen -S djapp_uat_celery_worker -d -m -h 500 \ $djapp_ENV/bin/celery -E -A djapp worker \ --concurrency=$djapp_CELERY_THREAD_WORKERS \ --pidfile=$djapp_VAR/djapp-celeryworker.pid \ --loglevel=INFO \ --logfile=$djapp_LOG_DIR/%p.%i.celery.worker.log screen -S djapp_uat_celery_scheduler -d -m -h 500 \ $djapp_ENV/bin/celery -A djapp beat \ --schedule=$djapp_VAR/djapp-celerybeat-schedule.db \ --pidfile=$djapp_VAR/djapp-celerybeat.pid \ --loglevel=INFO … -
Django Crispy_Form unable to render in HTML
I have been following the docs/videos online and can't seem to get my Form to render, I would be happy if someone could explain me what I am doing wrong: My goal is to get the Form to render Here is my Code: views.py I handled both cases according to request type and didn't leave the else block empty. Defined the form, didn't forget the redirect from django.shortcuts import render, redirect from django.contrib import messages from .forms import UserRegisterForm def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request, f'Account created for {username}!') return redirect('') else: form = UserRegisterForm() return render(request, 'register.html', {'form': form}) forms.py Defined a form from the existing Django Forms and included all the necessary fields from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm class UserRegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] register.html {% extends 'base.html' %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Join Today</legend> {{ form |crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Sign Up</button> </div> </form> <div class="border-top pt-3"> <small class="text-muted"> Already Have … -
Django duplicate database queries
I am using django_debug_toolbar for analyzing performance of web page. What confuses me in the results is the database queries. No matter I did everything as it should be (I suppose), results tab still shows duplicate database queries warning. For illustrating this problem, I set out django project as simple as below: models.py from django.db import models class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published', auto_now_add=True) class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) views.py from django.shortcuts import render from .models import Question, Choice def index(request): return render(request, 'polls/index.html', {'questions': Question.objects.all()}) index.html {% for question in questions %} <p>{{ question.question_text }}</p> <ul> {% for choice in question.choice_set.all %} <li>{{ choice.votes }} votes - {{ choice.choice_text }}</li> {% endfor %} </ul> {% endfor %} In the above html file and view, I load all questions and their related choices. For testing, I added only 2 question and 2 and 4 choices for them respectively (6 choices in total). And django_debug_toolbar SQL result are as below: What should I do for avoiding these duplicate SQL queries? I think that these duplicated query may have serious impacts on performance for big websites. What is your approach and best … -
How to make Django find a static css file
I am going nuts with muy current Django project and its static files. I tried different solutions on SO (e.g. Django cannot find my static files and Django Static Files CSS) and even my very own working ones from my other projects.. I just want to link a basic css file located in my projects /static/ folder to my base.html file which will contain the basic navbar for all sites/apps within the project. That's why I decided to place it in the projects directory centrally. Somehow it won't find the file though. This is my setup where debug is set to True (development, no production yet) settings.py: # this defines the url for static files # eg: base-url.com/static/your-js-file.js STATIC_URL = '/static/' # this is directory paths where you have to put your project level static files # you can put multiple folders here STATICFILES_DIRS = ( os.path.join(BASE_DIR, "static"), '/dashex/static/', ) base.html: {% load static %} [...] {% block head_css_site %} <link href="{{ STATIC_URL }}base.css" rel="stylesheet" type="text/css"> {% endblock head_css_site %} [...] project structure: error: GET http://127.0.0.1:8000/base.css net::ERR_ABORTED 404 (Not Found) -
Is there a way for a user to select an irregular geographic area on a map (on a website and app) and that to be stored?
So basically, I want the user to be able to select an area on a map, and then I would be able to return places in the area selected. My problem is how would I get the user to select the area and how would I store that? A good example would be on https://www.rightmove.co.uk/draw-a-search.html I dont know where to start with this. Is there a certain conventional way to do this. For reference, I am using python/django for my project. I need to do this on an android and ios app as well as the django site. Thanks for any help. -
How do I integrate Bootstrap 4 source files with Django 2.2?
I would like to integrate the source files of Bootstrap within my Django 2.2 web project, without using the CDN. I want to be able to completely customise my project and effect the bootstrap default settings. There seem to be no tutorials on how to do this, and the proper file structure once complete. I would love to know exactly how to download bootstrap files into my Django project, and the exact file structure, in a way that can be used during deployment also. I have copied and pasted all Bootstrap 4 files into the static sections of my Django project, however I can not seem to make changes to the __variables.scss file and it is saying in a lot of documentation that this isn't best practise anyhow. I have been using Koala to compile the SCSS into the CSS files but again I don't know if this is recommended and I would like to get it done the 'correct' way straight from the off. At the end I would like to fully incorporate Bootstrap and the Bootstrap JS into my project without using the CDN method as I would like complete customisation, with the file structure being as close … -
Registration with email django doesn't work
I want to implement registration with email verification in Django. Filled registration form --- OK Received email with link --- OK http://127.0.0.1/accounts/register/activate/mosk:tQUC9n5kMrmoVSZv4qy6DCAUjaM/ Clicked to the link --- received ERROR: This site can’t be reached127.0.0.1 refused to connect How can I solve the error??? It seems that urls.py is OK and I should add something to ALLOWED_HOSTS Image settings.py DEBUG = True ALLOWED_HOSTS = ['127.0.0.1'] STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') AUTH_USER_MODEL = 'blog.AdvUser' EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'alekmosk25@gmail.com' EMAIL_HOST_PASSWORD = '*****' DEFAULT_FROM_EMAIL = 'Alex' DEFAULT_TO_EMAIL = 'msumoskalenko@gmail.com' EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' models.py from django.db import models from django.contrib.auth.models import AbstractUser from django.dispatch import Signal from .utilities import send_activation_notification class AdvUser(AbstractUser): is_activated = models.BooleanField(default=True, db_index=True, verbose_name='Пpoшeл активацию?') send_messages = models.BooleanField(default=True, verbose_name='Слать оповещения о новых комментариях?') class Meta(AbstractUser.Meta): pass user_registrated = Signal(providing_args=['instance']) def user_registrated_dispatcher(sender, **kwargs): send_activation_notification(kwargs['instance']) user_registrated.connect(user_registrated_dispatcher) forms.py class RegisterUserForm(forms.ModelForm): email = forms.EmailField(required=True, label="Email address") password1 = forms.CharField(label="Password", widget=PasswordInput, help_text=password_validation.password_validators_help_text_html()) password2 = forms.CharField(label="Password", widget=PasswordInput, help_text=password_validation.password_validators_help_text_html()) def clean_password1(self): password1 = self.cleaned_data['password1'] if password1: password_validation.validate_password(password1) return password1 def clean(self): super().clean() password1 = self.cleaned_data.get('password1') password2 = self.cleaned_data.get('password2') if password1 and password2 and password1 != password2: errors = {'password2': ValidationError('Введённые пароли не совпадают', code='password_mismatch')} raise ValidationError(errors) else: return self.cleaned_data … -
how solve JSONDecodeError at /api/customer/order/add/ Expecting property name enclosed in double quotes: line 1 column 30 (char 29)
JSONDecodeError at /api/customer/order/add/ Expecting property name enclosed in double quotes: line 1 column 30 (char 29) Request Method: POST Request URL: http://localhost:8000/api/customer/order/add/?= Django Version: 2.2.6 Exception Type: JSONDecodeError Exception Value: Expecting property name enclosed in double quotes: line 1 column 30 (char 29) Exception Location: /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/decoder.py in raw_decode, line 353 Python Executable: /Users/sandip/Desktop/myvirtualenv/foodtasker/bin/python Python Version: 3.7.3 SELECT APAIS import json from django.utils import timezone from django.http import JsonResponse from django.views.decorators.csrf import csrf_exempt from oauth2_provider.models import AccessToken from foodtaskerapp.models import Restaurant, Meal, Order, OrderDetails from foodtaskerapp.serializers import RestaurantSerializer, MealSerializer def customer_get_restaurants(request): restaurants = RestaurantSerializer( Restaurant.objects.all().order_by("-id"), many = True, context = {"request": request} ).data return JsonResponse({"restaurants": restaurants}) def customer_get_meals(request, restaurant_id): meals = MealSerializer( Meal.objects.filter(restaurant_id = restaurant_id).order_by("-id"), many = True, context = {"request": request} ).data return JsonResponse({"meals": meals}) @csrf_exempt def customer_add_order(request): """ params: access_token restaurant_id address order_details (json format), example: [{"meal_id": 1, "quantity": 2},{"meal_id": 2, "quantity": 3}] stripe_token return: {"status": "success"} """ if request.method == "POST": # Get token access_token = AccessToken.objects.get(token = request.POST.get("access_token"), expires__gt = timezone.now()) # Get profile customer = access_token.user.customer # Check whether customer has any order that is not delivered if Order.objects.filter(customer = customer).exclude(status = Order.DELIVERED): return JsonResponse({"status": "failed", "error": "Your last order must be completed."}) # Check Address … -
Django, Check if checkbox is selected without submit or dynamically to update text
https://ibb.co/WxBfb3N Is there a way to check if a checkbox is selected without needing to submit? also I want the amount to change, I already have the choices ready with class ServiceForm(forms.ModelForm): CHOICES = ( (350, 'Nuat Thai Foot Massage(1hour)'), (350, 'Thai Body massage w/ Oil(1hour)'), (400, 'Sweddish Massage(1hour)'), (400, 'Armoatherapy Massage(1hour)'), (250, 'Express - Back and Head(30 mins)'), (250, 'Foot Massage(30 mins)'), (250, 'Back Massage(30 mins)'), (250, 'Head massage(30 mins)'), ) choices = MultiSelectFormField(choices=CHOICES) so in the picture when more than 1 of this is selected, I want the value to be added then be displayed. I want to be avoid submit button but if there is no such way, How can I do it with submit? -
Django templated does not display inputs to be filled
I need a call a form on an HTML template where the user posts data which saves to model The code is running without any errors But the html page display only title and button No text input fields I have a form which is to be displayed on a html page so the user can input data and it saves the data into the model.I am not getting any errors while executing th code but the template does not display the form it just shows the title and submit button def boqmodel1(request): form = boqform(request.POST) if form.is_valid(): obj=form.save(commit=False) obj.save() context = {'form': form} return render(request, 'create.html', context) else: context = {'error': 'The post has been successfully created. Please enter boq'} return render(request, 'create.html', context) MyTemplate <form action="" method="POST"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Create boq"/> </form> MY Url urlpatterns = [ url(r'^create/', views.boqmodel1, name='boqmodel1'), path('', views.boq, name='boq'), ] -
Displaying the same notification on all pages in the django application
I have a problem where I can't sleep ... I hope you will help. Well, in my application, creating a profile is like two stages, i.e. first you register, log in, and then you can go to the page where you can fill in your personal data, name, surname, etc. And my question is, is there any way that until these data have been filled in on each page in the designated place, a message appears encouraging you to complete the form? And the second question is, does anyone know a way that before filling out the form, let's give the "profile" on the page a form, and after filling it in entered data (without the form or editing option)? I hope you understood what I meant. -
I want to accept the data from user input in the form table generated dynamically
I want to pass the data from user input in the template create_proposal.html. The form is inside a dynamically generated table by JavaScript. Each row has cells that have input. The table inside create_proposal.html looks like: <table id="empTable" class="table-striped" border="1" cellmargin="100px" cellpadding="0px"cellspacing="5px"> <tr> <th> <h5></h5> </th> <th> <h5>No.</h5> </th> <th> <h5>Part no.</h5> </th> <th style="width:30vw"> <h5>Description</h5> </th> <th> <h5>Quantity</h5> </th> <th> <h5>Unit Market price</h5> </th> <th> <h5>Markup percentage</h5> </th> </tr> </table> And the script that generates the rows: <script> // ARRAY FOR HEADER. var arrHead = new Array(); arrHead = ['', 'No.', 'Part no.', 'Description', 'Quantity', 'Unit market price', 'Markup percentage']; // ADD A NEW ROW TO THE TABLE.s function addRow() { var empTab = document.getElementById('empTable'); var rowCnt = empTab.rows.length; // GET TABLE ROW COUNT. var tr = empTab.insertRow(rowCnt); // TABLE ROW. tr = empTab.insertRow(rowCnt); for (var c = 0; c < arrHead.length; c++) { var td = document.createElement('td'); // TABLE DEFINITION. td = tr.insertCell(c); if (c == 0) { // FIRST COLUMN. // ADD A BUTTON. var button = document.createElement('input'); // SET INPUT ATTRIBUTE. button.setAttribute('type', 'button'); button.setAttribute('value', 'Remove'); button.setAttribute('class', 'btn btn-danger'); // ADD THE BUTTON's 'onclick' EVENT. button.setAttribute('onclick', 'removeRow(this)'); td.appendChild(button); } else if(c == 1){ var ele = document.createElement('input'); … -
How to create Django objects that have foreign key field referenced on field which haven't contain data
I faced with problem while creating django objects. I have two models class League(models.Model): league_id=models.IntegerField (primary_key=True) league_name=models.CharField (max_length=20) league_logo = models.URLField (null = True) league_flag = models.URLField(null = True) standings=models.IntegerField (null=True) is_current = models.IntegerField (null=True) class Fixture(models.Model): fixture = models.IntegerField (primary_key=True) league_id=models.ForeignKey ('League',null=True, on_delete=models.SET_NULL) event_date = models.DateTimeField(null=True) event_timestamp= models.DateTimeField (null=True) When i am trying to create object from my fixture model and in this time i have not any data in league table. I get an error that Traceback (most recent call last): File "<console>", line 1, in <module> File "/data/data/com.termux/files/home/storage/predictions/forecast/odds.py", line 53, in <module> fixt = Fixture.objects.create_or_update(fixture_id = fixture_id,league_id_id = league_id,event_date = event_date,) AttributeError: 'Manager' object has no attribute 'create_or_update' >>> import odds /data/data/com.termux/files/home/storage/predictions/forecast Traceback (most recent call last): File "/data/data/com.termux/files/home/storage/predictions/env/lib/python3.7/site-packages/django/db/backends/base/base.py", line 240, in _commit self._commit() File "/data/data/com.termux/files/home/storage/predictions/env/lib/python3.7/site-packages/django/db/backends/base/base.py", line 240, in _commit return self.connection.commit() File "/data/data/com.termux/files/home/storage/predictions/env/lib/python3.7/site-packages/django/db/utils.py", line 89, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "/data/data/com.termux/files/home/storage/predictions/env/lib/python3.7/site-packages/django/db/backends/base/base.py", line 240, in _commit return self.connection.commit() django.db.utils.IntegrityError: insert or update on table "dataflow_fixture" violates foreign key constraint "dataflow_fixture_league_id_id_674984dc_fk_dataflow_" DETAIL: Key (league_id_id)=(780) is not present in table "dataflow_league". Like i understand this error occur because while i am creating a fixture object and process of creating reach league_id field and its reference to league_id … -
Need help after upgrading Django
I upgraded Django 2.2.5 to 2.2.6 and now I got the error: Message=Failed lookup for key [title] in [{'True': True, 'False': False, 'None': None}, {'csrf_token': <SimpleLazyObject: <function csrf.<locals>._get_val at 0x0000023044F223A8>>, 'request': <WSGIRequest: GET '/'>, 'user': <SimpleLazyObject: <function AuthenticationMiddleware.process_request.<locals>.<lambda> at 0x0000023044E74D38>>, 'perms': <django.contrib.auth.context_processors.PermWrapper object at 0x0000023045017688>, 'messages': <django.contrib.messages.storage.fallback.FallbackStorage object at 0x0000023044F3A388>, 'DEFAULT_MESSAGE_LEVELS': {'DEBUG': 10, 'INFO': 20, 'SUCCESS': 25, 'WARNING': 30, 'ERROR': 40}}, {}, {'form': <AuthenticationForm bound=False, valid=Unknown, fields=(username;password)>, 'view': <django.contrib.auth.views.LoginView object at 0x0000023044F3AC08>, 'next': '', 'site': <django.contrib.sites.requests.RequestSite object at 0x0000023044F65088>, 'site_name': 'localhost:65093', 'LANGUAGE_CODE': 'da-dk', 'LANGUAGE_BIDI': False}, {'block': <Block Node: title. Contents: [<Variable Node: title>, <TextNode: ' | '>, <Variable Node: site_title|default:_('Django site admin')>]>}] Source=C:\Users\WestcoastComputer\Development\env\pyØkonomiWeb\Lib\site-packages\django\template\base.py StackTrace: File "C:\Users\WestcoastComputer\Development\env\pyØkonomiWeb\Lib\site-packages\django\template\base.py", line 850, in _resolve_lookup (bit, current)) # missing attribute File "C:\Users\WestcoastComputer\Development\env\pyØkonomiWeb\Lib\site-packages\django\template\base.py", line 796, in resolve value = self._resolve_lookup(context) File "C:\Users\WestcoastComputer\Development\env\pyØkonomiWeb\Lib\site-packages\django\template\base.py", line 671, in resolve obj = self.var.resolve(context) File "C:\Users\WestcoastComputer\Development\env\pyØkonomiWeb\Lib\site-packages\django\template\base.py", line 987, in render output = self.filter_expression.resolve(context) File "C:\Users\WestcoastComputer\Development\env\pyØkonomiWeb\Lib\site-packages\django\template\base.py", line 904, in render_annotated return self.render(context) File "C:\Users\WestcoastComputer\Development\env\pyØkonomiWeb\Lib\site-packages\django\template\base.py", line 937, in render bit = node.render_annotated(context) File "C:\Users\WestcoastComputer\Development\env\pyØkonomiWeb\Lib\site-packages\django\template\base.py", line 904, in render_annotated return self.render(context) File "C:\Users\WestcoastComputer\Development\env\pyØkonomiWeb\Lib\site-packages\django\template\base.py", line 937, in render bit = node.render_annotated(context) File "C:\Users\WestcoastComputer\Development\env\pyØkonomiWeb\Lib\site-packages\django\template\base.py", line 163, in _render return self.nodelist.render(context) File "C:\Users\WestcoastComputer\Development\env\pyØkonomiWeb\Lib\site-packages\django\template\base.py", line 904, in render_annotated return self.render(context) File "C:\Users\WestcoastComputer\Development\env\pyØkonomiWeb\Lib\site-packages\django\template\base.py", line 937, in render bit = …