Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to have both author and participants in a model
Currently I have a post model in my models.py class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name="author") participants = models.ManyToManyField(User) quiet_tag = models.BooleanField("Quiet") camera_tag = models.BooleanField("Camera On") def __str__(self): return self.title def get_absolute_url(self): return reverse("post-detail", kwargs={"pk": self.pk}) I want to be able to have the functionaliy where a participant can request to join an author's post if the author accepts their request. Currently my model class is adding every single user to the post. Any idea would help a lot! thanks! -
How to resolve django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS error. DUPLICATED, but none of the answers worked for me
I am new to Django and I am getting this error when I try to run python3 poppulate_first_app.py file (using Kali Linux and venv with django 3.1.7). Error... Traceback (most recent call last): File "/home/hadi/Documents/first_django_project/poppulate_first_app.py", line 4, in <module> from first_app.models import * File "/home/hadi/Documents/first_django_project/first_app/models.py", line 6, in <module> class Topic(models.Model): File "/home/hadi/Documents/first_django_project/venv/lib/python3.9/site-packages/django/db/models/base.py", line 108, in __new__ app_config = apps.get_containing_app_config(module) File "/home/hadi/Documents/first_django_project/venv/lib/python3.9/site-packages/django/apps/registry.py", line 253, in get_containing_app_config self.check_apps_ready() File "/home/hadi/Documents/first_django_project/venv/lib/python3.9/site-packages/django/apps/registry.py", line 135, in check_apps_ready settings.INSTALLED_APPS File "/home/hadi/Documents/first_django_project/venv/lib/python3.9/site-packages/django/conf/__init__.py", line 82, in __getattr__ self._setup(name) File "/home/hadi/Documents/first_django_project/venv/lib/python3.9/site-packages/django/conf/__init__.py", line 63, in _setup raise ImproperlyConfigured( 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 tried to run it on Windows too, but the same error, also I recreate the projcet in case I miss with settings or something, also I tried most of the answers posted here but none of them worked for me. I do not know why. so depressing! Here is my poppulate_first_app.py code: import django import random from faker import Faker from first_app.models import * import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'first_project.settings') django.setup() # FAKE POP SCRIPT fake_gen = Faker() topics = ['Search', 'Social', 'Marketplace', 'News', 'Games'] def add_topic(): t = … -
Heroku background services writing to database
I need a web service that continuously pulls data from a remote server, stores it and makes it accessible to other clients. My idea was to use (1) a Heroku web service with Django for web access and (2) a Heroku clock scheduler to run a run a script repetitively in the background. However, while the script runs fine, i am stuck with how to write back the data to the Django data model. Trying to create instances of my Django data models causes an exception (app has not been loaded yet), probably because both services run independently. So, what would be the best setup for my problem? It seems like a very common task so i am probably missing something obvious. Thanks! -
How to Serilize a Model when it has Foriegn Key Relation with default User Model in Django
Models.py I have Model named Message it has Foriegn Key Realation with default User Model Django .i want to serilize this model. from django.db import models from django.contrib.auth.models import User from django.conf import settings class Message(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,) content=models.CharField(max_length=100) timestamp=models.DateTimeField(auto_now_add=True) def __str__(self): return self.author.username views.py from classes.models import ClassRoom,Student from classes import views from django.http import HttpResponse, JsonResponse from django.contrib.auth.models import User from chat.models import Message from django.contrib.auth.decorators import login_required from django.http import HttpResponse from django.shortcuts import render from django.core import serializers @login_required def course_chat_room(request,id): course = ClassRoom.objects.get(id=id) return render(request, 'chat/room.html',{'course':course}) def getMessages(request,id): serials = serializers.serialize('json', Message.objects.all().order_by("-id")) return JsonResponse(serials, safe=False) urls.py here is my urls of this app from django.urls import path from . import views app_name = 'chat' urlpatterns = [ path('room/<int:id>/', views.course_chat_room,name='course_chat_room'), path('room/<int:id>/ajax/', views.getMessages,name='getMessages'), ] Result when i run this i got the result like this below.i get the author id =10,11,9 etc i want the username instead .how to do this .i know about one technique i.e use_natural_foriegn key but i did not impelemt it in user model in this,because i dont know to to write manager for default user model .The data of message model is saved in database i retrived it in json format … -
Class Based Multi Environment Django Settings
In an effort to avoid from .local_settings import * and based on that post, I created a class-based settings file. The idea is to have a Common class which is inherited from Dev or Prod class as such: ./my_project/settings.py: import sys settings_module = sys.modules[__name__] class Common: SETTING1 = 'set' SETTING2 = 'set again' def __init__(self): for each in dir(self): if each.isupper(): setattr(settings_module, each, getattr(self, each)) class Dev(Common): SETTING1 = 'set_dev' class Prod(Common): SETTING1 = 'set_prod' #initialize the chosen class Prod() Is it a good idea? Django imports the settings as a module and discourages any other use. It seems to be working. -
How to hand it over to python shell from within a python script? [closed]
I want a python script to setup some context and variables and then give me the python shell and enable me interactive execution of python commands. I have seen this pattern in Django shell. My question is, what is the correct way of implementing such a feature? -
Django: Making a new copy of an mp3 file with a new name in a new folder
I want to copy the latest uploaded mp3 file from the object list in my first model (which uses the default media folder) to a new folder called ‘latest’ and I also want to rename the new copy ‘latest.mp3’. This is so that I have a known filename to be able to process the latest uploaded file using Javascript. I wish to also keep the original, unaltered, uploaded file in the object list of my first model. The below is what I have so far but it doesn’t work: I don’t get any traceback error from the server or from the browser. However, the copy isn’t made in the ‘latest/’ folder. I believe I am doing more than one thing wrong and I am not sure if I should be using CreateView for the SoundFileCopy view. I am also not sure when the process in SoundFileCopy view is triggered: I am assuming it happens when I ask the browser to load the template ‘process.html’. I am using Django 3.1.7 If anyone can help me by letting me know what I need to put in my models, views and template to get this to work I would be very grateful. Currently … -
Toggle does not display. Django
I am currently following this tutorial but with my own template that I got from w3layouts. I am using it as a practice project to better learn Django. I am currently trying to implement a user login/signup page. When you click on the icon/image that represents the user, you are supposed to be treated with a drop down lift of, My account, my favorites, my cart etc. etc. As I am using a different template from the one in the video, I understand that there may be issues. The following is the Lecturers( guys tutorial I'm following) drop down for user functionality. <li class="header-account dropdown default-dropdown"> {% if user.id is not None %} <div class="dropdown-toggle" role="button" data-toggle="dropdown" aria-expanded="true"> <div class="header-btns-icon"> <img src="{{ request.session.userimage }}" style="height: 40px; border-radius: 30%"> </div> <strong class="text-uppercase">{{ user.first_name }} <i class="fa fa-caret-down"></i></strong> </div> {% else %} <a href="{% url 'login' %}" class="text-uppercase">Login</a> / <a href="{% url 'signup' %}" class="text-uppercase">Sign Up</a> {% endif %} <ul class="custom-menu"> <li><a href="{% url 'user_index' %}"><i class="fa fa-user-o"></i> {% trans "My Account" %}</a></li> <li><a href="#"><i class="fa fa-heart-o"></i> {% trans "My Favorits" %}</a></li> <li><a href="{% url 'user_orders' %}"><i class="fa fa-exchange"></i> {% trans "My Orders " %}</a></li> <li><a href="{% url 'user_comments' %}"><i class="fa fa-check"></i> … -
Derive a schema version of a model class?
I have a use case where I want to serialize list of model instances and store it. Along with it, I want to store a "schema version" Now when I deserialize these model instances, I want to be sure that the model schema didn't change. If it didn't change I'll use the deserialized models. if it did change, I'll fall back to query from the database Roughly something like this from django.core import serializers def serialize(instances): return json.dumps({ "data": serializers.serialize('json', instances), "version": schema_version_for(MyModel) }) def deserialize(serialized): data = json.loads(serialized) version = data["version"] instances = serializers.deserialize('json', data["data"]) if version != schema_version_for(MyModel): # fall back to query from database return MyModel.objects.filter(id__in=[o.id for o in instances]) else: return instances Whats the best implementation of schema_version_for(ModelCls) I'm thinking around using the field names and field types to generate some sort of version. If you know of a better way to implement this, I'd love to hear. -
django filter with pagnition
Actually I have two inquiries. I looked a lot for answers, but I could not find. 1 _ How to add multiple pagination to same view ? 2 _ How to add options to the filter, such as dropdown ? this is my view.py: def Multimedia_Software(requset): category = Categorie.objects.all() Multimedia_Software = Apps.objects.filter(category=category[6]).order_by('App_title') myFilter = AppsFilter (requset.GET,queryset = Multimedia_Software) Multimedia_Software = myFilter.qs paginator = Paginator(Multimedia_Software,15) page = requset.GET.get('page') try: Multimedia_Software=paginator.page(page) except PageNotAnInteger: Multimedia_Software=paginator.page(1) except EmptyPage: Multimedia_Software=paginator.page(paginator.num_pages) context = { 'page':page, 'Multimedia_Software':Multimedia_Software, 'myFilter':myFilter, } return render( requset , 'windows/Multimedia_Software.html' , context ) this my filter.py: import django_filters from .models import Apps class AppsFilter (django_filters.FilterSet): App_license = django_filters.CharFilter(label='Filter the license' ) class Meta: model = Apps fields = ['App_license'] this is my model.py: App_license = models.CharField(max_length=100 , null=True) I used pagination with first queryset and I want to use it too with filter.How is this done? and How can I add options to the filter? -
Case/When Annotation on m2m field relationship is duplicating results
I am trying to annotate the existence of a m2m relationship onto a model's queryset. Models class Dog(models.Model): text = CharField(max_length=10) class Animal(models.Model): member = ManyToManyField(Dog, related_name='members') I want to build a query for Dog that annotates a BooleanField of whether Animal contains an M2M relationship for that Dog. This is what I've come up with so far, but it is returning a duplicate result for every relationship_exists = True (so one record with True, one with False) Current Query animal_id = Animal.objects.get(id=1).id queryset = Dog.objects.all().annotate( relationship_exists = Case( When(members__in=[animal_id], then=Value(True)), When(~Q(members__in=[animal_id], then=Value(False)), default=Value(False), output_field=NullBooleanField() ) ) Which would return not only all records where relationship_exists=True, but also for each of those True records, it would have a corresponding record of the same Dog with relationship_exists=False. I've tried setting the default to None and Coalescing the value, I've tried eliminating my second When clause and setting default value to None. None of it is working, and I'm not sure why this is the case. -
Django 3: Forgotten Password Reset: Is there a way to block password reset view to appear when ther user is logged in?
I have implemented a built in Django password reset procedure using django.contrib.auth.views. It works, but there is a problem, when the user is logged in he/she still can type in password reset url and then reset the password. I would like to prevent password reset view to appear when the user is logged in. What is the best way to achieve this? -
python elasticsearch error in modifying and adding doc during remote access
Hello I have some questions.. I developed django website on Windows 10 and changed OS to ubuntu for publishing On Windows, there were no problems but problems appeared on ubuntu My website uses a remote access on EleasticSearch and also uses elasticsearch, elasticsearch_dsl python lib. There was no error searching the document in index from an external connection, but an error occurs when adding update_by_query or a new document. There are no other settings except for modifying network.host in elasticsearch.yml to 0.0.0.0 Do I need special permissions or other settings to modify or create documents from outside? I am so stressed because of this. If anyone knows, I'm sure you're busy, but please give me a detailed explanation or a link. Thank you. -
Django loader while waiting for api response
I'm trying to put a loader while I'm waiting for the response from an api, because the loading time sometimes is high. The flow is the following: I made a form that leads to a payment api, and after the payment, the web app invokes another api which tries to do something, and that something sometimes takes too much time and the user may think something went wrong. So, my question is how could I put a spinner, or a loader, when waiting for the respose, and after the response is fetched, it redirects the user to the normal flow (a landing page that shows success or fail) -
ImportError: cannot import "url" from "app's" directory to project's urls.py
I am using Django==3.1.4. this is folder structure: - backend - urls.py - base - urls - order_urls.py - user_urls.py - product_urls.py - views inside backend/urls.py, i have this: from django.contrib import admin from django.urls import path,include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), // user_urls, order_urls, product_urls are inside base/urls directory path('api/users/', include('base.urls.user_urls')), path('api/orders/', include('base.urls.order_urls')), path('api/products/',include('base.urls.product_urls')), ] urlpatterns +=static (settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) if i call python3 manage.py runserver, I get this error: Exception in thread django-main-thread: Traceback (most recent call last): File "/home/my-desktop/anaconda3/lib/python3.8/threading.py", line 932, in _bootstrap_inner self.run() File "/home/my-desktop/anaconda3/lib/python3.8/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/home/my-desktop/Documents/projects/next.js/django-bingology/myenv/lib/python3.8/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/home/my-desktop/Documents/projects/next.js/django-bingology/myenv/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "/home/my-desktop/Documents/projects/next.js/django-bingology/myenv/lib/python3.8/site-packages/django/core/management/base.py", line 392, in check all_issues = checks.run_checks( File "/home/my-desktop/Documents/projects/next.js/django-bingology/myenv/lib/python3.8/site-packages/django/core/checks/registry.py", line 70, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "/home/my-desktop/Documents/projects/next.js/django-bingology/myenv/lib/python3.8/site-packages/django/core/checks/urls.py", line 13, in check_url_config return check_resolver(resolver) File "/home/my-desktop/Documents/projects/next.js/django-bingology/myenv/lib/python3.8/site-packages/django/core/checks/urls.py", line 23, in check_resolver return check_method() File "/home/my-desktop/Documents/projects/next.js/django-bingology/myenv/lib/python3.8/site-packages/django/urls/resolvers.py", line 408, in check for pattern in self.url_patterns: File "/home/my-desktop/Documents/projects/next.js/django-bingology/myenv/lib/python3.8/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/my-desktop/Documents/projects/next.js/django-bingology/myenv/lib/python3.8/site-packages/django/urls/resolvers.py", line 589, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/home/my-desktop/Documents/projects/next.js/django-bingology/myenv/lib/python3.8/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/my-desktop/Documents/projects/next.js/django-bingology/myenv/lib/python3.8/site-packages/django/urls/resolvers.py", line 582, in … -
Django Rest Framework how to set error_messages on models.CharField
Hi! summarize the problem I have a Django Rest Framework backend, on which I want to do a simple thing: change default validation message: 'max_length': _('Ensure this field has no more than {max_length} characters.'), To a custom one like 'max_length': 'I am happy to see you {max_length}.' methods that failed are on the bottom of this post minimal example: from django.contrib.auth.models import ( AbstractBaseUser, PermissionsMixin, ) from django.db import models from rest_framework import serializers class User(AbstractBaseUser, PermissionsMixin): name = models.CharField("Name", max_length=42, null=True, error_messages={'max_length':"I am happy to see you {max_length}."}) class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ["name"] extra_kwargs = { "name": {"required": True, "allow_blank": False, "allow_null": False}, } error messages seem to be ignored. What failed: error_messages as a CharField argument (as shown in example) based on this issue, I tried setting up a validatior argument for CharField, like: validators=[MaxLengthValidator(42, message="I am happy to see you {max_length}.")] based on a very similar stack question I tried adding a custom CharField class. Maybe I didnt understand their solution, because inheriting from fields.CharField didnt allow me to set stuff into init method (I use model.CharField, they use field.Charfield. It didnt work either way. Based on this issue I started wondering … -
Get key-value pairs of specific fields from Many-to-many related models without duplication
I want to get the keys and values of the specific fields from two models with one queryset. I use a many-to-many relationship between them. I use this queryset: Article.objects.values('title', 'topic__title')[:9] My models (shotlisted most of the fields for simplicity): class Article(models.Model): title = models.CharField('Title', max_length=99) topic = models.ManyToManyField('Topic', related_name='articles') body = RichTextField(blank=True, null=True) class Topic(models.Model): title = models.CharField(max_length=150) body = RichTextField(blank=True, null=True) This queryset returns one Article object multiple times if that Article object has multiple topics. How can I get only specified keys without sacrificing performance (with one query if possible)? I want queryset to return a list of dicts like this (anything near to it is acceptable as well): [ { "title": "Hello world", "topic__title": ["Programming", "Tutorial"] }, { "title": "Let's start coding", "topic__title": "Tutorial" } ] Please provide your code with an explanation and your suggestions are very welcome and highly appreciated. -
show only one type of user in forms using django
I'm trying to create an appointment app using Django but when I add the form it show me all the users how can i change that to only one type of user and make the user who register the appointment him self this is my models.py class User(AbstractUser): STATUS_CHOICES = (('paitent', 'paitent'), ('Doctor', 'Doctor'), ('reception', 'reception'), ('temporary', 'temporary')) STATUS_CHOICES_2 = (('yes', 'yes'), ('no', 'no')) type_of_user = models.CharField(max_length=200, choices=STATUS_CHOICES, default='paitent') allowd_to_take_appointement = models.CharField(max_length=20, choices=STATUS_CHOICES_2, default='yes') def is_doctor(self): if self.type_of_user == 'Doctor': return True else: return False def is_paitent(self): if self.type_of_user == 'paitent': return True else: return False class Appointement_P(models.Model): user_ho_add = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user_ho_add_appointement') patient = models.ForeignKey(User, null=True, on_delete=models.SET_NULL, related_name='paitent_app') doctor = models.ForeignKey(User, on_delete=models.CASCADE, related_name='doctor_app') date = models.Field(null=True, blank=True, default=timezone.now) start_time = models.TimeField(null=True, blank=True, default=timezone.now) end_time = models.TimeField(null=True, blank=True, default=timezone.now) and this is my fomrs.py class AppointementForm(forms.ModelForm): class Meta: model = Appointement_P fields = ('doctor', 'date', 'start_time',) and this is my fucntion in the views.py def create_appointement_p(request): user = User() form_appointement = AppointementForm() if request.method=='POST': if request.user.is_paitent(): form_appointement = AppointementForm(request.POST or None) if form_appointement.is_valid(): form_app = form_appointement.save(commit=False) form_app.save() messages.success(request, 'appointement added') else: messages.error(request, 'Error') return render(request,'appointement/add_appointement1.html',) else: return HttpResponseRedirect(reverse("create_appointement_D")) return render(request,'appointement/add_appointement1.html',{'form':form_appointement}) and this is the html file <body> <div class="container"> {{ … -
Django Query - Get list that isnt in FK of another model
I am working on a django web app that manages payroll based on reports completed, and then payroll generated. 3 models as follows. (ive tried to limit to data needed for question). class PayRecord(models.Model): rate = models.FloatField() user = models.ForeignKey(User) class Payroll(models.Model): company = models.ForeignKey(Company) name = models.CharField() class PayrollItem(models.Model): payroll = models.ForeignKey(Payroll) record = models.OneToOneField(PayRecord, unique=True) What is the most efficient way to get all the PayRecords that aren't also in PayrollItem. So i can select them to create a payroll item. There are 100k records, and my initial attempt takes minutes. Attempt tried below (this is far from feasible). records_completed_in_payrolls = [ p.report.id for p in PayrollItem.objects.select_related( 'record', 'payroll' ) ] -
Django. How to send non english word in url?
The project is a dictionary of Russian terms that can be translated into any other language. Here are a few Django models to be aware of. class Term_rus(models.Model): subject = models.ForeignKey(Subject, on_delete=models.CASCADE) name = models.CharField(max_length=128) definition = models.TextField() image = models.ImageField(default='', blank=True) class Term_foreign(models.Model): term_rus = ForeignKey(Term_rus, on_delete=models.CASCADE) language = models.ForeignKey(Language, on_delete=models.CASCADE) name = models.CharField(max_length=128) definition = models.TextField() image = models.ImageField(default='', blank=True) The hosting I use is provided by MySQL 5.7. Here is the database setup in the settings.py file. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'dictionary_db', 'USER': 'user', 'PASSWORD': 'password', 'HOST': 'localhost', 'OPTIONS': { 'init_command': "SET sql_mode='STRICT_TRANS_TABLES';", 'charset': 'utf8', 'use_unicode': True, }, } } I also configured Server connection collation and Database collation to utf8_general_ci in the database settings on the server. The site should be able to search for terms in any language. Here is the URL path to redirect to when searching. urlpatterns = [ ... path(r'<str:language>/search/<str:search_string>', views.search_results, name='search_results'), ] And here is a method search_results. def search_results(request, language, search_string): if request.method == 'POST': search_string = request.POST.get('search_string') return redirect('search_results', language, search_string) else: ... terms search ... Also, if you need a search form and html code: class SearchForm(forms.Form): search_string = forms.CharField(label='', widget=forms.TextInput(attrs={'class': 'input', 'placeholder': 'Найти'})) … -
How to set the language for the whole session after login in Django
I'm stuck, trying to set the language for an entire session, so that the menus, forms, etc. are displayed according to the language entered during login. For this I have defined the following: In the settings.py file add the middleware: 'django.middleware.locale.LocaleMiddleware', MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] Also add the context renderer: 'django.template.context_processors.i18n' And I defined my 3 languages: LANGUAGE_CODE = 'es' LANGUAGES = [ ('es' _('Spanish')), ('en', _ ('English')), ('it', _ ('Italian')), ] This is my view: class LoginFormView(FormView): form_class = UserLoginForm template_name = 'login.html' success_url = reverse_lazy('index') def dispatch(self, request, *args, **kwargs): if request.user.is_authenticated: return HttpResponseRedirect(self.success_url) return super().dispatch(request, *args, **kwargs) def form_valid(self, form): login(self.request, form.get_user()) user_language = self.request.POST.get('language', None) translation.activate(user_language) self.request.session['django_language'] = user_language self.request.session[translation.LANGUAGE_SESSION_KEY] = user_language return HttpResponseRedirect(self.success_url) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['title'] = 'Iniciar sesión' return context Despite this, the language after login does not change and always remains in Spanish. All templates have the tag: {% load i18n %} I also tried to force the language change by placing a button in the navigation bar, in order to test if the translation works and is indeed working well: <button type="button" class="btn-shadow p-1 btn btn-primary btn-sm"> {% include 'change_language.html' … -
How to fix it Django, Jquery, AJAX and JSON HTTP 500
I am creating the app which books a vizit time. I am trying to show if the time is reserved in my template. I take this code from a working project. But it doesnt work in my project. When I choose any date I have this error Failed to load resource: the server responded with a status of 500 () html {% block content %} <div class="container"> <h3>{{service.name|safe}}</h3> <div align="center"> <form action="" class="form-inline" method="post" enctype="multipart/form-data"> {% csrf_token %} <div class="form-group"> <table class="table table-borderless"> <tr><th>{{form.date.label}}</th><td>{{form.date}}{{form.date.errors}}<br><br></td></tr> <tr><th>{{form.time.label}}</th> <td> <table class="table table-bordered"> <tr> <td align="center" valign="center" class="time">9:00</td> <td align="center" valign="center" class="time">10:00</td> <td align="center" valign="center" class="time">11:00</td> </tr> <tr> <td align="center" valign="center" class="time">12:00</td> <td align="center" valign="center" class="time">13:00</td> <td align="center" valign="center" class="time">14:00</td> </tr> <tr> <td align="center" valign="center" class="time">15:00</td> <td align="center" valign="center" class="time">16:00</td> <td align="center" valign="center" class="time">17:00</td> </tr> </table> {{form.time.errors}} </td></tr> <tr><th> {{form.name.label}}</th><td>{{form.name}}{{form.name.errors}}<br><br></td></tr> <tr><th>{{form.info.label}}</th><td>{{form.info}}{{form.info.errors}}<br><br></td></tr> </table> {{form.time}} <div style="padding-left:20%;"><button id="submit" class="btn btn-success">Запись</button></div> </div> </form> </div> </div> <script type = "text/javascript"> $("#id_date").datepicker({ dateFormat: 'yy-mm-dd', }); $(document).ready(function() { //the date is sent via Ajax to the server for comparison // a list with the reserved time for receiving is returned, for comparison with the table var checkUnavailableTime = function() { var date_data = { service_id: {{service.id}}, date_from_ajax: $("input[name=date]").val(), csrfmiddlewaretoken: $("[name='csrfmiddlewaretoken']").attr('value') … -
how can store ForienKey from get method in django
I am trying to assign the product and category id to vendor, but after creating vendor successfully. When i select category and products for vendor and submit button nothing happened. It just redirect the menu after submit. Even after submit no error shown.When i debug the code and use break points it just only execute the get function and skip the post View.py class Vendor(TemplateView): template_name = 'purchase/vendor.html' def get(self, request, *args, **kwargs): return render(request, self.template_name) def post(self, request): try: data = self.request.POST.get vendor = VendorModel( name=data('name'), email=data('email'), Contact_No=data('Contact_No'), address=data('address') ) vendor.save() request.session['Vendor_id'] = vendor.id return redirect('menu') except Exception as e: return HttpResponse('failed{}'.format(e)) class Vendor_Category(TemplateView): template_name = 'purchase/vendorCategory.html' def get(self, request, *args, **kwargs): categories = CategoryModel.objects.all() categoryId = self.request.GET.get('SelectCategory') products = ProductModel.objects.filter(category_id=categoryId) args = {'categories': categories, 'products': products} return render(request, self.template_name, args) def post(self, request): if 'Vendor_id' in request.session: categoryobj = self.request.GET.get('SelectCategory') productobj = self.request.GET.get('SelectProduct') try: vendor = VendorCategory( vendor_id=request.session['Vendor_id'], category_id=categoryobj, product_id=productobj, ) vendor.save() return redirect('menu') except Exception as e: return HttpResponse('failed{}'.format(e)) Template {% extends 'auth/home.html' %} {% block content %} <form method="get"> {% csrf_token %} <label> <select name="SelectCategory"> <option disabled="disabled" selected> Select Category</option> {% for category in categories %} <option value="{{ category.id }}"> {{ category.name }} </option> {% endfor … -
ajax returns information that are removed from database
I have created a live chart by chart.js and Django. when I remove chart data from the MySQL database, my chart still shows the old data! I don't know how this is possible. I use AJAX to update the chart every 3 seconds. thanks -
Python Django Beginner: can't open manage.py
Trying to get started with Django on pycharm. (venv) C:\Users\Vince\PycharmProjects\assignment>python manage.py runserver But I get this error message whenever i run manage.py: C:\Users\Vince\AppData\Local\Programs\Python\Python37-32\python.exe: can't open file 'manage.py': [Errno 2] No such file or directory I do have a django directory opened with a manage.py file in it. Can anyone assist me on what to do? I have tried other solutions, like: python -vvvvv manage.py runserver python manage.py migrate