Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django + Bootstrap modal form still shows Djangos default errors, not bootstrapped errors?
I am struggling with displaying bootstraps form errors in a popup form modal. When I submit the form, with some missing required fields, I am still getting Django's built in basic form error messages, or even if a field requires a decimal, I enter text, I get an error but it's still django's built in basic validation error. I am using crispy-forms and bootstrap to try to display the errors in a nicer way on the page. This is the way errors are being displayed now.... I have a simple form here... {% load crispy_forms_tags %} <form role="form" method="post" name="employee-add" id="employee-add" action="{% url 'employee_add' company_id %}"> {% csrf_token %} <input type="hidden" id="companyID" name="comp" value="{{ company_id }}"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> <h4 class="modal-title">Add Employee</h4> </div> <div class="modal-body"> <div class="modal-inner defult-inner"> {% for field in employee_form %} <div class="form-group{% if field.errors %} has-error{% endif %}"> {{ field|as_crispy_field }} {% for error in field.errors %} <span class="error-msg">{{ error }}</span>s {% endfor %} </div> {% endfor %} <div class="footer-button employee-footer"> <button class="btn btn-default" data-dismiss="modal">Cancel</button> <button class="btn btn-danger" id="save">Save</button> </div> </div> </div> </form> The modal form is populated with an AJAX GET request. $(function () { // GET request … -
Django: how set default random value for readonly_field in admin view?
In django project, I created a default function called "create_code" to randomly generate a default value for "code" field in models.py file. # models.py class Project(models.Model): name = models.CharField("Project name", max_length=255) code = models.CharField("Code", max_length=10, default=create_code, editable=False) In admin.py file, I set "code" as a readonly_field. #admin.py @admin.register(Project) class ProjectAdmin(admin.ModelAdmin): fields = ('name', 'code') readonly_fields = ('code', ) The problem occours when I create a new Project object in admin page. The default value for "code" appers (eg. ABCD), but when I save the data this value change to another one (eg. EFGH). I think two objects are been created: one when loads the page and other when save the data. How can I read the "code" value from first object to overwrite the last one and save "ABCD" instead of "EFGH"? -
Django ORM bulk update with group by condition
At first have a look at models and query: This is my models class Dish(models.Model): restaurant = models.ForeignKey( restaurant, on_delete=models.CASCADE, related_name="dishes", ) is_active = models.BooleanField(default=True) start = models.DateTimeField(null=True, blank=True) and this is my query def update_dish_status(): today = datetime.today().strftime('%Y-%m-%d') for dish in Dish.objects.all(): if str(dish.start.date()) == str(today): dish.is_active = True dish.save() else: dish.is_active =False dish.save() You may notice that i am updating dish to change is_active and is_active status. Currently it's working the way i dont want that way. I want to when in a restaurant at least one dish's date are same as today's date, then that restaturant's all the dish should be active status False except the dish that is date is same as today date. and if any restaurants dont have such dish that start date matched with today's date, then those restaurants all the dish status should be active, i mean is_active=True For example, i have a restaurants, and in my restaurants 10 dishes. if at least one dish's start date is same as today's date, then that dish will is_active=True and all those dish whose date are not same as today, those dish will be is_active=False But there is another case should be handled like, … -
Connection Timed Out - Apache2 & Django Deployment
I rent a Ubuntu VPS and deployed my Django project using Apache2. But when I try to connect port 80(HTTP) with the IP number it results in the connection timed out. Here is my Apache configuration: <VirtualHost *:80> WSGIScriptAlias / /var/www/html/SistemDedektifi/SistemDedektifi/SistemDedektifi/wsgi.py WSGIDaemonProcess SistemDedektifi python-home=/var/www/html/SistemDedektifi/SistekDedektifi/venv python-path=/var/www/html/SistemDedektifi/SistemDedektifi WSGIProcessGroup SistemDedektifi Alias /static /var/www/html/SistemDedektifi/SistemDedektifi/static <Directory /var/www/html/SistemDedektifi/SistemDedektifi/static> Require all granted </Directory> <Directory /var/www/html/SistemDedektifi/SistemDedektifi/SistemDedektifi> <Files wsgi.py> Require all granted </Files> </Directory> Last two days I am working on configuring this but I can't figure it out. -
How to mock serializer in django testing?
So i was testing a rest api method in with we are returning json formatted serializer.data but when we tried to make testcases for this object we couldn't able to mock serializer properly. views.py data = {Something in jason format} serializer = ClassName1(data=data) serializer.is_valid(raise_exception=True) rec_data = {Something in json format} rec_serializer = ClassName2(data=rec_data) rec_serializer.is_valid(raise_exception=True) return Response({'key01':serializer.data, 'key02':rec_serializer.data}) test_views.py @mock.patch('myapp.serializers.ClassName1.data') @mock.patch('myapp.serializers.ClassName2.data') @mock.patch('myapp.serializers.ClassName1.is_valid') @mock.patch('myapp.serializers.ClassName2.is_valid') def test_serializer(TestCase, mock_c2_isvalid, mock_c1_isvalid, mock_c2_data, mock_c1_data): url = reverse('view-name') mock_c2_data.return_value = {dummy json data} mock_c1_data.return_value = {dummy json data} req = RequestFactory().get(url) response = views.Class.as_view()(req) self.assertEquals(response.status_code, 200) above test case is working but we have to patch two times for one serializer if there is any way to mock the serializer object if self and use that to return value for some method. let me know if there is another better way to mock serializer. -
Getting External url Hit in newrelic APM without the actual url
We are using newrelic in docker container on aws ec2. The transaction details on APM for a particular API is showing "urllib3[169.254.169.254]" in stacktrace, but I cannot identiy the source of it, also as per code no external link should be hit(tested in local no link is being hit; tested using pyinstrument). I have attached an image of the stacktrace please let me know how to find the target and get to the actual link being hit. -
how can adjust divs card position
i want to adjust divs so the last login list come on the right of devices list so what tags should i use and ? and this is the code : <div class="row "> <div class="card card-body col text-center"> <h5>All devices </h5> <hr> <table class="table"> <tr> .... </tr> {% for device in devices %} <tr> ..... </tr> {% endfor %} </table> </div> <div class="card card-body col text-center"> <h5>Last login </h5> <hr> <table class="table"> <tr> .... </tr> {% endfor %} </table> </div> </div> -
FactoryBoy - how to pass initial values?
I'm trying to use factory_boy in my tests. The problem is that it seems not to be taking to account Factory parameters. factory class ProductFactory(DjangoModelFactory): class Meta: model = Product title = factory.Faker('sentence') created_by = factory.SubFactory(UserFactory) organisation = factory.RelatedFactory(OrganisationFactory) sku = factory.Faker('word') usage def test_sku_organisation_uniqueness(self) -> None: print(self.product.organisation) product1 = ProductFactory.create(sku='xxxx', organisation=self.product.organisation) product2 = ProductFactory.create(sku='xxxx', organisation=self.product.organisation) print(product1.sku) print(product1.organisation) print(product2.sku) print(product2.organisation) Which returns: My organisation xxxx owner xxxx newspaper The strings "owner" and "newspaper" are organisations but I wanted it to have "My organisation" object. How can I do that? -
Django dependent drop down not functioning properly
Django noob I am currently attempting to implement a dependent drop down list for car models - manufactures I am following this tutorial I have the form displaying properly but the issue I am facing is if I select a manufacture no models are displayed. I have spent a bunch of time attempting to solve this and I am out of ideas All feedback welcome! forms.py from blog.models import Post, Manufactures, Models class PostForm(ModelForm): class Meta: model = Post fields = 'title', 'manufacture', 'model', 'content', 'image', 'aspiration' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['model'].queryset = Models.objects.none() models.py class Manufactures(models.Model): manufacture_id = models.AutoField(primary_key=True) manufacture = models.CharField(max_length=55) def __str__(self): return self.manufacture def get_absolute_url(self): return reverse('db-manufactures', kwargs={'pk': self.pk}) class Models(models.Model): model_id = models.AutoField(primary_key=True) model = models.CharField(max_length=55) model_manufacture = models.ForeignKey(Manufactures, on_delete=models.CASCADE) def __str__(self): return self.model def get_absolute_url(self): return reverse('blog-models', kwargs={'pk': self.pk}) Views.py def loadModels(request): manufacture_id = request.GET.get('model_manufacture') models = Models.objects.filter(manufacture_id = manufacture_id) return render(request, 'model_dropdown_list.html', {'models': models}) class PostCreateView(LoginRequiredMixin, CreateView): model = Post form_class = PostForm def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) def save(self, *args, **kwargs): super(Post,self).save(*args, **kwargs) model_dropdown_list.html <option value="">---------</option> {% for model in models %} <option value="{{ model.pk }}">{{ model.name }}</option> {% endfor %} post_form.html {% extends "blog/base.html" %} {% … -
Emojis are replaced by question marks (Django / MySQL)
Emojis are replaced by '?' when saved to the db and I cannot find where it does come from. I get "a🙂a" transformed to "a?a", either via django admin or directly through my code Any idea to fix this problem? My configuration: settings.py: DATABASES = { 'default': { ... 'OPTIONS': { 'init_command': "SET NAMES utf8mb4; SET CHARACTER SET utf8mb4; SET character_set_connection=utf8mb4; SET collation_connection = 'utf8_unicode_ci';", 'charset': 'utf8mb4', }, } } my mysql configuration: [mysqld] character-set-server = utf8mb4 collation-server = utf8mb4_unicode_ci init-connect='SET NAMES utf8mb4' [client] default-character-set=utf8mb4 [mysql] default-character-set=utf8mb4 charset in db: MariaDB [dbn]> SHOW VARIABLES WHERE Variable_name LIKE 'character\_set\_%' OR Variable_name LIKE 'collation%'; +--------------------------+--------------------+ | Variable_name | Value | +--------------------------+--------------------+ | character_set_client | utf8mb4 | | character_set_connection | utf8mb4 | | character_set_database | utf8mb4 | | character_set_filesystem | binary | | character_set_results | utf8mb4 | | character_set_server | utf8mb4 | | character_set_system | utf8 | | collation_connection | utf8mb4_general_ci | | collation_database | utf8mb4_unicode_ci | | collation_server | utf8mb4_unicode_ci | +--------------------------+--------------------+ the table containing the field: SHOW TABLE STATUS where name="xxx" => "utf8mb4_unicode_ci" for that table the field receiving the emoji string: MariaDB [dbn]> SELECT column_name, character_set_name, collation_name FROM information_schema.columns where TABLE_NAME='xxx'; +-----------------+--------------------+--------------------+ | column_name | character_set_name | collation_name | +-----------------+--------------------+--------------------+ … -
What is the difference between Django socket.io and Django channels?
What should I use to add a chat option on my website?. And what is the easiest to learn?. Can I learn it in 3 to 4 days. -
Is there an Visual Studio Code extension for formatting Django template tasg in Javascript?
I have a piece of code here I want to format <script> objectArray = [] {% for object in allObject %} myObject = { title: "{{object.title}}", number: parseFloat("{{object.number}}"), dateCreated : "{{object.dateCreated}}", } objectArray.push(myObject) {%endfor%} </script> After I "Shirt" + "Alt" + "F" to format it with Beautifier extension, it becomes this <script> objectArray = [] { % for object in allObject % } myObject = { title: "{{object.title}}", number: parseFloat("{{object.number}}"), dateCreated: "{{object.dateCreated}}", } objectArray.push(myObject) { % endfor % } </script> Beautifier can format Django template tags in HTML but it becomes strange when it's in Javascript I think a lot of people have the same problem. It would be great if you guys share your solution -
Django form.is_valid() is False, but not hitting the else statement?
I am working on something that should be pretty simple, but running into a very odd form issue. @csrf_protect def employee_create(request, company_id): template_name = 'business/employee-create.html' data = dict() company = Company.objects.get(id=company_id) if request.method == 'POST': employee_form = EmployeeForm(request.POST) if employee_form.is_valid(): logger.debug('Valid') emp = employee_form.save(commit=False) emp.company = venue emp.user = request.user emp.save() return redirect('comp_detail', company_id=company_id) else: logger.debug('Error') else: employee_form = EmployeeForm() data['html_form'] = render_to_string( template_name, {'form': employee_form, 'company_id': company.id}, request=request, ) return JsonResponse(data) The GET request is just a popup bootstrap form. But my odd situation is happening in the POST request. I am sending an invalid form that is completely empty(in the form modal I get djangos built in form errors popping up) , but the else statement never gets hit, that is supposed to print Error in my django logger. The form is invalid, but is also not invalid? There has to be something that I am missing here?? Thanks in advance for anyone that takes a glance! -
Django: Template statement to check if the user has liked the post or not
Hi Im trying to show a like button with some html class on it if the post is already liked else a button without the html class, I have the following model and I wanna check if the request.user has liked the picture or not on my template. Here's my model: class post(models.Model): user = models.ForeignKey(User, related_name='has_liked', on_delete=models.CASCADE) caption = models.CharField(max_length=100) image = models.FileField(upload_to='images/', null=True, blank=True) video = models.FileField(upload_to='videos/', null=True, blank=True) created = models.DateTimeField(auto_now_add=True) like = models.ManyToManyField(User, null=True, blank=True, default='') def __str__(self): return self.caption def total_likes(self): return self.like.count() Here's my view: @login_required def like_post(request): Post = get_object_or_404(post, id=request.GET.get('post_id')) cssClass = 'colorRed' if Post.like.filter(id=request.user.id).exists(): Post.like.remove(request.user) else: Post.like.add(request.user) count = Post.like.count() users = Post.like.all() user = [] for i in users: user.append((i.username)) response = { 'count':count, 'users':user, 'cssClass':cssClass, } return JsonResponse(response) The condition: {% if i.like %} <button id="likeBtn{{ i.id }}" class="likeClassBtn"> <i class="fas fa-heart"></i> </button> {% else %} hello {% endif %} I wanna check the condition on the template Although my view just works perfectly fine. -
404 Not Found error on Django deployment with Apache2 Web Server
I rent a VPS and deployed my Django project to it. And placed my project under /var/www/html which is the accessible directory for Apache2. I get 404 Not Found error. I think apache2 is looking for HTML files under the directory but I look lots of tutorials to make this configuration true. Here is my configuration. <VirtualHost *:80> # The ServerName directive sets the request scheme, hostname and port that # the server uses to identify itself. This is used when creating # redirection URLs. In the context of virtual hosts, the ServerName # specifies what hostname must appear in the request's Host: header to # match this virtual host. For the default virtual host (this file) this # value is not decisive as it is used as a last resort host regardless. # However, you must set it for any further virtual host explicitly. #ServerName www.example.com ServerAdmin webmaster@localhost DocumentRoot /var/www/html/SistemDedektifi/SistemDedektifi # Available loglevels: trace8, ..., trace1, debug, info, notice, warn, # error, crit, alert, emerg. # It is also possible to configure the loglevel for particular # modules, e.g. #LogLevel info ssl:warn ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined # For most configuration files from conf-available/, which are # enabled or … -
How to pass multiple attributes in error logs as a simple parameter in django?
class Request(APIView): @api_view(['GET']) def test_api_method(self): print('This is Test API') db_logger = logging.getLogger('db') try: 1 / 0 except Exception as e: db_logger.exception(e, extra={'user': self.user.username, 'class_name': self.__class__.__name__,'method_name':sys._getframe().f_code.co_name, 'module_name':__package__,'ip_address': socket.gethostbyname(socket.gethostname())}) return Response({'data': True}, status=status.HTTP_200_OK) I have given multiple attributes inside extra={......}. This has become quite lengthy. How to give this as a single parameter, so that I can use that parameter in other classes and methods for logging? -
Stuck at Could not build wheels for cryptography which use PEP 517 and cannot be installed directly
Upgraded pip command still having this message. I am trying to install django-allauth. The following error is generated while using pip install django-allauth (venv) C:\Users\Tubai\PycharmProjects\food>pip install django-allauth Collecting django-allauth Using cached https://files.pythonhosted.org/packages/70/8c/18e9fd164b0e1e578995cf916da49a074b22a629a71c6017455d1ba151e1/django-allauth-0.44.0.tar.gz Requirement already satisfied: Django>=2.0 in c:\users\tubai\documents\pycharmprojects\ldjangocrash\venv\lib\site-packages (from django-allauth) (3.1.7) Collecting python3-openid>=3.0.8 (from django-allauth) Using cached https://files.pythonhosted.org/packages/e0/a5/c6ba13860bdf5525f1ab01e01cc667578d6f1efc8a1dba355700fb04c29b/python3_openid-3.2.0-py3-none-any.whl Collecting requests-oauthlib>=0.3.0 (from django-allauth) Using cached https://files.pythonhosted.org/packages/a3/12/b92740d845ab62ea4edf04d2f4164d82532b5a0b03836d4d4e71c6f3d379/requests_oauthlib-1.3.0-py2.py3-none-any.whl Collecting requests (from django-allauth) Using cached https://files.pythonhosted.org/packages/29/c1/24814557f1d22c56d50280771a17307e6bf87b70727d975fd6b2ce6b014a/requests-2.25.1-py2.py3-none-any.whl Collecting pyjwt[crypto]>=1.7 (from django-allauth) Using cached https://files.pythonhosted.org/packages/3f/32/d5d3cab27fee7f6b22d7cd7507547ae45d52e26030fa77d1f83d0526c6e5/PyJWT-2.1.0-py3-none-any.whl Requirement already satisfied: asgiref<4,>=3.2.10 in c:\users\tubai\documents\pycharmprojects\ldjangocrash\venv\lib\site-packages (from Django>=2.0->django-allauth) (3.3.1) Requirement already satisfied: pytz in c:\users\tubai\documents\pycharmprojects\ldjangocrash\venv\lib\site-packages (from Django>=2.0->django-allauth) (2021.1) Requirement already satisfied: sqlparse>=0.2.2 in c:\users\tubai\documents\pycharmprojects\ldjangocrash\venv\lib\site-packages (from Django>=2.0->django-allauth) (0.4.1) Collecting defusedxml (from python3-openid>=3.0.8->django-allauth) Using cached https://files.pythonhosted.org/packages/07/6c/aa3f2f849e01cb6a001cd8554a88d4c77c5c1a31c95bdf1cf9301e6d9ef4/defusedxml-0.7.1-py2.py3-none-any.whl Collecting oauthlib>=3.0.0 (from requests-oauthlib>=0.3.0->django-allauth) Using cached https://files.pythonhosted.org/packages/05/57/ce2e7a8fa7c0afb54a0581b14a65b56e62b5759dbc98e80627142b8a3704/oauthlib-3.1.0-py2.py3-none-any.whl Collecting chardet<5,>=3.0.2 (from requests->django-allauth) Using cached https://files.pythonhosted.org/packages/19/c7/fa589626997dd07bd87d9269342ccb74b1720384a4d739a1872bd84fbe68/chardet-4.0.0-py2.py3-none-any.whl Collecting urllib3<1.27,>=1.21.1 (from requests->django-allauth) Using cached https://files.pythonhosted.org/packages/0c/cd/1e2ec680ec7b09846dc6e605f5a7709dfb9d7128e51a026e7154e18a234e/urllib3-1.26.5-py2.py3-none-any.whl Collecting certifi>=2017.4.17 (from requests->django-allauth) Using cached https://files.pythonhosted.org/packages/5e/a0/5f06e1e1d463903cf0c0eebeb751791119ed7a4b3737fdc9a77f1cdfb51f/certifi-2020.12.5-py2.py3-none-any.whl Collecting idna<3,>=2.5 (from requests->django-allauth) Using cached https://files.pythonhosted.org/packages/a2/38/928ddce2273eaa564f6f50de919327bf3a00f091b5baba8dfa9460f3a8a8/idna-2.10-py2.py3-none-any.whl Collecting cryptography<4.0.0,>=3.3.1; extra == "crypto" (from pyjwt[crypto]>=1.7->django-allauth) Using cached https://files.pythonhosted.org/packages/9b/77/461087a514d2e8ece1c975d8216bc03f7048e6090c5166bc34115afdaa53/cryptography-3.4.7.tar.gz Installing build dependencies ... done Getting requirements to build wheel ... done Preparing wheel metadata ... done Collecting cffi>=1.12 (from cryptography<4.0.0,>=3.3.1; extra == "crypto"->pyjwt[crypto]>=1.7->django-allauth) Using cached https://files.pythonhosted.org/packages/c6/92/9188a1dff4934d0bd18df7f92dc481324b3342814cea34849b393ea2d232/cffi-1.14.5-cp37-cp37m-win_amd64.whl Collecting pycparser (from cffi>=1.12->cryptography<4.0.0,>=3.3.1; extra == "crypto"->pyjwt[crypto]>=1.7->django-allauth) Using cached https://files.pythonhosted.org/packages/ae/e7/d9c3a176ca4b02024debf82342dab36efadfc5776f9c8db077e8f6e71821/pycparser-2.20-py2.py3-none-any.whl Building wheels for collected packages: cryptography Building wheel for cryptography (PEP 517) ... error Complete … -
Django all-auth Slack: Redirect URL as https instead of http and Social Network Login Failure
Hi I am using django all-auth with Slack. However, I have 2 problems. 1st: the redirect URL always goes to HTTP instead of HTTPS. E.g. I click on ***.ngrok.io/accounts/slack/login and then get redirected to https://***.slack.com/oauth?client_id=1737791866593.2107881969061&scope=identify&user_scope=&redirect_uri=http%3A%2F%2F***.ngrok.io%2Faccounts%2Fslack%2Flogin%2Fcallback%2F&state=ANmZKE1CMWq7&granular_bot_scope=0&single_channel=0&install_redirect=&tracked=1&response_type=code&team= as you can see the redirect_uri is HTTP. How can I change this in django all-auth? 2nd: After manually changing it I am still not able to login as I get the error below (see picture): e.g. https://django-allauth.readthedocs.io/en/latest/providers.html#slack -
Django: "AttributeError: type object 'AutoField' has no attribute 'rsplit'" after adding "DEFAULT_AUTO_FIELD" to settings.py
I just updated my Django project from 3.1.6 to 3.2.3. After running python manage.py runserver, the server ran with these warnings: core.CoreUser: (models.W042) Auto-created primary key used when not defining a primary key type, by default 'django.db.models.AutoField'. HINT: Configure the DEFAULT_AUTO_FIELD setting or the CoreConfig.default_auto_field attribute to point to a subclass of AutoField, e.g. 'django.db.models.BigAutoField'. Then I remembered that I need to add a DEFAULT_AUTO_FIELD setting to settings.py after updating a project to Django from version < 3.2 to version >= 3.2, so I did: # settings.py DEFAULT_AUTO_FIELD = django.db.models.AutoField Then I tried python manage.py runserver again, but this time I got a different warning: (venv) C:\Users\Chris\my_project>python manage.py runserver Traceback (most recent call last): ... (truncated for brevity) File "C:\Users\Chris\my_project\venv\lib\site-packages\django\utils\module_loading.py", line 13, in import_string module_path, class_name = dotted_path.rsplit('.', 1) AttributeError: type object 'AutoField' has no attribute 'rsplit' I thought that something about my migrations or database was causing the issue, so I deleted db.sqlite3 and all of the app's migrations. Then I ran a fresh python manage.py makemigrations, except that caused the same error: AttributeError: type object 'AutoField' has no attribute 'rsplit' Any ideas why this might be happening? -
DJANGO Paginated ajax results not working
I have a table for tracking job applications and im trying to implement a filter feature. I want to display the results with pagination. However, I am getting errors when trying to do so and can't seem to find my way out of it. Would be glad if someone can help Thank youu Here is my code: template file <ul id="filter_list" class="dropdown-menu"> <li><a href="#">Alphabetical Order (A-Z)</a></li> <li><a href="#">Application Date (Ascending)</a></li> <li><a href="#">Application Date (Descending)</a></li> <li><a href="#">Closing Date</a></li> </ul> <div id="table_results"> <div> <script> $(".dropdown-menu a").click(function(){ var selected_filter = $(this).text(); $.ajax({ url:'{% url "stu_filter_applications" %}', data:{ "filter_category": selected_filter, }, dataType:'json', success: function (response) { $("#table_results").html(''); #to test if its working }, error: function (response) { console.log(response.errors); }, }); }); </script> views.py: def stu_filter_applications(request): if request.is_ajax(): filter_cat = request.GET.get("filter_category", None) student = StudentUser.objects.get(user=request.user) int_apps = InternshipApplication.objects.filter(student=student) int_app = [] applications = [] for app in int_apps: #for each application, grab the internship and the recruiter if filter_cat == "Alphabetical Order (A-Z)": internship = Internship.objects.get(id=app.internship.id) int_applications = InternshipApplication.objects.filter(student=student).values(). order_by('internship.internship_title') if filter_cat == "Application Date (Ascending)": internship = Internship.objects.get(id=app.internship.id) int_applications = InternshipApplication.objects.filter(student=student).values(). order_by('application_date') if filter_cat == "Application Date (Descending)": internship = Internship.objects.get(id=app.internship.id) int_applications = InternshipApplication.objects.filter(student=student).values(). order_by('-application_date') recruiter = Recruiter.objects.get(id=internship.recruiter.id) int_app.append((internship,recruiter,int_applications)) applications = int_app.copy() paginator = … -
PDF output using django-weasyprint not using css files
I am trying to output PDF using the django-weasyprint package. When opening my detail view, I manage to create the html I wanted. When I want to download it, it looks like messy and doesn`t match the html file. Here is my views file. How can I add a css file to the DownloadPDF function. views.py class InvoiceView(DetailView): # vanilla Django DetailView model = Invoice template_name = 'accounting/invoices/invoice_pdf.html' class CustomWeasyTemplateResponse(WeasyTemplateResponse): # customized response class to change the default URL fetcher def get_url_fetcher(self): # disable host and certificate check context = ssl.create_default_context() context.check_hostname = False context.verify_mode = ssl.CERT_NONE return functools.partial(django_url_fetcher, ssl_context=context) class InvoicePrintView(WeasyTemplateResponseMixin, InvoiceView): # output of MyModelView rendered as PDF with hardcoded CSS pdf_stylesheets = [ settings.STATIC_URL + 'core/static/assets/css/pages/invoice.css', ] # show pdf in-line (default: True, show download dialog) pdf_attachment = False # custom response class to configure url-fetcher response_class = CustomWeasyTemplateResponse class InvoiceDownloadView(WeasyTemplateResponseMixin, InvoiceView): # suggested filename (is required for attachment/download!) pdf_filename = 'invoice.pdf' class InvoiceImageView(WeasyTemplateResponseMixin, InvoiceView): # generate a PNG image instead content_type = CONTENT_TYPE_PNG # dynamically generate filename def get_pdf_filename(self): return 'foo-{at}.pdf'.format( at=timezone.now().strftime('%Y%m%d-%H%M'), ) Many Thanks, -
I'm facing some problem in this code. I want to access the value of time1 in variable t but i don't know how?
def python_view(request): global time1 time1=datetime.datetime.now() mcq=Pythonmcq.objects.all() paginator=Paginator(mcq,1) page_number=request.GET.get('page') try: mcq=paginator.page(page_number) except PageNotAnInteger: mcq=paginator.page(1) except EmptyPage: mcq=paginator.page(page.num_pages) return render(request,'testApp/pythonexam.html',{'mcq':mcq,'time1':time1}) def result_view(request): t=python_view(time1) return render(request, 'testApp/result.html',{'time':t}) -
Passing JsonResponse data (from Django views) as a url parameter in Javascript is not working
I am making a website in django that has paypal client side payment integration. My payment works fine but after payment is completed, i send the delivery data to a django views function using fetch API and views function returns me a JsonResponse. I am trying to pass data from that response as a url parameter to another django view which will render a success page about the order with a few details in it. The problem I encounter is as follows: NoReverseMatch at /product-details/payment Reverse for 'order_successful' with keyword arguments '{'DATA': ''}' not found. 1 pattern(s) tried: ['order_successful/(?P[^/]+)$'] here is code for checkout.html which is calling paymentComplete.views <script> function completeOrder(){ var url = "{% url 'paymentComplete' %}" fetch(url, { method: 'POST', headers:{ 'Content-type': 'application/json', 'X-CSRFToken': csrftoken, }, body:JSON.stringify({'prodID': prodId, 'quantity': quantityBought, 'bill': total, 'fName': fName, 'lName': lName, 'apt': apt, 'street': street, 'city': city, 'state': state, 'zipcode': zipcode, 'country': country, 'email': email, 'phone': phone}) }) .then(response => response.json()) .then((data) => { console.log('Success ', data); console.log(typeof data); alert('Transaction Completed'); window.location.href = "{% url 'order_successful' DATA=data %}" }) } </script> following is code for paymentComplete.views def paymentComplete(request): body = json.loads(request.body) prod_ID = int(body['prodID']) prod_Qt_bought = int(body['quantity']) bill_paid = str(body['bill']) #loading product from … -
django templates {{form.errors}} not showing
I have a problem my website. Please help me. This is my template folder. {% extends "layout.html" %} {% block head %} <title>Login</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.1/css/all.css" integrity="sha384-gfdkjb5BdAXd+lj+gudLWI+BXq4IuLW5IT+brZEZsLFm++aCMlF1V92rMkPaX4PP" crossorigin="anonymous"> <style> body, html { margin: 0; padding: 0; height: 100%; background: #7abecc !important; } .user_card { width: 350px; margin-top: auto; margin-bottom: auto; background: #74cfbf; position: relative; display: flex; justify-content: center; flex-direction: column; padding: 10px; box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19); -webkit-box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19); -moz-box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19); border-radius: 5px; } .form_container { margin-top: 20px; } #form-title{ color: #fff; } .login_btn { width: 100%; background: #33ccff !important; color: white !important; } .login_btn:focus { box-shadow: none !important; outline: 0px !important; } .login_container { padding: 0 2rem; } .input-group-text { background: #f7ba5b !important; color: white !important; border: 0 !important; border-radius: 0.25rem 0 0 0.25rem !important; } .input_user, .input_pass:focus { box-shadow: none !important; outline: 0px !important; } </style> {% endblock %} {% block body %} <div class="container h-100"> <div class="d-flex justify-content-center … -
Problem with decimal field in django v3.2
After upgrading from version 3.1 to version 3.2, I found precision problem in using decimal field. Following example is a small code which could regenerate problem. from django.db import models class Foo(models.Model): amount = models.DecimalField( null=False, decimal_places=18, max_digits=44) # A simple insertion example from api.models import Foo from django.db.models import F from decimal import Decimal f = Foo.objects.create(amount=Decimal('0.5')) f.amount = F('amount') - Decimal('0.4') f.save(update_fields=['amount', ]) f.refresh_from_db() print(f.amount) This code generates 0.099999999999999980 but same code in previous version generate expected result 0.01. By checking mysql query generated for update query, I found that in new version number has sent using a quotation but in previous one there were no quotation. i.e in new version we have something like this UPDATE `api_foo` SET `amount` = (`api_foo`.`amount` - '0.4') WHERE `api_foo`.`id` = 1 but in previous one we had UPDATE `api_foo` SET `amount` = (`api_foo`.`amount` - 0.4) WHERE `api_foo`.`id` = 1. Also I must mention that this happens just in mysql driver not in sqllite. I know this seems like a bug, but I guessed that I am missing something trivial. I am using mysql-8.0.19 and I got the same value in versions 3.2 and 3.2.3 of django.