Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
get() got an unexpected keyword argument 'title'
i want to fetch a blog with a model field which is unique and but when i click on a perticular blog it throw me above mentioned error here is my views class Blogs(View): def get(self, request): blog_list = Blog.objects.order_by('-joined_date') return render(request, 'blogs.html',{'blog_list':blog_list}) class ReadBlogs(View): def get(self, request, url_title): blog = Blog.objects.filter(title=url_title) return render(request,'blogs_read.html',{'blog':blog}) my model class Blog(models.Model): title = models.CharField(max_length=48, blank=False) urltitle = models.SlugField(max_length=48, blank=False, unique=True) title_image = models.ImageField(upload_to='blog',blank=True, null=True) subone = models.CharField(max_length=80, blank=False) subone_image = models.ImageField(upload_to='blog',blank=True,null=True) onedes = models.TextField(blank=False) my html for fetching right blog <div class="blogs"> {% for blogs in blog_list %} <a class="products" href="{% url 'blogs:readblog' title=blogs.urltitle %}"> <div class="blog col-4" style="width: 18rem; height:350px"> <img class="img" src="{{ blogs.title_image.url }}" alt="" height="250px" width="100%"> <div class="detail"> <h4 class="title text-center" style="color: #025; font-family:cursive;">{{blogs.title}}</h4> </div> </div> </a> {% endfor %} </div> my url.py urlpatterns = [ path('blogs/',Blogs.as_view(),name="Blogs"), path('<slug:title>/',ReadBlogs.as_view(),name="readblog") ] as you can see mu urltitle is unique slug field so but when i clicked on a particular blog i got above mentioned error any idea what causing error -
Django Rest Framework : Why Complex nested serializer tries to create nested fields in database when calling .is_valid()?
Context I have a project in which there are three entities : Account, Community and JoinRequest. A JoinRequest binds an Account (user) with a Community. And there should not be more than one JoinRequest for any couple (Account, Community). Problem I coded the respective models, serializers and unittest, which you can see below. But when I run my test, I get the following error... I don't understand, it seems the .is_valid() method of the JoinRequestSerializer tries to recreate an Account and a Community, whose data were previously passed as arguments at construction of the instance... Any idea why this error appears? join_request_serializer.errors {'user': {'email': [ErrorDetail(string='account with this email already exists.', code='unique')], 'username': [ErrorDetail(string='account with this username already exists.', code='unique')], 'password': [ErrorDetail(string='This field is required.', code='required')]}, 'community': {'name': [ErrorDetail(string='community with this name already exists.', code='unique')]}} Account class MyAccountManager(BaseUserManager): def create_user(self, email, username, password=None): if not email: raise ValueError('Users must have an email address') if not username: raise ValueError('Users must have an username') user = self.model( email=self.normalize_email(email), username=username, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, username, password): # This method must be overridden to use MyAccountManager class user = self.create_user( email=self.normalize_email(email), username=username, password=password, ) user.is_admin = True user.is_staff = True user.is_superuser … -
The source code of the code pen is not applied
I've tried pasting the code copied from the code pen site below in the vault, but it doesn't work. I wonder why it's not working. What do I have to do to make it work? The CSS source code was imported using Viw compiled. Does this matter? Code Pen Address https://codepen.io/dodozhang21/pen/vNOmrv Paste Source Code <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <style> @import url(https://fonts.googleapis.com/css?family=Nunito); @import url(//maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css); *, *:before, *:after { -moz-box-sizing: border-box; -webkit-box-sizing: border-box; box-sizing: border-box; } html { height: 100%; } body { background: #ffd16e; height: 100%; padding: 0; margin: 0; font-size: 16px; display: -webkit-flex; display: flex; -webkit-align-items: center; align-items: center; -webkit-justify-content: center; justify-content: center; } .uploadWrapper { font-family: "Nunito", sans-serif; } .imageUploadForm { background: #6e95f7; height: 400px; width: 500px; position: relative; display: -webkit-flex; display: flex; -webkit-align-items: flex-end; align-items: flex-end; -webkit-justify-content: center; justify-content: center; -webkit-flex-wrap: wrap; flex-wrap: wrap; } .imageUploadForm .helpText { color: white; display: block; position: absolute; top: 2%; left: 0; width: 100%; height: 100%; text-align: center; font-size: 30px; } .imageUploadForm .helpText:after { content: "\f067"; font-family: "FontAwesome"; font-size: 150%; color: rgba(255, 255, 255, 0.5); display: -webkit-flex; display: flex; -webkit-align-items: center; align-items: center; -webkit-justify-content: center; justify-content: center; margin: 4% auto auto auto; width: 50%; height: 50%; border: … -
Unable to migrate in django
model.py class Staff(models.Model): organization = models.ForeignKey( Organization, related_name='staff_organization', on_delete=models.CASCADE, blank=True) user = models.OneToOneField( User, on_delete=models.CASCADE, blank=True) phone = models.CharField(max_length=15, blank=True) address = models.CharField(max_length=200, blank=True) I am trying to add the new field in the database table. II just added the address field. I got following error: The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "D:\Project\AIT Project\project\venv\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "D:\Project\AIT Project\project\venv\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "D:\Project\AIT Project\project\venv\lib\site-packages\django\core\management\base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "D:\Project\AIT Project\project\venv\lib\site-packages\django\db\backends\base\schema.py", line 142, in execute cursor.execute(sql, params) File "D:\Project\AIT Project\project\venv\lib\site-packages\django\db\backends\utils.py", line 100, in execute return super().execute(sql, params) File "D:\Project\AIT Project\project\venv\lib\site-packages\django\db\backends\utils.py", line 68, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "D:\Project\AIT Project\project\venv\lib\site-packages\django\db\backends\utils.py", line 77, in _execute_with_wrappers return executor(sql, params, many, context) File "D:\Project\AIT Project\project\venv\lib\site-packages\django\db\backends\utils.py", line 86, in _execute return self.cursor.execute(sql, params) File "D:\Project\AIT Project\project\venv\lib\site-packages\django\db\utils.py", line 90, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "D:\Project\AIT Project\project\venv\lib\site-packages\django\db\backends\utils.py", line 86, in _execute return self.cursor.execute(sql, params) django.db.utils.ProgrammingError: relation "auth_user_email_1c89df09_uniq" already exists -
How to develop webapps for manage other webapps as plugin
Is it possible to develop a web application that will dynamically connect and manage other web applications. These applications must be on the same domain name, with different prefixes. Is it possible on python? If so, tell me /mange/ app1 #url_prefix=/app1 | ***files app1*** app2 #url_prefix=/app2 | ***files app2*** run.py -
django - ValueError: Dependency on app with no migrations
I'm deploying my Django project to a VPS using Dokku. My project uses a CustomUser model, and there are two apps in the project: accounts which has the CustomUser and gradebook. During deployment the process runs makemigrations and migrate. After deployment when I run python manage.py showmigrations I get the following: account [X] 0001_initial [X] 0002_email_max_length accounts (no migrations) admin [X] 0001_initial [X] 0002_logentry_remove_auto_add [X] 0003_logentry_add_action_flag_choices auth [X] 0001_initial [X] 0002_alter_permission_name_max_length [X] 0003_alter_user_email_max_length [X] 0004_alter_user_username_opts [X] 0005_alter_user_last_login_null [X] 0006_require_contenttypes_0002 [X] 0007_alter_validators_add_error_messages [X] 0008_alter_user_username_max_length [X] 0009_alter_user_last_name_max_length [X] 0010_alter_group_name_max_length [X] 0011_update_proxy_permissions [X] 0012_alter_user_first_name_max_length contenttypes [X] 0001_initial [X] 0002_remove_content_type_name gradebook (no migrations) sessions [X] 0001_initial sites [X] 0001_initial [X] 0002_alter_domain_unique Where account is from django-allauth. It looks like my apps are not being migrated. So I then do: me@myserver:/home$ dokku run gradebook python manage.py makemigrations accounts success Migrations for 'accounts': accounts/migrations/0001_initial.py - Create model CustomUser me@myserver:/home$ And it looks like things are ready migrate. I then run migrate and get an error django - ValueError: Dependency on app with no migrations: accounts: shmish@Henry:/home$ dokku run gradebook python manage.py migrate accounts success Traceback (most recent call last): File "/app/.heroku/python/lib/python3.8/site-packages/django/db/migrations/loader.py", line 174, in check_key return self.graph.root_nodes(key[0])[0] IndexError: list index out of range During handling of … -
What will be the best approach for setting up multiple subdomains in a single django project using mysql?
I am about to build a web-app and use it as a product for multiple organizations. Let's say my domain name is example.com And I have 2 customers, org1 (Organization 1) and org2 (Organization 2) So, my sub domains would be org1.example.com and org2.example.com Now, I have gone through the Django tenant approach which uses PostgreSQL. But I am looking for something in MySQL. But my question is that is it possible for me to use MySQL and use separate databases, to maintain risk free and also data privacy for orgs, and also use Django tenant or is there some different approach to solve this subdomain issue? Do note, I'll be using my platform as a product so the subdomains would be given to each client who would be given credentials to access the platform (Kinda like an inventory system). Any links or videos is highly appreciated. -
Display objects related to requested object and children in Materialized Path trees
categories/models.py from django.db import models from treebeard.mp_tree import MP_Node class Category(MP_Node): title = models.CharField(max_length=50) slug = models.SlugField(unique=True) node_order_by = ['title'] class Meta: verbose_name = 'category' verbose_name_plural = 'categories' def __str__(self): return 'Category: {}'.format(self.title) categories/views.py from django.views.generic import DetailView from .models import Category class CategoryDetailView(DetailView): model = Category context_object_name = 'category' template_name = 'categories/category_detail.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["products_in_category"] = self.object.products.filter(active=True) return context category_detail.html ..... {% for p in products_in_category %} <h2><a href="{{ p.get_absolute_url }}">{{ p.title }}</a></h2> ..... The code above works well to display products that belong to a specific category but I would also be able to display the products that belong to its descendants. Example: shoes ├── sneakers │ ├── laced sneakers │ └── non-laced sneakers If I'm on the category page for sneakers I would want to be able to see products related to both Laced Sneakers and Non-laced Sneakers. My thought was that the get_context_data could look something like this def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["products_in_category"] = self.object.get_descendants().products.filter(active=True) return context But unfortunately, that did not work out. I was thinking about using ListView instead but the category page will have a description describing the category and for that reason, I figure DetailView would … -
Sorting a JSONField by adding an index value?
I am using a JSONField to store a custom form with field labels/values. I am having an issue when rendering the form. Each time the form gets rendered, the order is changed since I am using a dictionary. I was thinking of adding an extra value to my JSONField just to store an integer, in which I can order by. I am wondering if this is a possible solution, or if there was any other "best" way to keep this form in order. I have a simple model, class House(models.Model): form = JSONField(default=dict) Which in my view a json file is loaded into it with a json file as such. { "outside": [ { "fields": [ { "label": "Pool", "value": "" }, { "label": "Shed", "value": "" }, ], "index": 0 } ], "inside": [ { "fields": [ { "label": "Bedrooms", "value": "" }, { "label": "Baths", "value": "" }, ], "index": 1 } ], When the form is rendered in my view, I am using basic logic house = House.objects.get(id=1) form = house.form.items() return render(request, template, context={'form': form} The json loads fine the first time, with all fields with the label outside leading, and then fields with the label … -
How can I deal with rendering a selected template - getting a ,,Http request has no attribute'' meta error
def thanks(request): template = select_template(['poll/a.html', 'poll/b.html']) template.render({'a': 'b'}, HttpRequest) This is my code and it throws an error as above. I tried using return too. In documentaion it tells that it should be specifically HttpRequest, not request. Where is the problem? -
Remote Access to mysql from DigitalOcean Droplet
I have created my own server on Digital Ocean to upload the Django project to the Internet. But the problem is that I have a project-specific mysql database on phpmyadmin. The question is how can I link or upload this database to the server that I created so that the site can work normally? -
How i can get all these items in order page? There is no add to cart
I want to get all these items from this page. It was a customer order item where i select which items customer need. When all items are added than i want to click on check in button then it will rendered me into ordered page i can add customers information. It was an inventory management concept. -
DRF: router for ViewSet with a foreign-key lookup_field
Using Django REST Framework 3.12.4, I cannot properly get the URLs for a ViewSet to work if that ViewSet has a foreign-key lookup field. I have the following in models.py: class Domain(models.Model): name = models.CharField(max_length=191, unique=True) class Token(rest_framework.authtoken.models.Token): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) domain_policies = models.ManyToManyField(Domain, through='TokenDomainPolicy') class TokenDomainPolicy(models.Model): token = models.ForeignKey(Token, on_delete=models.CASCADE) domain = models.ForeignKey(Domain, on_delete=models.CASCADE) class Meta: constraints = [models.UniqueConstraint(fields=['token', 'domain'], name='unique_entry')] In views.py, I have: class TokenDomainPolicyViewSet(viewsets.ModelViewSet): lookup_field = 'domain__name' permission_classes = (IsAuthenticated,) serializer_class = serializers.TokenDomainPolicySerializer def get_queryset(self): return models.TokenDomainPolicy.objects.filter(token_id=self.kwargs['id'], token__user=self.request.user) You can see from TokenDomainPolicyViewSet.lookup_field that I would like to be able to query the -detail endpoint by using the related Domain's name field instead of its primary key. (name is unique for a given token.) I thought this can be done with lookup_field = 'domain__name'. However, it doesn't quite work. Here's my urls.py: tokens_router = SimpleRouter() tokens_router.register(r'', views.TokenViewSet, basename='token') tokendomainpolicies_router = SimpleRouter() tokendomainpolicies_router.register(r'', views.TokenDomainPolicyViewSet, basename='token_domain_policies') auth_urls = [ path('tokens/', include(tokens_router.urls)), # for completeness only; problem persists if removed path('tokens/<id>/domain_policies/', include(tokendomainpolicies_router.urls)), ] urlpatterns = [ path('auth/', include(auth_urls)), ] The list endpoint works fine (e.g. /auth/tokens/6f82e9bc-46b8-4719-b99f-2dc0da062a02/domain_policies/); it returns a list of serialized TokenDomainPolicy objects. However, let's say there is a Domain object with name = 'test.net' related … -
Object type <class 'str'> cannot be passed to C code CCAvenue payment gateway interation pycryptodome::3.10.1
I want to integrate CCAvenue payment gateway into my website, for that purpose I have to send all the requirements such as Merchant ID, working key etc in encrypted form to their page for payment. For encryption I am using pycryptodome==3.10.1. This is the method which I am using to encrypt my details. def encrypt(plain_text, working_key): """ Method to encrypt cc-avenue hash. :param plain_text: plain text :param working_key: cc-avenue working key. :return: md5 hash """ iv = '\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f' plain_text = pad(plain_text) byte_array_wk = bytearray() byte_array_wk.extend(map(ord, working_key)) enc_cipher = AES.new(hashlib.md5(byte_array_wk).digest(), AES.MODE_CBC, iv) #error line hexl = hexlify(enc_cipher.encrypt(plain_text)).decode('utf-8') return hexl At 3rd last line, I am getting this error Object type <class 'str'> cannot be passed to C code. Here is the data which I am encrypting, just in case if you need it. merchant_data = 'merchant_id=' + p_merchant_id + \ '&' + 'order_id=' + p_order_id + \ '&' + "currency=" + p_currency + \ '&' + 'amount=' + p_amount + \ '&' + 'redirect_url=' + p_redirect_url + \ '&' + 'cancel_url=' + p_cancel_url + \ '&' + 'language=' + p_language + \ '&' + 'billing_name=' + p_billing_name + \ '&' + 'billing_address=' + p_billing_address + \ '&' + 'billing_city=' + p_billing_city … -
Django: Include a html on ajax request
I am using Django as my Webframework togehter with Ajax for async calls. When a button is pressed I want an entire HTML file to be loaded in (like normal includes). This is the AJAX code: $.ajax({ url: "{% url 'project-detail' project_object.id %}", type: 'get', data: { ... }, success: function (response) { $("#div1").html("{% include 'projects/recommendations.html' %}") } }) As you can see I try to wrap {% include 'projects/recommendations.html' %} with ".". This unfortunatley doesnt work. As a work around I thought of reading the file in and output the string. As the to be included file is also relatively large ~150 LOC I try to avoid having it all in one file. Is there a way to neatly load this in? -
nginx - gunicorn - django allauth redirect to 127.0.0.1 issue, how can I solve this?
I want to deploy my django app with nginx-gunicorn. so I set nginx and gunicorn conf like this. /etc/nginx/conf.d/default.conf included by /etc/nginx/nginx.conf server { listen 80; server_name my.domain.com; charset utf-8; location /static/ { root /home/flood/dj-eruces-ango; } location / { proxy_pass http://127.0.0.1:8000; #include proxy_params; #proxy_pass http://unix:/etc/systemd/system/gunicorn.socket; } } /etc/systemd/system/gunicorn.service [Unit] Description=gunicorn daemon After=network.target [Service] User=flood Group=www-data WorkingDirectory=/home/flood/dj-eruces-ango/ ExecStart=/home/flood/dj-eruces-ango/secure/bin/gunicorn \ --workers 2 \ --bind 0.0.0.0:8000 \ config.wsgi:application [Install] WantedBy=multi-user.target and I set my google social-auth api to 'my.domain.com' and 'my.domain.com/auth/google/login/callback/' but when I try social auth, the error occurs below. 400 error: redirect_uri_mismatch http://127.0.0.1:8000/auth/google/login/callback/ I want to solve this. show localhost issue(not a my.domain.com) and redirect_uri_mismatch issue. How can I try? -
django.db.utils.ProgrammingError: (1146, "Table 'zebrapro.corpann_comments_updated' doesn't exist") Error. How to fix?
I shifted my django website to MySQL DB on localhost. Post this migrated models in MySQL. However, I deleted one table directly from SQL language. Now no matter what I run, the django python manage.py migrate command shows this error - django.db.utils.ProgrammingError: (1146, "Table 'zebrapro.corpann_comments_updated' doesn't exist") I tried creating similar table using SQL too. However, does not work. Please help fix this. -
ISSUE ON NOT NULL constraint failed: accounts_user.course_id
I'm trying to create a multiple user model in django. I am a beginner using django and as such not in a position to get the exact result I need. I got an error when trying to createsuperuser. Here is my model.py *from django.db import models from admin_dash.models import Course from django.contrib.auth.models import ( BaseUserManager, AbstractBaseUser ) class UserManager(BaseUserManager): def create_user(self,roll,phone,name,password=None): if not roll: raise ValueError('You Don't have Permission to do exam') user = self.model( roll=roll, phone=phone, name=name ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self,roll,phone,name, password): user = self.create_user(roll,phone,name,password=password) user.is_admin = True user.is_staff=True user.save(using=self._db) return user class User(AbstractBaseUser): phone= models.CharField(verbose_name='phone number', max_length=12,unique=True) name=models.CharField(max_length=150,null=True) roll=models.CharField(max_length=20,verbose_name='roll',unique=True) course=models.ForeignKey(Course,on_delete=models.CASCADE) date_joind=models.DateTimeField(verbose_name='date joind', auto_now_add=True) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) is_staff=models.BooleanField(default=False) USERNAME_FIELD = 'roll' REQUIRED_FIELDS = ['name','phone'] objects = UserManager() def __str__(self): return self.name def has_perm(self, perm, obj=None): return self.is_admin def has_module_perms(self, app_label): return True* This is My admin.py *from django.contrib import admin from .import models # Register your models here. admin.site.register(models.User)* Trying to create a superuser I got the following traceback *Traceback (most recent call last): File "C:\Users\freddyparc\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\utils.py", line 86, in _execute return self.cursor.execute(sql, params) File "C:\Users\freddyparc\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\sqlite3\base.py", line 396, in execute return Database.Cursor.execute(self, query, params) sqlite3.IntegrityError: NOT NULL constraint failed: accounts_user.course_id The above exception was … -
Django - my function doesn't update data in the database
My function does not update the data in the database. It seems to work properly, but nothing changes in the database task.py import time from celery import shared_task from store.models import Product @shared_task # do something heavy def hh(self): records = Product.objects.filter() for rec in records: rec.price_before_offer = rec.price * 4 / 3 rec.save() while True: hh() time.sleep(10000) -
Can anyone tell how to upload multiple files using Restangular, I'm using Django Rest Framework as a backend
On my web page, I have multiple questions and their answers and all fields have a browse button that selects files, images. I have put attachment and answer in the $scope.question.attachment so when I am making API call it is taking this data from Frontend sends to the backend and also I am not using the element and FYI answers are going to the backend correctly and storing in database. (now you are thinking how answers are going in backend and not attachments because I have put attachments read_only = true) class ServiceProjectAnswerSerializer(serializers.ModelSerializer): attachement = AnswerAttachmentsSerializer(read_only=True, many=True) def create(self, validated_data): instance = ServiceProjectAnswer(**validated_data) if isinstance(self._kwargs["data"], dict): instance.save() return instance class Meta: model = ServiceProjectAnswer fields = ('project', 'question', 'answer', 'attachement') list_serializer_class = BulkCreateListSerializer My problem is that how can I select multiple files and how to do a rectangular post method for files (with files I am also sending answers and question id)so please keep that in mind. how to select multiple files? How to send files and data both? with this method (If you want more info please tell me in comments and If you don't understand what I am talking about then also please tell me in comments … -
Django Bulk Create doesn't respect ignore_conflicts for django.db.utils.IntegrityError
I am trying to do two sequential bulk creates to sync data to django from another data store. The problem is the data store allows duplicates but I don't want to allow that in my django schema. I'm ok losing the duplicates. Duplicates are based on two of the items fields The first bulk create generates a bunch of items, the second creates a through field for those items. If there is a duplicate in the first list of items, the second bulk create fails since it is trying to create a through field for a item that doesn't exist. I would want that second create to fail gracefully like the first since I'm using ignore_conflicts=True but it throws an exception and no other items get created. Even worse, since I'm supplying the primary key the first bulk create returns all of the items, even if they weren't actually created. I'm creating hundreds of these every second, so I have to use bulk create. Anyway to get bulk create to ignore the IntegrityError exception? I'm using postgresql. -
Heroku deployment failure-- psycopg2 installation failure
I am getting a persisting error when I am deploying my python/Django project to heroku. I keep getting "It appears you are missing some prerequisite to build the package from source. You may install a binary package by installing 'psycopg2-binary' from PyPI. If you want to install psycopg2 from source, please install the packages required for the build and try again. For further information please check the 'doc/src/install.rst' file (also at <https://www.psycopg.org/docs/install.html>)." and when I install psycopg2 I also get the same message, any help please github repo Link : https://github.com/moeabraham/finalsoccer Also, they might be helpful, when typing commands for pip I usually get an error unless I wrote it as pipenv! I am a beginner and this has been confusing so far :) -
Django Forms: Attributes on Select Element not being applied?
I've got a Django Model Form that I am rendering in a modal window. It's displaying fine and I have no issues except for the styling of one of the dropdowns. I can add/remove classes to the other field in the form without issue - but the Select widget does not use the attrs I am giving it. My Issue: The select widget in the Django model form is not applying the correct classes My Attempts To Fix: I've tried setting the attributes in the __init__ method Setting them as they currently are (which is the recommended method from documentation) Creating another model to extend the Select widget as found here on SO My Code: forms.py: class EvaluationForm(forms.ModelForm): """Form definition for Evaluation.""" # THESE ATTRS LOAD FINE AND CLASSES APPLIED AS EXPECTED evaluation_date = forms.CharField( max_length=100, widget=forms.TextInput(attrs={"class": "form-control test"}), ) # THESE ATTRS ARE NOT BEING APPLIED TO THE SELECT WIDGET - NO CLASSES APPLIED evaluation_level = forms.ModelChoiceField( queryset=EvaluationLevel.objects.all(), widget=forms.Select( attrs={"class": "form-control something something-else"} ), ) class Meta: """Meta definition for Evaluationform.""" model = Evaluation fields = [ "summative", "evaluation_type", "evaluation_level", "evaluation_date", ] widgets = { "summative": forms.HiddenInput(), "evaluation_type": forms.HiddenInput(), } template html that renders the form: {% if form.non_field_errors … -
Page not found (404), The empty path didn’t match any of these
I know this question is asked in many different forms, but I can't find a solution for my problem; My problem is I need to display the static pages and I have run into this error:enter image description here I have also used URL instead of re_path but it doesn't work, I am newly to Django please any help would be appreciated. Here is my code: `urlpatterns = [ path('admin/', admin.site.urls), re_path(r'^', include('EmployeeApp.urls')) ]` App.urls: `urlpatterns=[ re_path(r'^department$',views.departmentApi, name='department'), re_path(r'^department/([0-9]+)$',views.departmentApi, name='departmentApi'), re_path(r'^employee$',views.employeeApi, name='employee'), re_path(r'^employee/([0-9]+)$',views.employeeApi, name='employeeApi'), re_path(r'^Employee/SaveFile$', views.SaveFile, name='SaveFile') ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)` The view: @csrf_exempt def departmentApi(request, id=0): if request.method == 'GET': department = Departments.objects.all() departments_serializer = DepartmentSerializer(department, many=True) return JsonResponse(departments_serializer.data, safe=False) elif request.method == 'POST': department_data = JSONParser().parse(request) department_serializer = DepartmentSerializer(data=department_data) if department_serializer.is_valid(): department_serializer.save() return JsonResponse("Added Successfully!!", safe=False) return JsonResponse("Failed ro Add.",safe=False) elif request.method=='PUT': department_data = JSONParser().parse(request) department=Departments.objects.get(DepartmentId=department_data['DepartmentId']) department_serializer=DepartmentSerializer(department,data=department_data) if department_serializer.is_valid(): department_serializer.save() return JsonResponse("Updated Successfully!!", safe=False) return JsonResponse("Failed to Update.", safe=False) elif request.method == 'DELETE': department = Departments.objects.get(DepartmentId=id) department.delete() return JsonResponse("Deleted Successfully!!", safe=False) @csrf_exempt def employeeApi(request,id=0): if request.method=='GET': employees = Employees.objects.all() employees_serializer = EmployeeSerializer(employees, many=True) return JsonResponse(employees_serializer.data, safe=False) elif request.method=='POST': employee_data=JSONParser().parse(request) employee_serializer = EmployeeSerializer(data=employee_data) if employee_serializer.is_valid(): employee_serializer.save() return JsonResponse("Added Successfully!!" , safe=False) return JsonResponse("Failed to Add.",safe=False) elif request.method=='PUT': employee_data = … -
<!DOCTYPE html> missing in Selenium Python page_source
I'm using Selenium for functional testing of a Django application and thought I'd try html5lib as a way of validating the html output. One of the validations is that the page starts with a <!DOCTYPE ...> tag. The unit test checks with response.content.decode() all worked fine, correctly flagging errors, but I found that Selenium driver.page_source output starts with an html tag. I have double-checked that I'm using the correct template by modifying the title and making sure that the change is reflected in the page_source. There is also a missing newline and indentation between the <html> tag and the <title> tag. This is what the first few lines looks like in the Firefox browser. <!DOCTYPE html> <html> <head> <title>NetLog</title> </head> Here's the Python code. self.driver.get(f"{self.live_server_url}/netlog/") print(self.driver.page_source And here's the first few lines of the print when run under the Firefox web driver. <html><head> <title>NetLog</title> </head> The page body looks fine, while the missing newline is also present between </body> and </html>. Is this expected behaviour? I suppose I could just stuff the DOCTYPE tag in front of the string as a workaround but would prefer to have it behave as intended. Chris