Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
url tag not finding existing 'google_login' view function of django-allauth
I have a simple HTML content point towards the Google Login, as below. # foo.html <a class="p-2 text-dark" href="{% url 'google_login' %}">Google Login</a> This simple demo project was using django==3.2.x and django-allauth==0.43.x. Recently, I have upgraded packages to the latest versions, viz, django==4.1.x and django-allauth==0.52.x. After the upgrade, I was getting the following error - Reverse for 'google_login' not found. 'google_login' is not a valid view function or pattern name. I have confirmed whether the google_login is present or not by executing the reverse(...) function from the shell. In [1]: from django.urls import reverse In [2]: reverse("google_login") Out[2]: '/accounts/google/login/' Error traceback Environment: Request Method: GET Request URL: http://127.0.0.1:1234/ Django Version: 4.1.5 Python Version: 3.9.11 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'whitenoise.runserver_nostatic', 'django.contrib.staticfiles', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google', 'crispy_forms', 'debug_toolbar', 'drf_yasg', 'django_extensions', 'rest_framework', 'drf_spectacular', 'accounts', 'pages', 'polls', 'extra', 'attendance'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'debug_toolbar.middleware.DebugToolbarMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Template error: In template /home/jpg/work-dir/projects/-personal/generic-django-example/templates/_base.html, error at line 32 Reverse for 'google_login' not found. 'google_login' is not a valid view function or pattern name. 22 : <link rel="stylesheet" href="{% static 'css/base.css' %}"> 23 : {% endblock %} 24 : </head> 25 : 26 : <body> 27 : <main role="main"> 28 … -
django-test-migrations failing when using multiple postgres schemas in django
I am using local postgres 12 db. I have 2 models: class CustomUser2(models.Model): name = models.CharField(max_length=100) class CustomUser3(models.Model): name = models.CharField(max_length=100) class Meta: db_table = 'schema1\".\"custom_user_3' I run following test: from django_test_migrations.contrib.unittest_case import MigratorTestCase class TestDirectMigration(MigratorTestCase): """This class is used to test direct migrations.""" migrate_from = ('core', '0002_customuser2') migrate_to = ('core', '0003_customuser3') def prepare(self): """Prepare some data before the migration.""" SomeItem = self.old_state.apps.get_model('core', 'CustomUser2') def test_migration_main0003(self): """Run the test itself.""" SomeItem = self.new_state.apps.get_model('core', 'CustomUser2') I get following error: django.db.utils.ProgrammingError: relation "custom_user_3" already exists Is there a way to test migrations when using different schemas in django + postgres ? -
How to save list of objects in DRF
I am new to django. I have following model: class Standup(models.Model): team = models.TextField() standup_time = models.DateTimeField(auto_now_add=True) employee = models.TextField() update_time = models.DateTimeField(auto_now_add=True) status = models.CharField(max_length=50) work_done_yesterday = models.TextField() work_to_do = models.TextField() blockers = models.TextField() Serializer class looks like this: class StandupSerializer(serializers.ModelSerializer): class Meta: model = Standup fields = '__all__' Viewset is like this: class StandupDetail(viewsets.ModelViewSet): queryset = Standup.objects.all() serializer_class = StandupSerializer My task is to hit a single API which will save the data of all employees, instead of saving the data of employees separately. In the current implementation, each employee will have to hit the API separately to save the data in database. Each employee will select team first, as one employee can be a part of multiple team. We will save a list of objects. Any leads on how to do it? -
Create form for intermediate model showing all objects from one model
I’m working on a project to track Apps that are assigned to Employees. These assignments are stored in an intermediate model called EmployeeApps that contain an extra field called status (model.ChoiceField). I need to build a form that displays a list of all Apps and a checkbox to request that app. This would save back to the EmployeeApps model any requested apps. I have the various models created and working fine but cannot figure out how to create the form itself. An identical question was asked a few years ago but the form logic wasn’t shared: Django with multiple ManyToManyField form How can I get the list of all apps and display them alongside a checkbox that gets saved/updated back to EmployeeApps? models.py class Employees(models.Model): name = models.CharField() class Apps(models.Model): name = models.CharField() class EmployeeApps(models.Model): employee = models.ForeignKey(“Employees”, on_delete=models.CASCADE) apps = models.ForeignKey(“Apps”, on_delete=models.CASCADE) status = models.IntegerField(choices=STATUS_CHOICES) -
Handling relation choices in Django REST Framework Serializers
Imagine having these two models: class PaymentMethod(models.Model): title = models.CharField(max_length=32) description = models.CharField(max_length=255) class Order(models.Model): amount = models.IntegerField() payment_method = models.ForeignKey(PaymentMethod) What I'm trying to achieve is having one serializer with a single field for payment_method, that on GET methods shows the string representation of PaymentMethod but on POST, PUT or DELETE uses the pk. In this way, front-end can easily show the current object by using the response from the end-point without having to process the metadata from an OPTIONS request which contains the available choices. The other option would be going around my code to add an additional StringRelatedField field on all my serializers, something similar to: payment_method_label = serializers.StringRelatedField(...) What I have already tried is customizing serializers.PrimaryKeyRelatedField: class CustomPrimaryKeyRelatedField(serializers.PrimaryKeyRelatedField): def use_pk_only_optimization(self): return False def to_representation(self, value): return str(value) However, this also changes the representation of metadata in an OPTIONS request, and instead of getting something like: "choices": [ { "value": 1, "display_name": "Cash" }, { "value": 2, "display_name": "Another Payment Method Name" } ] It produces this output which is not desired: "choices": [ { "value": "Cash", "display_name": "Cash" }, { "value": "Another Payment Method Name", "display_name": "Another Payment Method Name" } ] Is there anyway to … -
intermittent bad gateway django mysql error
My error is intermittent, and occurs on all pages, so for now the only code I will paste is the settings for my database. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'hms', 'USER': 'hms', 'PASSWORD': '27Kovelov', 'HOST': '127.0.0.1', 'PORT': '3306', 'OPTIONS': {'init_command': "SET sql_mode='STRICT_TRANS_TABLES'"}, } } I'm getting the following error message from django: (2003, "Can't connect to MySQL server on '127.0.0.1:3306' (111)") or I get a Bad Gateway error message in my browser. I have a separate application that writes scientific data to a mysql database that resides on my web hosting plan (digitalocean droplet). Is it possible the django error message is because my app the writes the data and my django app are accessing the database at the same time? -
Attributes of a Model don't appear on Django
I made a ListView-supported page with names, images, and a button for add product using Django, but for some reasons I don't know the other attributes like name and image fail to be appeared when I write some codes about the button connected with functions in views.py. This is some of my code <div class="card h-100"> <!-- Product image--> <img class="card-img-top" src={{ product.head_image.url }} alt="..." width="450px" height="300px"/> <!-- Product details--> <div class="card-body p-4"> <div class="text-center"> <!-- Product name--> <a class="stretched-link text-decoration-none" style="color:black" href="{{ product.get_absolute_url }}"><h5 class="fw-bolder">{{ product.title }}</h5></a> <!-- Product price--> <h4>₩{{ product.price }}</h4> </div> </div> <!-- Product actions--> <div class="text-center card-footer p-4 pt-0 border-top-0 bg-transparent"> <form method="post"> {{add_to_cart}} {% csrf_token %} <input type="submit" class="btn btn-outline-dark mt-auto update-cart" value="add to cart"> </form> </div> </div> </div> </div> As you see, the rest of the code except the button part are totally normal. what's wrong with this? -
Django - Redirect to the same page on post and reload
I'm trying to do a self redirect in a view sending some data in the session, i achieved that as follows: class SomeView(TemplateView): template_name = 'path/to/template.html' def get(self, request, *args, **kwargs): # get data from session context["data"] = request.session.get("data", {}) print(context) del request.session["data"] # In a try-except block return render(request, context=context) def post(self, request, *args, **kwargs): # do stuff request.session["data"] = data return redirect("app:someview") It does the redirect, in the console i can see context variable with the data, the problem is that the browser does not reload the view, so the data does not displays. I want to force a reload of the view or anything that displays the data in the template. It's important to note that use a different view is not an option. I tried to not delete the request.session attributes but then, to display the data i need to reload the page (F5), and i need to display the data without the user reload it manually. -
I got this when I tried to change the user to Abstractuser?
┌──(venv)─(neo㉿neo)-[~/…/Software Development/DjangoReact/-Blog/backend] └─$ python3 manage.py migrate Operations to perform: Apply all migrations: admin, auth, blogapp, contenttypes, forumapp, sessions, token_blacklist, useraccount Running migrations: Applying useraccount.0001_initial...Traceback (most recent call last): File "/home/neo/Documents/Software Development/DjangoReact/-Blog/backend/manage.py", line 22, in main() File "/home/neo/Documents/Software Development/DjangoReact/-Blog/backend/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/neo/Documents/Software Development/DjangoReact/-Blog/backend/venv/lib/python3.10/site-packages/django/core/management/init.py", line 446, in execute_from_command_line utility.execute() File "/home/neo/Documents/Software Development/DjangoReact/-Blog/backend/venv/lib/python3.10/site-packages/django/core/management/init.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/neo/Documents/Software Development/DjangoReact/-Blog/backend/venv/lib/python3.10/site-packages/django/core/management/base.py", line 402, in run_from_argv self.execute(*args, **cmd_options) File "/home/neo/Documents/Software Development/DjangoReact/-Blog/backend/venv/lib/python3.10/site-packages/django/core/management/base.py", line 448, in execute output = self.handle(*args, **options) File "/home/neo/Documents/Software Development/DjangoReact/-Blog/backend/venv/lib/python3.10/site-packages/django/core/management/base.py", line 96, in wrapped res = handle_func(*args, **kwargs) File "/home/neo/Documents/Software Development/DjangoReact/-Blog/backend/venv/lib/python3.10/site-packages/django/core/management/commands/migrate.py", line 349, in handle post_migrate_state = executor.migrate( File "/home/neo/Documents/Software Development/DjangoReact/-Blog/backend/venv/lib/python3.10/site-packages/django/db/migrations/executor.py", line 135, in migrate state = self._migrate_all_forwards( File "/home/neo/Documents/Software Development/DjangoReact/-Blog/backend/venv/lib/python3.10/site-packages/django/db/migrations/executor.py", line 167, in _migrate_all_forwards state = self.apply_migration( File "/home/neo/Documents/Software Development/DjangoReact/-Blog/backend/venv/lib/python3.10/site-packages/django/db/migrations/executor.py", line 252, in apply_migration state = migration.apply(state, schema_editor) File "/home/neo/Documents/Software Development/DjangoReact/-Blog/backend/venv/lib/python3.10/site-packages/django/db/migrations/migration.py", line 130, in apply operation.database_forwards( File "/home/neo/Documents/Software Development/DjangoReact/-Blog/backend/venv/lib/python3.10/site-packages/django/db/migrations/operations/models.py", line 96, in database_forwards schema_editor.create_model(model) File "/home/neo/Documents/Software Development/DjangoReact/-Blog/backend/venv/lib/python3.10/site-packages/django/db/backends/base/schema.py", line 442, in create_model sql, params = self.table_sql(model) File "/home/neo/Documents/Software Development/DjangoReact/-Blog/backend/venv/lib/python3.10/site-packages/django/db/backends/base/schema.py", line 216, in table_sql definition, extra_params = self.column_sql(model, field) File "/home/neo/Documents/Software Development/DjangoReact/-Blog/backend/venv/lib/python3.10/site-packages/django/db/backends/base/schema.py", line 346, in column_sql field_db_params = field.db_parameters(connection=self.connection) File "/home/neo/Documents/Software Development/DjangoReact/-Blog/backend/venv/lib/python3.10/site-packages/django/db/models/fields/related.py", line 1183, in db_parameters target_db_parameters = self.target_field.db_parameters(connection) File "/home/neo/Documents/Software Development/DjangoReact/-Blog/backend/venv/lib/python3.10/site-packages/django/db/models/fields/related.py", line 1060, in target_field return self.foreign_related_fields[0] File … -
redirect @login-required for specific pages
In Django, I have in my files: settings.py LOGIN_URL = 'login' LOGOUT_REDIRECT_URL = 'frontpage' LOGIN_REDIRECT_URL = 'myaccount' views.py @login_required() def checkout(request): cart = Cart(request) if not len(cart): return redirect('cart_view') ...more code... my question is simple... How do I set the @login_required, so that instead of the myaccount page being the redirect URL, I can send it back to checkout page? In other words, where can I override LOGIN_REDIRECT_URL when needed? Thank you, -
why is my python for loop in django return just a single value
the django views.py def quiz_automate(request): val=automate_data() # print(val['data']) get_quiz=Quiz.objects.get(subject='english',exam_type='jamb') for data in val['data']: print(data['question']) d_question=Question(text=data['question'],quiz=get_quiz) d_question.save() return HttpResponse('saved')` the scraped.py function def automate_data(): url = 'https://questions.aloc.com.ng/api/v2/m?subject=chemistry' headers = {'Accept': 'application/json','Content-Type': 'application/json'} r = requests.get(url, headers=headers) return r.json() i tried scraping data from a site and it returned multipled values but whenever i use in my django views to store in my postgres database it just store a value instead of multiple values -
Django parler: error when for same translation
I've just added django-parlel to my project and I'm wondering is it my bad or it's really impossible to have same translation more then once. Case I'm trying to add translation for Polish language for word "Sport", in polish it would be "Sport", just same as in English (which I have by default in app). When trying to add this getting error both when adding from admin panel and when loading fixture. I know that i might leave it blank and it won't really be that bad however I need to have translation for each single word. I'm assuming there is a constraint in parlel ;( Thanks in advance. Error in Admin -
Does a Django site need a Postgres database when hosting on Heroku? Can I remove the Postgres add-on?
I have a website that I built using Django and deployed on Heroku. The tutorial I followed had me set up a Heroku Postgres database attached as an add-on. After Heroku's recent pricing changes the Postgres database has gone from free to $5 / month. Maybe static isn't the correct word, but the site doesn't have user accounts, collect user information, or otherwise have any need for a database. I believe the only information that's stored in the database is login info for the Django admin site. I was able to export a .pgdmp file from Heroku of the data stored in the database but couldn't make heads or tails of the contents. Here's the settings.py file code for the database section: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } import dj_database_url db_from_env = dj_database_url.config(conn_max_age=500) DATABASES['default'].update(db_from_env) My question is can I delete this add-on from the Heroku CLI or dashboard without breaking the site in production? Would I need to change anything in my settings.py file or elsewhere in my Django code first? I assume I would still be able to access the Django admin page on the development server, is that assumption correct? Sorry … -
How to sort distinct values with respect to manytoone class in Django?
I have two models class MessageThread(models.Model): title = models.CharField(max_length=120, blank=True, null=True) created_user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, related_name='created_user') belonging_user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) last_message_date = models.DateTimeField(blank=True, null=True) and class Message(models.Model): thread = models.ForeignKey(MessageThread, on_delete=models.SET_NULL, null=True) user = models.ForeignKey(User, null=True, blank=True, on_delete=models.SET_NULL) comments = models.TextField(blank=True, null=True, max_length=500) create_date = models.DateTimeField(blank=True, null=True) Here, I want to get MessageThreads that are sorted by their last Messages' create_date. I tried to get sorted Messages by '-create_date' and then get distinct thread ids from that query but it doesnt work. I am using PostgreSQL. -
AttributeError: 'HttpResponse' object has no attribute 'render'
anyone know why this error is happening? i've been running the same line for my other tests and only this one is returning an error both lines in test_coverageReturnSuccess + test_coverageReturnCorrectCoverage returning this error: response.render() AttributeError: 'HttpResponse' object has no attribute 'render' This is my APi test case class CoverageTest(APITestCase): protein = None domain = None protein_domain = None good_url = '' bad_url = '' def setUp(self): self.protein = ProteinFactory.create(pk=1, protein_id='A0A014PQC0', length=338) self.domain = PfamFactory.create() self.protein_domain = ProteinDomainLinkFactory.create(protein=self.protein, pfam_id=self.domain, start=157, stop=314) # Set urls self.good_url = reverse('coverage', kwargs={'protein_id': 'A0A014PQC0'}) def tearDown(self): # Reset test tables Protein.objects.all().delete() Pfam.objects.all().delete() ProteinDomainLink.objects.all().delete() # Reset primary keys ProteinFactory.reset_sequence(0) PfamFactory.reset_sequence(0) ProteinDomainLinkFactory.reset_sequence(0) def test_coverageReturnSuccess(self): """ Ensure we get an 200 OK status code when making a valid GET request. """ response = self.client.get(self.good_url, format='json') response.render() self.assertEqual(response.status_code, 200) def test_coverageReturnCorrectCoverage(self): """ Ensure we get the right coverage of the requested protein """ response = self.client.get(self.good_url, format='json') response.render() data = json.loads(response.content) self.assertEqual(data, 0.46449704142011833) -
React MUI Checkbox set checked on false value
I am having this problem with React MUI - Checkbox component. I have the site where I have the checkbox with handler targeting to the REST API endpoint that sets the boolean flag for the user in the database on POST request and returns the boolean value for the logged user. Backend code: # Models class Client(models.Model): all_submitted = models.BooleanField(default=False, null=False) # Views @api_view(["POST", "GET"]) @permission_classes([IsAuthenticated]) def all_submitted(request): current_client = request.user.client if request.method == "GET": return Response(status=status.HTTP_200_OK, data={ "submitted": current_client.all_submitted }) elif request.method == "POST": checked = request.data['checked'] if type(checked) == bool: with transaction.atomic(): current_client.all_submitted = checked current_client.save() return Response(status=status.HTTP_200_OK, data={ "submitted": current_client.all_submitted }) and the client code: const [checked, setChecked] = useState(false); const handleChange = (event) => { api.post("/client/files", {checked: event.target.checked}).then((response) => { if (response.status === 200) { setChecked(response.data.allEvidenceSubmitted); } }) }; useEffect(() => { api.get("/client/files").then((response) => { if (response.status === 200) { setChecked(response.data.allEvidenceSubmitted); } }); }, ["checked"]) <FormGroup> <FormControlLabel labelPlacement="bottom" control={<Checkbox checked={checked} onChange={handleChange} inputProps={{'aria-label': 'controlled'}} />} label={t("checkbox", "I confirm that the documents have been completely uploaded.", {ns: "evidence"})}/> </FormGroup> Now the problem is that when the value is supposed to be false, then on page refresh, even if the false value is returned, the checkbox gets checked. Does … -
ModuleNotFoundError in Django in Vscode
from django.contrib import admin from django.urls import path from home import views urlpatterns = [ path("", views.index, name='home'), ] This is code in urls.py file under home app. And now its giving following error: (env) abhishek@Abhisheks-MacBook-Pro hello % /Users/abhishek/Documents/django_work/env/bin/python /Users/abhishek/Do cuments/django_work/Hello/home/urls.py Traceback (most recent call last): File "/Users/abhishek/Documents/django_work/Hello/home/urls.py", line 3, in <module> from home import views ModuleNotFoundError: No module named 'home' I tried this & still not working INSTALLED_APPS = [ 'home', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', Can anyone expain this? And also how to fix this. -
CrispyError at /login/ |as_crispy_field got passed an invalid or inexistent field
I'm working on a login form for my Django blog. I'm having a problem with crispy forms. This is login.html <div class="entry-main-content mt-50"> <!--<h1 class="mt-30">Get in touch</h1>--> <hr class="wp-block-separator is-style-wide"> <form method="post" class="form-contact comment_form" action="#" id="commentForm"> {% csrf_token %} <div class="row"> <div class="col-sm-6"> <div class="form-group"> {{ form.username | as_crispy_field }} </div> </div> <div class="col-sm-6"> <div class="form-group"> {{ form.password | as_crispy_field }} </div> </div> </div> <div class="form-group"> <button type="submit" class="button button-contactForm">Login</button> </div> </form> </div> This is views.py def login_request(request): if request.method == "POST": form = AuthenticationForm(request, data=request.POST) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(username=username, password=password) if user is not None: login(request, user) messages.info(request, f"You are now logged in as {username}.") return redirect("home") else: messages.error(request,"Invalid username or password.") else: messages.error(request,"Invalid username or password.") form = AuthenticationForm() return render(request=request, template_name="login.html", context={"login_form":form}) This is forms.py class NewUserForm(UserCreationForm): email = forms.EmailField(required=True) class Meta: model = User fields = ("username", "email", "password1", "password2") def save(self, commit=True): user = super(NewUserForm, self).save(commit=False) user.email = self.cleaned_data['email'] if commit: user.save() return user I tried to follow instructions like in this blog because I need to keep html template. Any idea how to solve this? Thanks in advance! -
Coupon code not working for items in cart
I am trying to implement a coupon code feature in my Django e-commerce website. I have added the apply_coupon method to the Order model and a coupon field to the Order model, and I have also added a coupon_code parameter to the cart view function. However, when I test the coupon code by entering it in the cart page, nothing happens and the discount is not applied. I've included the relevant code snippets below. Can someone please help me understand why the coupon code is not working and how to fix it? views.py from django.shortcuts import render from django.http import JsonResponse from django.contrib import messages import json import datetime from .models import * from .utils import cookieCart, cartData, guestOrder def store(request): data = cartData(request) cartItems = data['cartItems'] order = data['order'] items = data['items'] products = Product.objects.all() context = {'products': products, 'cartItems': cartItems} return render(request, 'store/store.html', context) def cart(request): data = cartData(request) cartItems = data['cartItems'] order = data['order'] items = data['items'] coupon = Coupon(code='PERMANENT', discount=0.2, active=True, valid_until=None) coupon.save() # Kupon kodu işlevini ekleyin coupon_code = request.GET.get('coupon_code', None) if coupon_code: # Eğer bir sipariş nesnesi oluşturulmuşsa kupon uygulayın if hasattr(order, 'apply_coupon'): coupon_applied = order.apply_coupon(coupon_code) if not coupon_applied: messages.warning(request, 'Geçersiz veya etkin olmayan … -
Constructor can't set property value in Python class
I encounter strange behaviour in constructor of a python class: class MetricQuery(): query = None def __init__(self, query = None): self.query = query @classmethod def sum(self, field, response_field = None): self.es_query = basic_aggregation("sum", field, response_field) return self @classmethod def get(self): output = self.es_query if self.query != None: output["query"] = self.query["query"] return output Here's the test method for sum: def test_sum(): query = {"query": {"match": {"active": True}}} assert MetricQuery(query).sum("visits").get() == {"query": {"match": {"active": True}},"aggs": {"sum_visits_field": {"sum": {"field": "visits"}}}} Test fails, saying that right contains 1 more item, "query". It seems constructor can't set query value properly. What am I missing? -
Need support, Initially Django Search page is displaying all data, while i want to have only search text boxes and display data after user input
Views.py def advance_filter(request): user_list = SarnarLogs.objects.all() user_filter = UserFilter(request.GET) return render(request, 'advance_filter.html', {'filter': user_filter}) Template: Advance_filter.html <form method="get"> <div class="well"> <h4 style="margin-top: 0">Filter</h4> <div class="row"> <div class="form-group col-sm-4 col-md-3"> {{ filter.form.source.label_tag }} {% render_field filter.form.source class="searchfield" %} </div> <div class="form-group col-sm-4 col-md-3"> {{ filter.form.destination.label_tag }} {% render_field filter.form.destination class="searchfield" %} </div> <div class="form-group col-sm-4 col-md-3"> {{ filter.form.port.label_tag }} {% render_field filter.form.port class="searchfield" %} </div> <div class="form-group col-sm-4 col-md-3"> {{ filter.form.request_no.label_tag }} {% render_field filter.form.request_no class="searchfield" %} </div> </div> <button type="submit" class="btn btn-primary" placeholder="Search" aria-label="Search" name="q" value='{{ request.GET.q }}'> <span class="glyphicon glyphicon-search"></span> Search </button> </div> </form><br> <div class="col-12"> <div class="card my-4"> <div class="card-header p-0 position-relative mt-n4 mx-3 z-index-2"> <div class="bg-gradient-primary shadow-primary border-radius-lg pt-4 pb-3"> <h6 class="text-white text-capitalize ps-3">HUB Requests</h6> </div> </div> <div class="card-body px-0 pb-2"> <div class="table-responsive p-0"> <table class="table align-items-center mb-0"> <thead> <tr> <th class="text-uppercase text-secondary text-xxs font-weight-bolder opacity-7">ID</th> <th class="text-uppercase text-secondary text-xxs font-weight-bolder opacity-7 ps-2">SOURCE</th> <th class="text-center text-uppercase text-secondary text-xxs font-weight-bolder opacity-7">DESTINATION</th> <th class="text-center text-uppercase text-secondary text-xxs font-weight-bolder opacity-7">PORT</th> <th class="text-center text-uppercase text-secondary text-xxs font-weight-bolder opacity-7">REQUEST TYPE</th> <th class="text-center text-uppercase text-secondary text-xxs font-weight-bolder opacity-7">REQUEST_NO</th> <th class="text-center text-uppercase text-secondary text-xxs font-weight-bolder opacity-7">REQUESTER</th> <th class="text-center text-uppercase text-secondary text-xxs font-weight-bolder opacity-7">START DATE</th> <th class="text-center text-uppercase text-secondary text-xxs font-weight-bolder opacity-7">EXPIRY DATE</th> <th class="text-center … -
How to 'check' a value in a radio button by default in Django?
I wrote a model form. I used widgets to make radio buttons and I want a particular radio button to be checked by default while rendering the form in my html file. Model: class Room(models.Model): class Meta: number = models.PositiveSmallIntegerField() CATEGORIES = ( ('Regular', 'Regular'), ('Executive', 'Executive'), ('Deluxe', 'Deluxe'), ) category = models.CharField(max_length=9, choices=CATEGORIES, default='Regular') CAPACITY = ( (1, '1'), (2, '2'), (3, '3'), (4, '4'), ) capacity = models.PositiveSmallIntegerField( choices=CAPACITY, default=2 ) advance = models.PositiveSmallIntegerField(default=10) manager = models.CharField(max_length=30) The following is my model form based on the above model. Form: class AddRoomForm(forms.ModelForm): ROOM_CATEGORIES = ( ('Regular', 'Regular'), ('Executive', 'Executive'), ('Deluxe', 'Deluxe'), ) category = forms.CharField( max_length=9, widget=forms.RadioSelect(choices=ROOM_CATEGORIES), ) ROOM_CAPACITY = ( (1, '1'), (2, '2'), (3, '3'), (4, '4'), ) capacity = forms.CharField( max_length=9, widget=forms.RadioSelect(choices=ROOM_CAPACITY), ) class Meta: model = Room fields = ['number', 'category', 'capacity', 'advance'] Here is the views: def add_room(request): if request. Method == 'POST': form = AddRoomForm(request.POST) if form.is_valid(): room = Room(number=request.POST['number'], category=request.POST['category'], capacity=request.POST['capacity'], advance=request.POST['advance'], manager=request.user.username) room.save() # Implemented Post/Redirect/Get. return redirect('../rooms/') else: context = { 'form': form, 'username': request.user.username } return render(request, 'add_room.html', context) context = { 'form': AddRoomForm(), 'username': request.user.username } return render(request, 'add_room.html', context) I rendered the form like this in my … -
Deployment fails without prompting any errors on console on digitalocean app-engine django app
We have 2 apps that are running with similar settings, now we are trying to deploy another app but this time it's failing without telling any error in app engine. Python django app starts and then suddenly app engine stops deployment. How to find reason behind that? -
Django logging does not work inside views and viewsets
Can someone please help me understand why django does not print logging messages that I put inside views methods? When I call logger.debug() from outside views it works correctly my views.py import logging logger = logging.getLogger(__name__) logger.debug('THIS LOGGING MESSSAGE SHOWS UP IN LOGS') class RequestGetResultViewSet(viewsets.GenericViewSet, mixins.RetrieveModelMixin): permission_classes = (IsAuthenticated,) serializer_class = serializers.RequestGetResultSerializer queryset = Request.objects.all() def get_queryset(self):] logger.debug('THIS LOGGING MESSSAGE DOES NOT SHOW UP') return self.queryset.filter(user=self.request.user.id) @action(methods=['get'], detail=True, renderer_classes=(PassthroughRenderer,)) def download(self, *args, **kwargs): logger.debug('THIS LOGGING MESSSAGE DOES NOT SHOW UP') # working code here return response my settings.py: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console': { 'class': 'logging.StreamHandler', }, }, 'root': { 'handlers': ['console'], 'level': 'DEBUG' , }, 'loggers': { 'django': { 'handlers': ['console'], }, } -
Hello everyone, help me write a test to Check if a post has been removed from the old group
You need to check that the post has disappeared from the old group page. You get our old band by its slack. old_group_response = self.authorized_client.get( reverse('group_list', args=(self.group.slug,)) ) And you compare, что old_group_response.context['page_obj'].paginator.count equals zero. This means that there are no posts in our old group. You can check another new one, that there is 1 post there. Please help me write correctly) from django import forms from django.test import Client, TestCase from django.urls import reverse from ..models import Group, Post, User NEW_POST = reverse('posts:post_create') class PostFormTests(TestCase): @classmethod def setUpClass(cls): super().setUpClass() cls.author_auth = User.objects.create_user(username='test auth') cls.not_author = User.objects.create_user(username='Not Author') cls.group = Group.objects.create( title='Test group_title', slug='test_slug', description='Test description') def setUp(self): self.authorized_client = Client() self.authorized_client.force_login(PostFormTests.author_auth) self.authorized_client_not_author = Client() self.authorized_client_not_author.force_login( PostFormTests.not_author) def test_post_old_group_response(self): """ Check if a post has been removed from the old group.""" post = Post.objects.create( group=PostFormTests.group, author=PostFormTests.author_auth, text='test post') group_2 = Group.objects.create( title='Test group_title2', slug='test_slug2', description='Test description2') posts_count = Post.objects.count() form_data = { 'text': 'text_post', 'group': group_2.id} old_group_response = self.authorized_client.get( reverse('posts:group_list', args=(self.group.slug)), data=form_data, follow=True) self.assertEqual( old_group_response, reverse( 'posts:post_detail', kwargs={'post_id': post.pk})) self.assertEqual(Post.objects.count(), posts_count) self.assertEqual(old_group_response.context[ 'page_obj'].paginator.count == 0) I know what rubbish is written here (I'm just learning), this is what I was able to sketch))