Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Updated data is not saving to db
I want to change Branch field of Blank model in a given range. For example, changing Blank model's Branch field with numbers from 1 to 3. Here are my codes: views.py: @login_required(login_url='sign-in') def blanks(request): if request.method == 'POST' and 'create-blank' in request.POST: form = CreateBlankForm(request.POST) if form.is_valid(): form.save() # here happens updating process elif request.method == 'POST' and 'share-blank' in request.POST: form = CreateBlankForm(request.POST) if form.is_valid(): form.update() else: form = CreateBlankForm() blank_list = Blank.objects.all().order_by('-created') context = { 'form': form, } return render(request, 'blank.html', context) forms.py: class CreateBlankForm(ModelForm): def save(self, commit=False): blank = super(CreateBlankForm, self).save(commit=False) number_of_objects = range(blank.number_from, blank.number_to+1) for i in number_of_objects: Blank.objects.create( blank_series = blank.blank_series, blank_number = i, branch=blank.branch, number_from = blank.number_from, number_to = blank.number_to ) def update(self, commit=False): shared_blank = super(CreateBlankForm, self).update(commit=False) number_of_objects = range(shared_blank.number_from, shared_blank.number_to+1) for i in number_of_objects: Blank.objects.update( branch=shared_blank.branch ) models.py: class Blank(models.Model): blank_series = models.CharField(_('Blankın seriyası'), max_length=3) blank_number = models.IntegerField(_('Blankın nömrəsi'), blank=True, null=True) branch = models.ForeignKey(Branch, on_delete=models.CASCADE, blank=True, null=True) number_from = models.IntegerField() number_to = models.IntegerField() def __str__(self): return self.blank_series -
how to split screen into two halves of 20/80 or 30/70 in HTML?
I have the following structure in HTML: <div class="row"> <div class="col"> <div class="leftside"> ...leftside content here... </div> </div> <div class="col> <div class="rightside> ...rightside content here... </div> </div> </div> However, this results into my page being split into 2 halves. I would like to have my leftside be 30% of the page, and the rightside 70%. How can I do this easily? I'm working in the Django with Bootstrap. -
How to Install mysqlclient for Django in windows 10?
i am new in Django.i want to use Mysql database for my project.i am installing mysqlclient for that, but its showing below error. i am using --pip install mysql-python command for installing mysqlclient Collecting mysql-python Using cached MySQL-python-1.2.5.zip (108 kB) Using legacy setup.py install for mysql-python, since package 'wheel' is not installed. Installing collected packages: mysql-python Running setup.py install for mysql-python ... error ERROR: Command errored out with exit status 1: command: 'f:\xampp\htdocs\django\scripts\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\Users\DELL\AppData\Local\Temp\pip-install-ti26jpbi\mysql-python\setup.py'"'"'; file='"'"'C:\Users\DELL\AppData\Local\Temp\pip-install-ti26jpbi\mysql-python\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' install --record 'C:\Users\DELL\AppData\Local\Temp\pip-record-h90u4076\install-record.txt' --single-version-externally-managed --compile --install-headers 'f:\xampp\htdocs\django\include\site\python3.8\mysql-python' cwd: C:\Users\DELL\AppData\Local\Temp\pip-install-ti26jpbi\mysql-python Complete output (24 lines): running install running build running build_py creating build creating build\lib.win32-3.8 copying mysql_exceptions.py -> build\lib.win32-3.8 creating build\lib.win32-3.8\MySQLdb copying MySQLdb_init.py -> build\lib.win32-3.8\MySQLdb copying MySQLdb\converters.py -> build\lib.win32-3.8\MySQLdb copying MySQLdb\connections.py -> build\lib.win32-3.8\MySQLdb copying MySQLdb\cursors.py -> build\lib.win32-3.8\MySQLdb copying MySQLdb\release.py -> build\lib.win32-3.8\MySQLdb copying MySQLdb\times.py -> build\lib.win32-3.8\MySQLdb creating build\lib.win32-3.8\MySQLdb\constants copying MySQLdb\constants_init_.py -> build\lib.win32-3.8\MySQLdb\constants copying MySQLdb\constants\CR.py -> build\lib.win32-3.8\MySQLdb\constants copying MySQLdb\constants\FIELD_TYPE.py -> build\lib.win32-3.8\MySQLdb\constants copying MySQLdb\constants\ER.py -> build\lib.win32-3.8\MySQLdb\constants copying MySQLdb\constants\FLAG.py -> build\lib.win32-3.8\MySQLdb\constants copying MySQLdb\constants\REFRESH.py -> build\lib.win32-3.8\MySQLdb\constants copying MySQLdb\constants\CLIENT.py -> build\lib.win32-3.8\MySQLdb\constants running build_ext building '_mysql' extension error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools": https://visualstudio.microsoft.com/downloads/ ---------------------------------------- ERROR: Command errored out with exit status … -
How to setup menu data in Context_processor in Django?
I have category and subcategory store in my database, and subcategory is related to category, I have multiple pages on my website, but I am able to display category in the menu on some pages, but I want to display on all pages, so I found the solution using context_processor, but I am unable to render HTML file there, it only takes data in the dictionary file, please check my code and let me know where I am mistaking. here is my models.py file... class Category(models.Model): cat_name=models.CharField(max_length=225) cat_slug=models.SlugField(max_length=225, unique=True) def __str__(self): return self.cat_name class SubCategory(models.Model): subcat_name=models.CharField(max_length=225) subcat_slug=models.SlugField(max_length=225, unique=True) category = models.ForeignKey('Category', related_name='subcategoryies', on_delete=models.CASCADE, blank=True, null=True) def __str__(self): return self.subcat_name here is my context_processor.py file... from django.shortcuts import render from dashboard.models import Category, SubCategory def context_categories(request, cat_slug): category = Category.objects.all().order_by('-created_at') return render(request, "base.html", {'category':category}) included this file in settings.py file under TEMPLATES section 'mainpage.context_processors.context_categories', here is my base.html file... {% for cat in category %} <li> <a href="javascript:void()">{{cat.cat_name}}</a> <ul> {% for subcat in cat.subcategoryies.all %} <li><a href="/subcategory/{{subcat.subcat_slug}}">{{subcat.subcat_name}}</a></li> {% endfor %} </ul> </li> {% endfor %} -
Issue in accessing child model objects from parent model in Django
I am creating a blogging website. I want to display all the articles posted by any particular writer/user. I have created the 'Post' model as the child of the 'Writer' model. I wanna display all the articles of the user in his profile. But I can't access the Post('s title) from the parent class, i.e., Writer class. (I searched a few answers from the internet. Didn't help.) I am getting the error: 'Writer' object has no attribute 'post_set' models.py: class Writer(models.Model): user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE) email = models.EmailField(unique=True) profile_pic = models.ImageField(default='profile.png', upload_to = 'Bloggers') def __str__(self): return self.user.username class Post(models.Model): title = models.CharField(max_length=25) cover = models.ImageField(upload_to='Blog Image') content = models.TextField() post_writer = models.ForeignKey(Writer,null=True, related_name="tags", related_query_name="tag", on_delete=models.CASCADE) def __str__(self): return self.title views.py: def profile(request, pk): writer = Writer.objects.get(id=pk) print(writer.post_set.all()) Error received: 'Writer' object has no attribute 'post_set' -
How can I deal with 'str' object has no attribute '_meta' error on my django project
I have django project that have a form to upload data which save at my database. But there are some problems which I cannot deal with. I try to find documentations to deal with problem, but I can't find which can help me. views.py from django.shortcuts import render,redirect from django.contrib.auth.models import User,auth from exam.functions.functions import handle_uploaded_file from django.http import HttpResponse from exam.forms import Examinationform from exam.models import Examination import json # Create your views here. def upload1(request): if request.method == 'POST': main=[] exam = Examinationform(request.POST, request.FILES) if exam.is_valid(): for _file in request.FILES.getlist('fileexam'): _file = request.FILES['fileexam'] #devide list of files. filename = _file.name main.append("filename") handle_uploaded_file(_file) Examination.namefileexam = json.dumps(main) Examination.category = request.POST.get('category') try: Examination.notation = request.POST.get('notation') except AttributeError: Examination.notation = '' try: Examination.name = request.POST.get('name') except AttributeError: Examination.name = '' Examination.save('self') exam = Examinationform() main.clear() return HttpResponse("File uploaded successfuly") else: exam = Examinationform() return render(request,'uploadfileexam1.html',{'form':exam}) Models.py from django.db import models from django import forms class Examination(models.Model): namefileexam = models.TextField(null=True) notation = models.CharField(max_length=78, blank=True, null=True) category = models.CharField(max_length=25) name = models.CharField(max_length=25, blank=True, null=True)` enter code here forms.py from django import forms from exam.models import Examination BOSS_CHOICES=( ('sheets', 'sheets'), ('contestexams', 'contestexams'), ('schoolexams', 'schoolexams'), ('others', 'others'), ) class Examinationform(forms.Form): fileexam = forms.FileField(label = 'เลือกไฟล์', required … -
How to use VSCODE Live Server with templated html?
I'm a web developer who primarily uses Django and is used to using templatized code with Jinja and what not. The Live Server vscode extension is SUPER valuable, but seems to not be able to work with ANY Templating from what I've researched (actually, I couldn't even find another question, but I'm sure it's out there.) I want to use Live Server without having to copy and paste the stuff in the head tag, or the same navbar / footer over and over and over again. Do I have to choose between having templated HTML and using Live Server? If not, how can I do this with Live Server? For example: base.html <!-- DOCTYPE html --> <html> <head> </head> <body> <main> <!-- Where I want the other page's code to be --> </main> </body> </html> Then with my other html pages, I want to not link the other pages: other_page.html <!-- Between the main tag in the other page --> <div>Added code but on a different page</div> <!-- End of the code --> I'm more than open to using some front-end framework like view or react if this will work with liveserver. Thanks in advance! :) -
How can I use concatenation within a request.POST.get() function? (django/python)
I was trying to iterate request.POST.get() to get some inputs from my view's corresponding html file using concatenation. However, no matter whether the input is filled, it always says that the input returns the fallback. (As in the default response that the programmer gives.) Does anyone know how to solve this? I'm trying to make it so it adds each choice to the set of choices for each question. create.html {% block title %}Create a Poll{% endblock title %} {% block header %}Create:{% endblock header %} {% load custom_tags %} {% block content %} {% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %} <form action="{% url 'polls:create' %}" method="post"> {% csrf_token %} {% for field in questionfields %} {% if field == 'question_text' %} <label for="{{ field }}">{{ field|capfirst|replace }}:</label> <input type="text" name="{{ field }}" id="{{ field }}"> <br> {% endif %} {% endfor %} <br> {% for choice in choicenumber|rangeof %} <br> <label for="choice{{ forloop.counter }}">Choice {{ forloop.counter }}</label> <input type="text" name="choice{{ forloop.counter }}" id="choice{{ forloop.counter }}"> <br> {% endfor %} <br> <br> <input type="submit" value="Create" name="submit"> </form> {% endblock content %} views.py def create(request): choicenumber = 3 context = { 'questionfields': Question.__dict__, 'choicenumber': choicenumber, } submitbutton = request.POST.get('submit', False) … -
Get authentication type from request in a view of Django
In my project, I use 2 authentication backends: LDAPBackend and ModelBackend(Django's default). User can log in by using LDAP account or Django's account. How can I get authentication type from request in a view? Settings.py: AUTHENTICATION_BACKENDS = [ 'django_auth_ldap.backend.LDAPBackend', 'django.contrib.auth.backends.ModelBackend', ] Views.py: def my_function(request): #I want to get authentication type here return render(request, "index.html") -
Azure search - Create Index - JSON decode error
I'm using the django framework. I'm trying to create an index in the Azure portal using the REST api tutorial they have provided. I'm getting the following error when I send my post request. JSONDecodeError at /createIndex This is my method. @csrf_exempt def createIndex(request): endpoint = 'https://service.search.windows.net/' api_version = '2020-06-30' url = endpoint + "indexes" + api_version index_schema = { "name": "hotels-quickstar11t", "fields": [ {"name": "HotelId", "type": "Edm.String", "key": "true", "filterable": "true"}, {"name": "HotelName", "type": "Edm.String", "searchable": "true", "filterable": "false", "sortable": "true", "facetable": "false"}, {"name": "Description", "type": "Edm.String", "searchable": "true", "filterable": "false", "sortable": "false", "facetable": "false", "analyzer": "en.lucene"}, {"name": "Description_fr", "type": "Edm.String", "searchable": "true", "filterable": "false", "sortable": "false", "facetable": "false", "analyzer": "fr.lucene"}, {"name": "Category", "type": "Edm.String", "searchable": "true", "filterable": "true", "sortable": "true", "facetable": "true"}, {"name": "Tags", "type": "Collection(Edm.String)", "searchable": "true", "filterable": "true", "sortable": "false", "facetable": "true"}, {"name": "ParkingIncluded", "type": "Edm.Boolean", "filterable": "true", "sortable": "true", "facetable": "true"}, {"name": "LastRenovationDate", "type": "Edm.DateTimeOffset", "filterable": "true", "sortable": "true", "facetable": "true"}, {"name": "Rating", "type": "Edm.Double", "filterable": "true", "sortable": "true", "facetable": "true"}, {"name": "Address", "type": "Edm.ComplexType", "fields": [ {"name": "StreetAddress", "type": "Edm.String", "filterable": "false", "sortable": "false", "facetable": "false", "searchable": "true"}, {"name": "City", "type": "Edm.String", "searchable": "true", "filterable": "true", "sortable": "true", "facetable": "true"}, {"name": "StateProvince", "type": "Edm.String", … -
join 2 tables with ForeignKey in django
i have an image table which is made of all of my images and i have a product table i want to use more than one image in my product table how is this possible ? i dont want to write ForeignKey in image table because i want to use my images somewhere else models.py from django.db import models class Image (models.Model): path = models.CharField(max_length=200) class Product (models.Model): name = models.CharField(max_length=100) price = models.FloatField(default=0) description = models.TextField(max_length=10000) image = models.ForeignKey(Image,on_delete=models.DO_NOTHING) -
django-user-accounts signup doesn't work propely
I've started new project with django-user-accounts. This is my html form for sign up: <form class="" action="{% url 'account_signup' %}" method="post"> {% csrf_token %} <div class="form-group"> <input class="form-control" type="text" id="loginInput" name="username " value="" placeholder="Имя пользователя"> </div> <div class="form-group"> <input class="form-control" type="email" id="emailInput" name="email" value="" placeholder="Адрес эл. почты"> <small id="emailHelp" class="form-text text-muted">Мы не распростаняем ваши личные данные третьим лицам.</small> </div> <div class="form-group"> <input class="form-control" type="password" id="pwdInput" name="password" value="" placeholder="Пароль"> </div> <div class="form-group"> <input class="form-control" type="password" id="pwdRepeatInput" name="password_confirm" value="" placeholder="Повторите пароль"> </div> <input type="hidden" name="next" value="{{ redirect_field_value }}" /> <div class="reg__btn"> <button type="submit" class="btn btn-block btn-outline-warning">Регистрация</button> </div> </form> and this is my urls.py: urlpatterns = [ path('admin/', admin.site.urls), path('account/overview', include("account_extend.urls")), path('account/', include("account.urls")), path('', get_index) ] When i go to /account/signup/ i get my html template with form. After that i fill the inputs of it and hit submit button, but nothing happens. I only get my page reloaded, without user creation. At the same time, /account/login/ and /account/logout/ pages work properly. What i'm doing wrong? -
how to calculate between to different models field without having connection
hi i need to calculate between to different models field without having any connection imagine i have two models (tables) i want to get profit and income in a storage , Model1 for selling purpose and the other for costs of the company , i need to know profit and incomes , field_1 all selling prices and field_2 all costs of the company class Model1(models.Model): field_1 = models.IntegerField() class Model2(models.Model): field_2 = models.IntegerField() can i calculate something like this model1__field1 - model2__field2 ? i much appreciate your helps -
Change Overriden Django Views Return URL
I want to change the return url of a django-allauth page. I know I could override the entire function in views.py and just change the return url at the bottom, but doesn't seem ideal as it could cause issues if associated code in the django-allauth package gets changed by the packages authors. Is there a better way to do this? Thank you. -
access to fields which required is false in save method - django
i have a serializer like that : phone = serializers.CharField() name = serializers.CharField(required=False) product = serializers.IntegerField() birth_date=serializers.CharField(required=False) father_name = serializers.CharField(required=False) mobile = serializers.CharField() address = serializers.CharField(required=False) post_paid = serializers.BooleanField() national_code = serializers.CharField(required=False) current_line = serializers.CharField() install = serializers.IntegerField() is_extension = serializers.IntegerField() def save(self,**extra_fields): product = Product.objects.get(id=self.validated_data['product']) user = Account.objects.get(mobile=self.validated_data['current_line']) create = Payment( user_id=user.id, cost=product.total_price, status='در حال پرداخت' ) create.save() order = ProductOrder ( company = product.company_id, product = product, user = user, payment = create, name = self.validated_data['name'], mobile = self.validated_data['mobile'], phone = self.validated_data['phone'], birth_date=self.validated_data['birth_date'], father_name = self.validated_data['father_name'], address = self.validated_data['address'], national_code = self.validated_data['national_code'], post_paid = self.validated_data['post_paid'], install_id = int(self.validated_data['install']), status_id = 3 ) order.save() return order but i don't have access to fields which required is false by self.validated_data['FIELD_NAME'] how can i use fields which not required in my serializers in save() method. thanks all. -
Django not serving text content (Second attempt)
Summary: I’m writing a Django web app whose purpose is to showcase a writing sample (a ‘post mortem’) which is basically like a blog post for all intents and purposes. Django is not serving the content and I am not sure why. The problem I figure is with either my views.py or template (copied below). I don’t think the issue is with my models or urls.py but I included them anyways. Details: This is my second attempt at getting my Django project to serve this template properly. In my prior first attempt, I encountered a similar issue: Django not serving text content (First attempt) There in that question, another SO member answered by identifying three mistakes I was making. The problem there was that I was missing a for loop inside my template, I was missing an all() class method inside my views.py and the context dictionary key value pair in views.py was not pluralized. Those issues have been resolved however my new issue involves Django serving a blank template when I am expecting the Lorem Ipsum content to show. Django should be pulling all the class objects from my models.py and then be sending them to the alls/landings.html. I … -
what to write in views.py to pass the foerign key with particular Material key to detail.html to show all materials related to Subject Model
I want to display material list related to Subject on detail page but when I click on particular material to display then it passes only that particular material key to detail.html to show on same page, but other materials get dissappear. Please help! My Models.py class Subject(models.Model): topic = models.CharField(max_length = 100) image = models.ImageField(upload_to='images/') user = models.CharField(max_length = 100) def __str__(self): return self.topic class Material(models.Model): material_name = models.CharField(max_length=50) topic = models.ForeignKey(to=Subject, on_delete=models.CASCADE, null=True, blank=True) material_video = models.FileField(upload_to='images/') material_desc = models.TextField() material_code = models.TextField() created_at = models.DateTimeField(auto_now_add = True) updated_at = models.DateTimeField(auto_now = True) def __str__(self): return self.material_name My urls.py path('',index,name='index'), path('tutorial/',tutorial,name='tutorial'), path('detail/<int:pk>/',detail,name='detail'), path('detail/<slug:st>/<sub_id>',sub_detail,name='subdetail'), Tutorial.html <div style="align:center; padding-left:50px;"> <a href="{% url 'tutorial:detail' i.pk %}"> <button class="button button--tamaya button--border-thick" data-text="Learn Java"><span>Learn Java</span></button> </a> My detail.html page <div class="col-md-3 px-0" id="course-content-box"> <div class="py-2 px-3 bg-lgrey"> <h5> Course Content <i class="mx-2 fas fa-plus" id="toggleCourse"></i></h5> </div> <div id="content-box"> <ul class="content-holder"> {% for i in j %} <a href="/detail/{{i.topic}}/{{i.id}}"> <li class="content-holder-item"> {{i.id}}. &nbsp; {{i.material_name}} <div class="mx-3"> <i class="far fa-play-circle"></i> Free YouTube Video </div> </li> </a> {% endfor %} Views.py def tutorial(request): j = Subject.objects.filter() context = {'j':j} return render(request,'tutorial.html',context) def detail(request,pk): j = Material.objects.filter(topic = pk) context = {'j':j} return render(request,'detail.html',context) def sub_detail(request,st,sub_id): j = … -
Django DB: Model attributes with field depending on ManyToMany Field
I need advice in what I can do with a Model when the attributes depend on how many ManytoMany Fields I have. the following problem: class myModel(model.Model): id = model.AutoField(primary_key=True) date = ... fkey = models.ForeignKey(myOtherModel, ...) m2m = models.ManytoMany(LineModel) #notes = models.TextField(max_length=100, blank=True, null=True) #days = models.PositiveIntegerField(default=1, blank=True, null=True) I need the last 2 attributes notes and days multiple times. Exactly how many m2m I have. If I have 2 I need 2 notes and 2 days attributes that I can associate with the m2m_1 and m2m_2. for example m2m_1 notes: "To be taken with caution" and days: 2 and m2m_2 notes: "-" and days: 7 I have solved this so far with another Model that comes with these attributes. But I ran into some difficulties in creating the view and initial forms and so forth. So am I on the right path or is there a different more elegant solution? Thanks -
ProgrammingError : column "id" is of type integer but expression is of type uuid
i am getting ProgrammingError : column "id" is of type integer but expression is of type uuid. it would be great if anybody figure out where i'm doing thing wrong. thank you so much in advance. import uuid class BookProduct(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) product = models.ForeignKey("Product", on_delete=models.CASCADE) bookdate = models.DateTimeField(default=datetime.now()) created_on = models.DateTimeField(default=datetime.now()) status = models.BooleanField(default=True) -
Using django-smart-selects to achieve chained selection but in reverse foreign relationship
I am trying to use django-smart-select and I totally understand the example: from smart_selects.db_fields import ChainedForeignKey class Continent(models.Model): name = models.CharField(max_length=255) class Country(models.Model): continent = models.ForeignKey(Continent) name = models.CharField(max_length=255) class Location(models.Model): continent = models.ForeignKey(Continent) country = ChainedForeignKey( Country, chained_field="continent", chained_model_field="continent", show_all=False, auto_choose=True, sort=True) area = ForeignKey(Area) city = models.CharField(max_length=50) street = models.CharField(max_length=100) However the relationship of my models is not set this way, the following is what approximate my data: class Continent(models.Model): name = models.CharField(max_length=255) countries = models.ManyToManyField('Country') class Country(models.Model): name = models.CharField(max_length=255) How do I achieve that same chained select if the relationship is reversed? -
django.db.utils.ProgrammingError: relation "django_site" does not exist
Django 3.0.8 settings.py INSTALLED_APPS = [ 'django.contrib.sites', # DJANGO_APP. Necessary for the built in sitemap framework. ... ] SITE_ID = 1 # For the sites framework. urls.py from feeds.feeds import RssFeed urlpatterns += [ path('rss/', RssFeed(), name="rss"), ... feeds.py from general.utils import get_site_address class RssFeed(Feed): title = "Pcask.ru: все о компьютерах, гаджетах и программировании." link = get_site_address() utils.py from django.contrib.sites.models import Site def get_site(): site = Site.objects.first().name return site def get_protocol(): if HTTPS: protocol = "https://" else: protocol = "http://" return protocol def get_site_address(): return "".format(get_protocol(), get_site()) Problem First of all I have to migrate as I use sites framework (https://docs.djangoproject.com/en/3.0/ref/contrib/sites/#enabling-the-sites-framework). $ python manage.py migrate Traceback (most recent call last): File "/home/michael/PycharmProjects/pcask/venv/lib/python3.8/site-packages/django/db/backends/utils.py", line 86, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedTable: relation "django_site" does not exist LINE 1: ..."django_site"."domain", "django_site"."name" FROM "django_si... ^ The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/home/michael/PycharmProjects/pcask/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/home/michael/PycharmProjects/pcask/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/michael/PycharmProjects/pcask/venv/lib/python3.8/site-packages/django/core/management/base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "/home/michael/PycharmProjects/pcask/venv/lib/python3.8/site-packages/django/core/management/base.py", line 366, in execute self.check() File "/home/michael/PycharmProjects/pcask/venv/lib/python3.8/site-packages/django/core/management/base.py", line 392, in check all_issues = self._run_checks( … -
Is it possible to pause the django background tasks?
For example I have a django background task like this. notify_user(user.id, repeat=3600, repeat_until=2020-12-12 00:00:00) Which will repeat every 1 hour until some datetime. My question is : Is it possible to pause this task? and if the user resume the task then the task should be resumed again(if not possible restart the task again would be fine also). Is there someone who is experienced with django background tasks ? -
JavaScript submitting form only if "window.close()" not present
I have a form with id "myform". <form method="POST" id="myform">{% csrf_token %} <label for="target_bla">Bla bla</label> <select id="target_bla" name="target_bla"> <option>1</option> <option>2</option> <option>3</option> </select> <div class="buttons"> {% if condition %} <input name="btnSubmit" value="Bla bla" onclick="subAndClose()" /> {% else %} <input name="btnSubmit" type="submit" value="Other bla" /> {% endif %} </div> </form> Then I have this JavaScript part that should submit the form: function subAndClose() { document.forms["myform"].submit(); window.close() } Now the strange thing: When line window.close() is omitted, the form submits just fine. When the line is there, the window actually closes, but the form is not submitted at all, without any errors or issues. What I have tried already: I checked all names and IDs, no reserved keywords used I tried submitting with default HTML submit button, it is working properly -
How to pass a url title in a form action in django
sorry for newbie question, I'm learning django and ran into a problem: I'm trying to pass a page title to url that will searched for in views for .md file with name of that title. HTML: <form action="{% url 'edit' %}"> {% csrf_token %} <div class="form-group mt-4"> <button class="btn btn-outline-info" type="submit">Edit page</button> </div> urls.py: path("wiki/edit/", views.edit_page, name="edit") views.py: def edit_page(request, page): if request.method == "GET": return render(request,"encyclopedia/edit_page.html", { "pagename": page, "html": markdown2.markdown(util.get_entry(page)) }) ~ What is the best practice for this. Thanks very much! -
How to know which reference was chosen on the page?
I have made a Django webpage, and on the left I have a table containing table names such as "users, sports, activities" ..., and on the right I have a table that shows the records of a table. I want the user to be able to click on a table name on the left, and the table should load up on the right. I added anchors to the table names table, but how can I make it so that when an anchor is clicked, the page is refreshed with the correct table loaded up? Right now the anchors are just refreshing the page. Is there a way to know which anchor was clicked on, from views.py?