Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
pictures are not shown in django production site
I have a django website in production. Everything works fine except pictures are not shown. The pictures are not stored in the database but located in a different location on the server. When I inspect the site than the url is shown correctly This is in my template {% if img_url != "" %} <img scr="{{ img_url|safe }}" width="500" height="300"> <br> {% else %} {% endif %} This is in my view how I generate the url. The pictures are located in each program and link_picture is just the name and ending of that picture e.g. picture1.png url = os.path.join(settings.MEDIA_ROOT,project.get_program_display(),project.link_picture) if os.path.exists(url): img_url = url else: img_url = "" This is in my settings STATIC_URL = '/static/' MEDIA_URL = '/media/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_ROOT = os.path.join('/mnt/data/import', 'media') This is in my apache2 config file Alias /static /home/user1/FDB/static <Directory /home/user1/FDB/static> Require all granted </Directory> Alias /media /mnt/data/import/media <Directory /mnt/data/import/media> Require all granted </Directory> <Directory /home/user1/FDB/fdb> <Files wsgi.py> Require all granted </Files> </Directory> WSGIScriptAlias / /home/user1/FDB/fdb/wsgi.py WSGIDaemonProcess django_app python-path=/home/user1/FDB python-home=/home/user1/FDB/venv WSGIProcessGroup django_app Any help is appreciated. -
How to filter rows in django and html?
How to filter column's in django using templates (html,bootstrap)? I have table called Some contains 50 column's. example: a,b,c,d,e,f,g how to filter columns if i select a,b column show two columns records after adding c column need to show c records ? -
Forbidden (CSRF cookie not set.) only thrown on a single view when I have disabled CSRF protections on POST?
I am developing a django backend using the djangorestframework and simplejwt authentication. I am using it for a react native mobile app so I am disabling CSRF protections for my views. For some reason, even though every other view works without issue, my token blacklist view throws an error Forbidden (CSRF cookie not set.) For example the following view works fine: @method_decorator(csrf_exempt, name='dispatch') class BusinessProfileView(APIView): permission_classes = (permissions.IsAuthenticated, HasAccountOwnershipBP) def post(self, request, format='json'): serializer = BusinessProfileSerializer(data=request.data, context={'request': request}) if serializer.is_valid(): ... def put(self, request, format='json'): ... But this token blacklist view throws the above error @method_decorator(csrf_exempt, name='dispatch') class BlackListToken(APIView): permission_classes = (permissions.IsAuthenticated,) def post(self, request): refresh = request.data['refresh'] try: #get this refresh token from outstanding and invalidate it token = RefreshToken(refresh) token.blacklist() print('ran') return Response(status=status.HTTP_200_OK) except Exception as e: print(e) return Response(status=status.HTTP_400_BAD_REQUEST) I've tried setting csrf exempt on the post method directly but that doesn't seem to help anything. I initially tried to use simplejwt's packaged token blacklist but that also threw the same error so I was trying to gain some more control over the view creation with this custom version. Just in case here is my middleware list as I'm aware the order can affect things MIDDLEWARE = … -
How to pass {% url 'category' %} in my category_list.html?
I have a detail view for categories and if i pass in the URL directly it works just fine. But if i want to pass it as a link in my template it gets an error. Here is my models: class Category(models.Model): name = models.CharField(max_length=255) def __str__(self): return (self.name) def get_absolute_url(self): return reverse("home") Here is my views: class CategoryClassView(TemplateView): model = Category template_name = "categories.html" def get_context_data(self, **kwargs): cats = kwargs.get("cats") category_posts = Category.objects.filter(name=cats.replace('-', ' ')) context = {'cats':cats.replace('-', ' ').title(), 'category_posts':category_posts} return context Here is my URLS: path('category/<str:cats>/', CategoryClassView.as_view(), name='category') Here is my template: {% extends "base.html" %} {% block content %} {% for category in category_list %} <div class="card"> <div class="card-header"> <span class="font-weight-bold"><a href="">{{ category.name}}</a></span> &middot; </div> </div> {% endfor %} {% endblock content %} Could you write a more detailed explanation for your answer? Why is just passing {% url 'categoryl' %} is not working? A link to a list of useful materials would be also acceptable for better understanding. -
Forbidden: /unauthentication error for token
(views.py) class userApi(APIView): def get(self,request): auth = get_authorization_header(request).split() if not auth: raise AuthenticationFailed('User Authentication Failed!!!') elif auth and len(auth)==2: token =auth[1].decode('utf-8') id=decode_access_token(token) #payload = decode_access_token(token) users=user.objects.filter(id = id).first() serializer=userSerializer(users) return Response(serializer.data) raise AuthenticationFailed('unauthenticated') (authentication.py) import jwt,datetime from rest_framework.exceptions import AuthenticationFailed def create_access_token(id): return jwt.encode({ 'user_id':id, 'exp':datetime.datetime.utcnow()+datetime.timedelta(minutes=10), 'iat':datetime.datetime.utcnow() },'access_secret',algorithm='HS256') def decode_access_token(token): try: #payload = jwt.decode(token, app.config['SECRET_KEY'], algorithms=["HS256"]) payload=jwt.decode(token,'access_secret',algorithm='HS256') return payload['user_id'] except: raise AuthenticationFailed('unauthenticated') Filter the user details form id form authentication token. -
how to create a object from django models to database and save it
Hi everyone this is my models and i'am calculation total total_time in a function . But unable to save the entry in database in (totaltime) field . Please suggest the best possible way to do this . class Attendance(models.Model): employee = models.ForeignKey( Employee, on_delete=models.CASCADE, default=1, related_name='Attendance') attendance_date = models.DateField(null=True) in_time = models.TimeField(null=True) out_time = models.TimeField(null=True, blank=True) totaltime = models.TimeField(null=True, blank=True) @property def total_time(self): if self.out_time != None: t1 = datetime.strptime(str(self.in_time), "%H:%M:%S") t2 = datetime.strptime(str(self.out_time), "%H:%M:%S") delta = t2 - t1 return delta else: return None I was trying to print the totaltime feild in class but shown result is none.please advise how can i add this entry in database -
Reverse for 'edit_vehicle' with arguments '('',)' not found. 1 pattern(s) tried: ['vehicle/edit/(?P<vehicle_id>[0-9]+)\\Z']
NoReverseMatch at /vehicle/vehicle_view/ Reverse for 'edit_vehicle' with arguments '('',)' not found. 1 pattern(s) tried: ['vehicle/edit/(?P<vehicle_id>[0-9]+)\\Z'] Here my Render link in HTML ✎ Views.py def edit_vehicle(request, vehicle_id): instance = get_object_or_404(Vehicle, id=vehicle_id) form = UpdateVehicleForm(request.POST or None, instance=instance) context = { 'form': form, 'vehicle_id': vehicle_id, 'page_title': 'Edit Vehicle' } if request.method == 'POST': if form.is_valid(): model_name = form.cleaned_data.get('model_name') vehicle_type = form.cleaned_data.get('vehicle_type') manufacture_company = form.cleaned_data.get('manufacture_company') vehicle_number = form.cleaned_data.get('vehicle_number') try: vehicle = Vehicle.objects.get(id=vehicle_id) vehicle.model_name = model_name vehicle.manufacture_company = manufacture_company vehicle.vehicle_type = vehicle_type vehicle.vehicle_number = vehicle_number vehicle.save() messages.success(request, "Successfully Updated") return redirect(reverse('edit_vehicle', args=[vehicle_id])) except Exception as e: messages.error(request, "Could Not Add " + str(e)) else: messages.error(request, "Fill Form Properly") return render(request, 'user/edit_vehicle.html', context) urls.py path("edit/int:vehicle_id",views.edit_vehicle, name='edit_vehicle'), -
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? -
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 … -
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. -
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!