Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to display the Form properly?
I just want to show a Form on a HTML Page. When I put it on the Page and look via Web Browser, there seems to show me the memory address instead of rendering the form.. [forms.py] from django import forms MODES=[('top10', 'Top 10 Songs'), ('last10', 'Last 10 Songs'), ('recentX', 'Recent X Songs')] class chooseMode(): first_name = forms.CharField(required=True) selectMode = forms.ChoiceField(label='Choose Mode', widget=forms.RadioSelect,choices=MODES) [views.py] def home(request): modusFormular = chooseMode() return render(request, 'home.html', {'modusForm' : modusFormular}) [home.html] somewhere in body: {{ modusForm }} I expected the form to be shown on the page, but it shows me the following: -
TemplateDoesNotExist at /accountparents/login/
The signup.html is working fine but if i click the login and logout, The error show this: TemplateDoesNotExist at /accountparents/login/ registration/login.html I dont know where I can locate that registration/login.html This is my settings.py INSTALLED_APPS = [ 'accounts', 'Homepage', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'Homepage/templates','accounts/templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] and this is my URLS.py urlpatterns = [ path('home/', Homepage.views.home, name='home'), path('login/', LoginView.as_view(template_name='Homepage/login.html'), name='login'), path('logout/', LoginView.as_view(template_name='Homepage/logout.html'), name='logout'), path('staff/', Homepage.views.staff, name='staff') ] -
Redirect to same page in django
I keep getting an ERR_TOO_MANY_REDIRECTS error each time i try to redirect to same page in django. I tried using return HttpResponseRedirect('') but it shows a blank screen. I have equally tried : from django.http import HttpResponseRedirect **views.py** class Test(DetailView): def get(self, request, *args, **kwargs): if not .....: return HttpResponseRedirect(self.request.path_info) -
Django: Template Form action not redirecting
My Form action is not redirecting to the passed view. I am calling simple_upload view method from login_form.html form action. Instead, upon clicking the login button, it stays on the same page. Below is my code: urls.py: from django.conf.urls import url from django.contrib import admin from django.conf import settings from django.conf.urls.static import static from uploads.core import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^', views.login_form, name='login_form'), url(r'^upload/', views.simple_upload, name='simple_upload'), url(r'^drop_down/$', views.drop_down, name='drop_down'), url(r'^visualize_view/$', views.visualize_view, name='visualize_view'), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.AKASH_ROOT) login_form.html: {% block content %} <button onclick="document.getElementById('id01').style.display='block'" style="width:auto;">Login</button> <div id="id01" class="modal"> <form class="modal-content animate" action="{% url 'simple_upload' %}" method="get"> {% csrf_token %} <div class="imgcontainer"> <span class="close" title="Close Modal">&times;</span> <img src="https://www.w3schools.com/howto/img_avatar2.png" alt="Avatar" class="avatar"> </div> <div class="container"> <label for="uname"><b>Username</b></label> <input type="text" placeholder="Enter Username" name="uname" required> <label for="psw"><b>Password</b></label> <input type="password" placeholder="Enter Password" name="psw" required> <button type="submit">Login</button> <label> <input type="checkbox" checked="checked" name="remember"> Remember me </label> </div> <div class="container" style="background-color:#f1f1f1"> <button type="button" class="cancelbtn">Cancel</button> <span class="psw">Forgot <a href="">password?</a></span> </div> </form> </div> <script> // Get the modal var modal = document.getElementById('id01'); // When the user clicks anywhere outside of the modal, close it window.onclick = function(event) { if (event.target == modal) { modal.style.display = "none"; } } </script> {% endblock %} views.py: from django.http import HttpResponse from django.shortcuts … -
docker compose error when "building wheel for psycopg2
Im pretty new with docker. I ran the command docker-compose up -d using docker for windows and it went fine, but now that I'm doing it in ubuntu, it doesn't work. This is the error Building wheel for psycopg2 (setup.py): started ERROR: Command errored out with exit status 1: command: /usr/local/bin/python -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-7u_i6jh4/psycopg2/setup.py'"'"'; __file__='"'"'/tmp/pip-install-7u_i6jh4/psycopg2/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d /tmp/pip-wheel-bjao_ppd --python-tag cp38 cwd: /tmp/pip-install-7u_i6jh4/psycopg2/ Complete output (72 lines): running bdist_wheel running build running build_py creating build creating build/lib.linux-x86_64-3.8 creating build/lib.linux-x86_64-3.8/psycopg2 copying lib/psycopg1.py -> build/lib.linux-x86_64-3.8/psycopg2 copying lib/pool.py -> build/lib.linux-x86_64-3.8/psycopg2 copying lib/tz.py -> build/lib.linux-x86_64-3.8/psycopg2 copying lib/_ipaddress.py -> build/lib.linux-x86_64-3.8/psycopg2 copying lib/_range.py -> build/lib.linux-x86_64-3.8/psycopg2 copying lib/extras.py -> build/lib.linux-x86_64-3.8/psycopg2 copying lib/sql.py -> build/lib.linux-x86_64-3.8/psycopg2 copying lib/_json.py -> build/lib.linux-x86_64-3.8/psycopg2 copying lib/extensions.py -> build/lib.linux-x86_64-3.8/psycopg2 copying lib/errorcodes.py -> build/lib.linux-x86_64-3.8/psycopg2 copying lib/__init__.py -> build/lib.linux-x86_64-3.8/psycopg2 creating build/lib.linux-x86_64-3.8/psycopg2/tests copying tests/test_green.py -> build/lib.linux-x86_64-3.8/psycopg2/tests copying tests/test_types_extras.py -> build/lib.linux-x86_64-3.8/psycopg2/tests copying tests/test_bugX000.py -> build/lib.linux-x86_64-3.8/psycopg2/tests copying tests/test_module.py -> build/lib.linux-x86_64-3.8/psycopg2/tests copying tests/test_types_basic.py -> build/lib.linux-x86_64-3.8/psycopg2/tests copying tests/test_with.py -> build/lib.linux-x86_64-3.8/psycopg2/tests copying tests/test_errcodes.py -> build/lib.linux-x86_64-3.8/psycopg2/tests copying tests/dbapi20_tpc.py -> build/lib.linux-x86_64-3.8/psycopg2/tests copying tests/test_async.py -> build/lib.linux-x86_64-3.8/psycopg2/tests copying tests/test_quote.py -> build/lib.linux-x86_64-3.8/psycopg2/tests copying tests/test_ipaddress.py -> build/lib.linux-x86_64-3.8/psycopg2/tests copying tests/test_lobject.py -> build/lib.linux-x86_64-3.8/psycopg2/tests copying tests/test_cancel.py -> build/lib.linux-x86_64-3.8/psycopg2/tests copying tests/dbapi20.py -> build/lib.linux-x86_64-3.8/psycopg2/tests copying tests/test_replication.py -> build/lib.linux-x86_64-3.8/psycopg2/tests copying tests/test_extras_dictcursor.py -> build/lib.linux-x86_64-3.8/psycopg2/tests copying … -
Django CBV method firing order
I'm trying to dig deeper into class-based views and I couldn't find any advanced references of how exactly Django CBV's work under the hood. Let's take as an example a ListView. How can I determine methods firing order of this class? I love Django because of it's 'simplicity' but there is a moment in time when I'd like to be 100% sure of code I write. Best regards, Wojtek -
How to work BaseInlineFormSet inside Django form?
I'm so beginner in django so BaseInlineFormSet how to work i don't understand . class BaseAnswerInlineFormSet(forms.BaseInlineFormSet): def clean(self): super().clean() has_one_correct_answer = False for form in self.forms: if not form.cleaned_data.get('DELETE', False): if form.cleaned_data.get('is_correct', False): has_one_correct_answer = True break if not has_one_correct_answer: raise ValidationError('Mark at least one answer as correct.', code='no_correct_answer') -
Algorithm/Query For Determine Weighted Reward
I'm working on a game where a user is given a random reward with each reward's chance of being delivered weighted by a "share" system. To illustrate the issue, let's look at an example: Let's say I was going to give a pure random reward, out of set: [A, B, C]. It would be as simple as getting a random index and returning whatever reward from the array. In my use case, however, the reward set is weight with a "share" system. So we have a situation like below: A - Weight of 2. B - Weight of 3. C - Weight of 5. So the set looks like something like this: [A, A, B, B, B, C, C, C, C, C]. Now, I could just build out that array and get a random result like that, but I'm concerned about performance implications. These rewards are stored in a database (using Django and PSQL as the backend if that factors in), and there may be upwards of 100 potential rewards, each with a weight of 1-100 (or more). So I'm trying to figure out an efficient method to pull a random reward based on such weight. As I'm writing this, … -
Django - Post list not appearing
Django blog posts not appearing I am new to Django and am trying to return a list of published blog posts. The page is appearing and no errors are produced, however no posts are showing. I have checked in the admin page and all posts are published. Model: class BlogPost(models.Model): title = models.CharField(max_length=200) snippet = models.CharField(max_length=400, null=True) Blog_pic = models.ImageField(upload_to='blog_pics',blank=True) hero_pic = models.ImageField(upload_to='blog_pics',blank=True) content = models.TextField() blogcategory = models.CharField(max_length=200, default='uncategorised') create_date = models.DateTimeField(default=timezone.now()) published_date = models.DateTimeField(blank=True, null=True) #def publish(self): # self.published_date = timezone.now() # self.save() def get_absolute_url(self): return reverse("BlogPost_detail",kwargs={'pk':self.pk}) Views: class BlogPostListView(ListView): model = BlogPost def get_queryset(self): return BlogPost.objects.all().order_by('-published_date') class BlogPostDetailView(DetailView): model = BlogPost Template: {% for BlogPost in BlogPost_list %} <div class="col-sm-6"> <a href="{% url 'BlogPost_detail' pk=BlogPost.pk %}"> <div class="card"> <img src="#"> <div class=""> <h4><span class="">{{ BlogPost.category }}</span></h4> <p class="">{{ BlogPost.tile }}</p> <p class="">{{ BlogPost.snippet }}</p> <p style="">{{ BlogPost.published_date }</p> <p style="">x min</p> </div> </div> </a> </div> {% endfor %} -
Setting a sender name when sending an email with smtplib and python
I am creating an endpoint where a user can get sent an email with a code to reset their password with. When sending the email, I am using the built in smtplib that comes bundled with python. When a request is made to the endpoint, I want the sender name to appear instead of the raw email. How can I accomplish this? Here's my code: code = ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(8)) content = 'Subject: {}\n\n{}'.format('Your code to reset your password:', 'Your Code: {}'.format(code)) mail = smtplib.SMTP('smtp.gmail.com', 587) mail.ehlo() mail.starttls() mail.login(os.environ.get('email'), os.environ.get('password')) mail.sendmail(os.environ.get('email'), user.email, content) mail.close() When searching the web for similar questions, the only solution that came across was to add this line of code: content['From'] = "Your name " Adding this line of code didn't send the email at all. Does anybody know how to add the sender name to the email? Thank You. -
Define Django Model Constraints
I want to add a constraint onto a model that involves a reference to another model object. In the code below, I want to have, on the ProjectMember model, the project_member field constrained to be different from the project_creator in the project model. class User(models.Model): fullname = models.CharField(max_length=200) email = models.EmailField(max_length=254) password = models.CharField(max_length=254) class Project(models.Model): name = models.CharField(max_length=200) timestamp = models.DateTimeField("date created", auto_now=True) project_creator = models.ForeignKey(User, on_delete=models.CASCADE) class ProjectMember(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE) project_member = models.ForeignKey( User, on_delete=models.CASCADE, verbose_name="member of the project" ) class Meta: order_with_respect_to = 'user_member' constraints = [ models.CheckConstraint(check= , name='project creator not project member'), ] -
Django - AttributeError: module 'os' has no attribute 'environment'
In the context of learning Django, I need to populate Sqlite with random data using Faker module. Several models have been created under models.py : from django.db import models class Topic(models.Model): top_name = models.CharField(max_length=264,unique=True) def __str__(self): return self.top_name class Webpage(models.Model): topic = models.ForeignKey(Topic,on_delete=models.DO_NOTHING) name = models.CharField(max_length=264,unique=True) url = models.URLField(unique=True) def __str__(self): return self.name class AccessRecord(models.Model): name = models.ForeignKey(Webpage,on_delete=models.DO_NOTHING) date = models.DateField() def __str__(self): return str(self.date) To randomly populate these models, I'm using the following script (populate_first_app.py): import os os.environment.setdefault('DJANGO_SETTINGS_MODULE','first_project.settings') import django django.setup() ##FAKE POP SCRIPT import random from first_app.models import AccessRecord,Webpage,Topic from faker import Faker fakegen = Faker() topics = ['Search','Social','Marketplace','News','Games'] def add_topic(): t = Topic.objects.get_or_create(top_name=random.choice(topics))[0] t.save() return t def populate(N=5): for entry in range(N): top = add_topic() fake_url = fakegen.url() fake_date = fakegen.date() fake_name = fakegen.company() webpg = Webpage.objects.get_or_create(topic=top,url=fake_url,name=fake_name)[0] acc_rec = AccessRecord.objects.get_or_create(name=webpg,date=fake_date)[0] if __name__ == '__main__': print('populating script!') populate(20) print('populating complete') When I'm running populate_first_app.py, I got the following error: AttributeError: module 'os' has no attribute 'environment' Using Visual Studio Code (v1.39.2), I'm stuck. Visual code is highlighting error on following lines: t = Topic.objects.get_or_create(top_name=random.choice(topics))[0] Class 'Topic' has no 'objects' memberpylint(no-member) I installed pylint using the following command: pip3 install pylint-django But still stuck. -
Django static tag adding queryparams to generated static files when using DigitalOcean spaces
So, my webpage generates file that includes the access tokens when using the static tag in django to link to my static files, preferably i would like this link to go to my server, aka: http://xxx.xxx.xxx/static/css/main.css Right now its generating: https://******.digitaloceanspaces.com/fpl/static/css/main.css?AWSAccessKeyId=&Signature=%3D&Expires=1571503012 in my html My settings for static files in production: AWS_ACCESS_KEY_ID = '***' AWS_SECRET_ACCESS_KEY = '****' AWS_STORAGE_BUCKET_NAME= '***' AWS_S3_ENDPOINT_URL = 'https://*****.digitaloceanspaces.com' AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } AWS_LOCATION = 'static' STATIC_URL = 'http://***.***.***' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' How can i change the settings to make it link to my servers nginx instead? -
Test cases for Django Rest Framework; struggling to get a correct response
I am writing tests for my Django Rest Framework API but I am struggling to get my code to return a 200 OK. At the moment, my test case continually returns a 404 Not Found. I'm in the early stages of writing tests, and have a lot to learn. I'm currently following https://www.django-rest-framework.org/api-guide/testing/ I'm trying to test an endpoint at the following URL # Not shown here, is that all URLs here will be prepended with /api/v1 path('case/<int:pk>/', EntireCaseView.as_view(), name='case'), I have an object in my database with an ID (primary key) of 1. I can successful query the API by going to http://localhost:8000/api/v1/case/1/ I receive a valid JSON response (Trampe is a rabbit) { "id": 1, "total_points": 5000, "passing_points": 3700, "budget": 5000, "description": "Saving Trampe from Trauma", "name": "Trampe", "signalment": "8yr, intact male, mixed breed.", "problem": "Respiratory difficulty", "image": { "id": 1, "file": "http://localhost:8000/media/images/trampe.jpg", "description": "A lovely picture of Trampe" }, My API requires authentication, and as such I am providing authentication in my test case. class CaseTests(APITestCase): def test_status_code(self): """ ensure that case/1 returns 200 OK """ # Create a test user test_user = User(username='jim', password='monkey123', email='jim@jim.com') test_user.save() factory = APIRequestFactory() user = User.objects.get(username='jim') view = EntireCaseView.as_view() url … -
ListView and DetailView in Django
I have 4 categories on my site. How can I write one class PageViews(ListView) for four same pages with different posts. And same question, how to write class DeteilViews(DetailView) for each posts? My models below. class Category(models.Model): category = models.CharField(max_length=50) slug = models.CharField(max_length=60, unique=True) class Topic(models.Model): topic = models.CharField(max_length=50) slug = models.CharField(max_length=60, unique=True) category = models.ManyToManyField(Category) class Page(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) topic = models.ForeignKey(Topic, on_delete=models.CASCADE) datetime = models.DateTimeField() title = models.CharField(max_length=60) slug = models.CharField(max_length=250, unique=True) short_text = models.CharField(max_length=255) text = models.TextField() image = models.ImageField(upload_to='media/news_img') img_source = models.CharField(max_length=255) page_source = models.CharField(max_length=60) parsing_date = models.DateTimeField(auto_now=True) objects = models.Manager() def get_absolute_url(self): return reverse('news:detail', args=[self.category.slug, self.topic.slug, self.slug]) class Comment(models.Model): page = models.ForeignKey(Page, on_delete=models.CASCADE) comment = models.TextField() author = models.CharField(max_length=55) datetime = models.DateTimeField() -
Sql check a value in column is greater than number of rows
i am building a web app where customer can book a service from a business(vendor). but first vendor need to add what services he provide, where he able to deliver those services, and from which time (start time) to which time(end time) how many users is available for that service so i am confusing that suppose a customer book a service for some particular time and when another customer book a service from that vendor we need to calculate is the number of users available in this time period is greater than count of already booked services(which are not completed yet) in that particular time i have these three table users = (for both customer & vendors) id | name | address | role_id vendor_available_time = (only for vendor) id | date_start_time | date_end_time | no_of_users | service_id bookings = (for both) id | booking_status | booking_datetime | customer_id | vendor_id | service_id please help me with a query where i can get all vendors whose no_of_users is greater than count(bookings) where booking_datetime >= date_start_time and booking_datetime < date_end_time and booking_status is not in ['completed', 'rejected', 'cancelled'] Any suggestion will be really appreciated can i get those result from one … -
Django Rest Framework - how to change query params recognition?
I use [https://www.npmjs.com/package/vue-bootstrap4-table#8-filtering][1] with django-rest-framework. The problem is that this component uses totally different query params for sorting, filtering, etc. vue-bootstrap4-table http://127.0.0.1:8000/api/products/?queryParams=%7B%22sort%22:[],%22filters%22:[%7B%22type%22:%22simple%22,%22name%22:%22code%22,%22text%22:%22xxx%22%7D],%22global_search%22:%22%22,%22per_page%22:10,%22page%22:1%7D&page=1 "filters":[{"type":"simple","name":"code","text":"xxx"}], whereas Django-rest-framework needs this format: ../?code__icontains=... I want to figure out how to make DRF accept this format instead of the built-in? I use just ViewSet. class ProductViewSet(viewsets.ModelViewSet): serializer_class = ProductSerializer filter_class = ProductFilter filter_backends = [filters.OrderingFilter] ordering_fields = '__all__' Is it possible? -
Django admin log in page gets stuck after I click the Log in button
This problem can be reproduced on my computer even with the simplest polls application. Execute python .\manage.py runserver to run the server. Open http://127.0.0.1:8000/admin in Chrome. If already logged in, then log out. Click "Log in again" and redirect to http://127.0.0.1:8000/admin/login/?next=/admin/. Type the correct username and password. Then, nothing happens except that the tab of Chrome keeps loading. The log of the python command is as follows. [19/Oct/2019 22:02:09] "GET /admin/logout/ HTTP/1.1" 200 1195 [19/Oct/2019 22:02:10] "GET /admin/ HTTP/1.1" 302 0 [19/Oct/2019 22:02:10] "GET /admin/login/?next=/admin/ HTTP/1.1" 200 1807 [19/Oct/2019 22:02:25] "POST /admin/login/?next=/admin/ HTTP/1.1" 302 0 I tried another browser, Edge, for several times. This problem never happens in Edge. However, it will happen in Chrome almost every time I follow the steps listed above. I wonder if this is due to Chrome or am I missing something? -
How to force users to complete their profile in Django
I have designed a learning management system that customers can attend courses, buy books and ... . In this system when users want to enrollment in course forced to fill their profile info. But some of them don't want to enrollment in course and then I can't have their info. I want to force users to complete their profile and enter the required information into their profile. For example I want: System show them warning and force them to complete their profile three days after registration. How can I do that? Notice: In other hand I want to block access for users who have not yet completed their profile to use the panel, until they complete theirs profile. -
Too many redirect to same page in django
I am trying to redirect to a the same page if certain conditions are not met in my view in django but i keep getting ERR_TOO_MANY_REDIRECTS error. I am using HttpResponseRedirect. from django.http import HttpResponseRedirect return HttpResponseRedirect(self.request.path_info) -
Raise Form error below the input field in case any invalid data is entered in Django
I am using pre_save to raise error if while entering the data any condition is not met. But when I am using raise ValidationError(). Its showing me error in the next page like this. But what I actually want is the error just below my field that the data is invalid. For example the one that you get for a unique field eg username in the django admin. The error should show in this page itself showing invalid data. How can I do this. This is what I have tried. @receiver(pre_save, sender=Works_in) def check_dept_has_manager(sender, instance, **kwargs): print(instance.emp_name, instance.dept_name) if str(instance.emp_name) == "BB": raise ValidationError("Manager already assigned to this department") -
getting error while creating database python manage.py initdb , how to solve this issue?
error while creating database in python , python manage.py initdb is not working C:\Users\Mantu Kumbhakar\Downloads\pyfile>python manage.py initdb Traceback (most recent call last): File "manage.py", line 4, in from app import app, db, models File "C:\Users\Mantu Kumbhakar\Downloads\pyfile\app__init__.py", line 6, in app.config.from_object('app.config') File "C:\Users\Mantu Kumbhakar\AppData\Local\Programs\Python\Python37-32\lib\site-packages\flask\config.py", line 162, in from_object obj = import_string(obj) File "C:\Users\Mantu Kumbhakar\AppData\Local\Programs\Python\Python37-32\lib\site-packages\werkzeug\utils.py", line 546, in import_string import(import_name) File "C:\Users\Mantu Kumbhakar\Downloads\pyfile\app\config.py", line 1, in config_dev.py NameError: name 'config_dev' is not defined NameError: name 'config_dev' is not defined -
'You're accessing the development server over HTTPS, but it only supports HTTP.' I don't know the cause of the error
I divided and edited the setting.py file in Django. And after starting, it disappeared on the screen. 'ERR_SSL_PROTOCOL_ERROR' is displayed on the screen. Command. python manage.py runserver 0.0.0.0:8000 The error is as follows. 2019-10-19 21:44:10,829 [INFO] /Users/t.a/Desktop/apasn/apasn_rest/venv/lib/python3.7/site-packages/django/core/servers/basehttp.py:154 code 400, message Bad request version ('\x80ì.UÂHÂg\x95JÁ\xad\x81µXBz\'\x00"êê\x13\x01\x13\x02\x13\x03À+À/À,À0̨̩À\x13À\x14\x00\x9c\x00\x9d\x00/\x005\x00') 2019-10-19 21:44:10,830 [ERROR] /Users/t.a/Desktop/apasn/apasn_rest/venv/lib/python3.7/site-packages/django/core/servers/basehttp.py:137 You're accessing the development server over HTTPS, but it only supports HTTP. I tried with 'SECURE_SSL_REDIRECT' set to false, but the result did not change. #base.py import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) PROJECT_NAME = os.path.basename(BASE_DIR) SECRET_KEY = '***' DEBUG = True ALLOWED_HOSTS = ['*'] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] SECURE_SSL_REDIRECT = False ROOT_URLCONF = 'apasn_rest.config.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'apasn_rest.config.wsgi.application' DATABASES = {} AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] LANGUAGE_CODE = 'ja' TIME_ZONE = 'Asia/Tokyo' USE_I18N = True USE_L10N = True USE_TZ = True STATIC_URL = '/static/' #local.py from .base import * DEBUG = True SECRET_KEY = '***' ALLOWED_HOSTS = ['*'] DATABASES = … -
DetailView redirect not working in django
I keep getting a reverse error when i try to redirect from a DetailView and CreateView. I keep getting object has no attribute pk. I have equally tried using : args=[str(self.id)]) but i still get the error. class check (DetailView) def get(self, request, *args, **kwargs): if...: return reverse('no_edit', kwargs={"pk": self.pk}) -
vue-bootstrap4-table - how to modify filtering query params?
I use https://www.npmjs.com/package/vue-bootstrap4-table#8-filtering with django-rest-framework. The problem is that this component uses totally different query params for sorting, filtering, etc. vue-bootstrap4-table http://127.0.0.1:8000/api/products/?queryParams=%7B%22sort%22:[],%22filters%22:[%7B%22type%22:%22simple%22,%22name%22:%22code%22,%22text%22:%22xxx%22%7D],%22global_search%22:%22%22,%22per_page%22:10,%22page%22:1%7D&page=1 "filters":[{"type":"simple","name":"code","text":"xxx"}], but Django-rest-framework needs this format: ../?code__icontains=... Do you know how to make vue-bootrstrap4-table to generate this format? My app: new Vue({ el: '#app', data: { product_list_url: "{% url "api:product-list" %}", rows: [], total_rows:0, queryParams: { sort: [], filters: "", global_search: "", per_page: 10, page: 1, }, columns: [{ label: "Kód", name: "code", filter: { type: "simple", placeholder: "code" }, sort: true, }, { label: "Názov", name: "name", filter: { type: "simple", placeholder: "Enter name" }, sort: true, }, ], config: { checkbox_rows: true, rows_selectable: true, {#card_title: "Vue Bootsrap 4 advanced table",#} server_mode: true, } }, mounted() { this.fetchData(); }, methods: { onChangeQuery(queryParams) { this.queryParams = queryParams; this.fetchData(); }, fetchData() { let self = this; axios.get(self.product_list_url, { params: { "queryParams": this.queryParams, "page": this.queryParams.page } }) .then(function (response) { self.rows = response.data.results; self.total_rows = response.data.count; }) .catch(function (error) { console.log(error); }); } }, })