Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
AttributeError: module 'lib' has no attribute 'OpenSSL_add_all_algorithms'
I have been getting this error anytime i run my project with (runserver_plus --cert-file cert.crt)...I already installed the django extensions and pyOpenSSL I tried running without the (--cert-file cert.crt), that one seems to work fine buh doesnt provide me with what I am looking for . -
Is saving the user object to sessions safe to do when logging them in?
I am writing my own 2FA functionality (I know that django-otp and django-two-factor-auth exist, this is just for fun). Everything is fine except for the log in view. I know that you can use the following to authenticate the user: user = authenticate(request, username=cd['username'],password=cd['password']) login(request, user) What I want to do though is pass the user variable into the .view function that I will be using to do the 2FA on. That way, once the user enters their totp, I can use the already authenticated user as the user in the login function. Everything is fine other than on how to pass this data along. Is it safe security wise to pass the user along via sessions? I would do: request.session['authenticate_user'] = user And in the 2FA view put the following to retrieve the user: user = request.session.get('authenticate_user', None) I know that passing the password along is not safe, even if it is encrypted. Is the way I am proposing alright to do though? If not, what should you do instead? I have contemplated posting the password and user to the view using the requests module. Would this be security safe as an alternative, assuming it is not safe to … -
Merging Paginator and export html to xlsx and large amount of data
I'm trying to create a way to export the HTML table to xlsx, but I have a large amount of data in the queries. So I need to use pagination with Paginator so the browser doesn't load the data all at once and end up causing TimeOut. But when applying the Paginator and exporting, it only exports what is on the current page. Any suggestions to improve this code, such as creating a loop so that it can export all pages? View function: def export_project_data(request, pk): if str(request.user) != 'AnonymousUser': # só vai ter acesso se for diferente de AnonymousUser individuals_list = Individual.objects.filter(Project=pk) traps = Sample_unit_trap.objects.filter(Project=pk) page = request.GET.get('page', 1) paginator = Paginator(individuals_list, 1000) try: individuals = paginator.page(page) except PageNotAnInteger: individuals = paginator.page(1) except EmptyPage: individuals = paginator.page(paginator.num_pages) path_info = request.META['PATH_INFO'] context = { 'individuals': individuals, 'pk': pk, 'traps': traps, 'header': 'export_project_data', 'path_info': path_info } return render(request, 'inv/index.html', context) HTML paginator code: <div class="table-div"> {% if individuals.has_other_pages %} <ul class="pagination pagination-sm"> {% if individuals.has_previous %} <li><a href="?page={{ individuals.previous_page_number }}">&laquo;</a></li> {% else %} <li class="disabled"><span>&laquo;</span></li> {% endif %} {% for i in individuals.paginator.page_range %} {% if individuals.number == i %} <li class="active"><span>{{ i }} <span class="sr-only">(current)</span></span></li> {% else %} <li><a href="?page={{ … -
Highcharts. Django won't load. Highcharts with Django
There is a wonderful library of js - Highcharts. I'm trying to link it to Django, and everything actually works, but not when I'm trying to insert a variable with content into data. Here's the code. This function returns what I substitute in data in Highcharts. def get_series(context): data_ser = [] for i in context: if i in ['One', "Two", "Three", "Four", "Five"]: data_ser.append({ 'name': i, 'y': context[i], 'z': 22.2 }) data_ser = json.dumps(data_ser) return data_ser And this is the jquery code itself <script> $(document).ready(function () { var data_ser = '{{ data_ser|safe }}' console.log(data_ser) Highcharts.chart('container', { chart: { type: 'variablepie' }, title: { text: 'Stats' }, series: [{ minPointSize: 10, innerSize: '20%', zMin: 0, name: 'countries', data: data_ser }] }); }) </script> In series in data, I try to substitute data_ser, but the graph is not output. Although, if you write it manually, then everything will work. Similar code works: `<script> $(document).ready(function () { var data_ser = '{{ data_ser|safe }}' console.log(data_ser) Highcharts.chart('container', { chart: { type: 'variablepie' }, title: { text: 'Stats' }, series: [{ minPointSize: 10, innerSize: '20%', zMin: 0, name: 'countries', data: [ { "name": "One", "y": 50.0, "z": 22.2 }] }] }); }) </script>` I really hope … -
I want to implement the dj-rest-auth Google OAuth feature, but I cannot understand where to get code to access google endpoints
I cannot understand where to get code or acsess_token to login user with google. I cannot find the endpoint to which I should send a request to get a code as a response. And I somewhat confused how to implement dg-rest-auth SocialAuth feature( I want my app to be able to login users with github, facebook and google). I have found these endpoint for Google OAuth2 https://accounts.google.com/o/oauth2/v2/auth?redirect_uri=http://127.0.0.1:8001/ &prompt=consent&response_type=code&client_id=364189943403-pguvlcnjp1kd9p8s1n5kruhboa3sj8fq.apps.googleusercontent.com &scope=openid%20%20profile&access_type=offline Implicit Grant https://accounts.google.com/o/oauth2/v2/auth?redirect_uri=http://127.0.0.1:8001/ &prompt=consent&response_type=code&client_id=364189943403-pguvlcnjp1kd9p8s1n5kruhboa3sj8fq.apps.googleusercontent.com &scope=openid%20%20profile Could you guys analyse my code and tell me what's wrong or what needs to be improved, please? And can you please provide me with a link to proper Google and Facebook Docs for OAuth2? settings.py Django settings for resume_website_restapi project. Generated by 'django-admin startproject' using Django 4.1.3. For more information on this file, see https://docs.djangoproject.com/en/4.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.1/ref/settings/ """ from pathlib import Path import os from datetime import timedelta # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-b#t)ywiymb&@+mv^%j$p&4*y)iq2z-1da*z@beo4s-6-qu9ba%' # SECURITY WARNING: don't run with debug turned on … -
In django, how do you code this type of relationship model?
here's my code: from django.db import models class Parent(models.Model): name = models.CharField(max_length=50, unique=True) def __str__(self): return str(self.name) class Child(models.Model): parent = models.ForeignKey(Parent, on_delete=models.CASCADE) name = models.CharField(max_length=50, unique=True) def __str__(self): return str(self.name) Parents in my database: Rogan Smith Doe In admin dashboard: First, I create a child that has a name of John and his parent is Smith.. it works! Now, after that, whenever I create a child that also has a name of John and this time with a parent of Doe or Rogan, it says: "Child with this Name already exists." here I tried searching on google but I can't seem to find the answer. Not a native english speaker here, please bare with me. -
Not able to Sumit data from Vue Js to Django Rest
I built a web app with Vue js and Django, django rest framework , I am only able to post data from the backend. When I try and fill in the data from the form with vue js nothing posts. here is my code hope someone smart can solve this. Thank you for your help it is appreciated. I followed the tutorial from: https://blog.logrocket.com/how-to-build-vue-js-app-django-rest-framework/ I attempted it twice there may be some code issues with her code. but I am open for anyone to help thank you. Tasks.vue <template> <div class="tasks_container"> <div class="add_task"> <form v-on:submit.prevent="submitForm"> <div class="form-group"> <label for="title">Title</label> <input type="text" class="form-control" id="title" v-model="title" /> </div> <div class="form-group"> <label for="description">Description</label> <textarea class="form-control" id="description" v-model="description" ></textarea> </div> <div class="form-group"> <button type="submit">Add Task</button> </div> </form> </div> <div class="tasks_content"> <h1>Tasks</h1> <ul class="tasks_list"> <li v-for="task in tasks" :key="task.id"> <h2>{{ task.title }}</h2> <p>{{ task.description }}</p> <button @click="toggleTask(task)"> {{ task.completed ? "Undo" : "Complete" }} </button> <button @click="deleteTask(task)">Delete</button> </li> </ul> </div> </div> </template> <script> export default { data() { return { tasks: [], title: "", description: "", }; }, methods: { async getData() { try { // fetch tasks const response = await this.$http.get( "http://localhost:8000/api/tasks/" ); // set the data returned as tasks this.tasks = response.data; … -
Django Aggregation on date field
Hi I have two following models class Store(models.Model): store_name = models.CharField(max_length=100) class Meta: db_table = 'stores' class Sales(models.Model): store = models.ForeignKey(Store, on_delete=models.CASCADE, related_field='sales') product_id = models.BigInteger() sale_date = models.DateTimeField() total_mrp = models.FloatField() I am trying to fetch sum(total_mrp) of each store day wise but seem to unable to group by date col in my Sales Table I am using django_rest_framework I tried to do above using following serializers class SalesSerializer(serializers.RelatedField): queryset = Sales.objects.all() def to_representation(self, value): data = self.queryset.annotate(day=functions.ExtractWeekDay('sale_date'), total_sale=Sum('total_mrp')) return data.values('day', 'total_mrp') class StoreSerializer(serializers.ModelSerializer): primary_sales = SalesSerializer(many=False) class Meta: model = Store exclude = ['id'] The output result doesn't get grouped as I expect. Instead I get same data for primary sales for each store. -
Django - Pass Form data in URL
I want to pass the forms data to another view (if possibleby GET params) def post(self, request): form = SomeForm(request.POST) if form.is_valid(): response = HttpResponse(reverse('page_to_go')) How can I accomplish that? -
Android app problem: UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 207: invalid start byte
So I have two ubuntu servers stage and dev, and one single API for android, IOS and web front on reactjs. I get this error when I try to upload a photo to my server from ANDROID app, basically I can upload the same photo to DEV server from Postman and IOS, but I keep getting this error when I try uploading from android. But from the same android app I can upload this exact photo to stage server and prod server, so basically nothing wrong with android app, but something is wrong on the server, even tho it correctly works with IOS and postman and web app. I believe that the code and settings are almost the same on both servers, so I have no idea where is the problem... Traceback (most recent call last): File "/home/project/.local/share/virtualenvs/blabla_backend-B039YcMy/lib/python3.10/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/project/blabla_backend/dating/middleware.py", line 144, in call body_repl = str(request.body, 'utf-8').replace('\n', '') if request.body else 'null' UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 207: invalid start byte Uploading a photo from android just like from other apps, but it just dissapears and I get this error in django logs. But still same android app … -
Setting permissions by group in Django
I am working with a Django project that requires user, group, and permission management to be done only through the admin panel. So I used Django's user system and created a login with this view.py # Django from django.contrib.auth import authenticate, login, logout from django.shortcuts import render, redirect from django.contrib import messages def LoginView(request): """ Login Se utiliza el modulo de usuarios de Django """ template_name = "login.html" if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request, username=username, password=password) if user is not None: login(request, user) if request.user.groups.filter(name="administradores").exists(): return redirect('inicio') else: return redirect('listarS') else: messages.error(request, 'Error en el ingreso') else: messages.error(request, 'Error en CUIT o contraseña') context = {} return render(request, 'login.html', context) def LogoutView(request): """ Logout de Django """ template_name = "login.html" context = {} logout(request) return redirect(request, 'login.html', context) Groups are administradores and operadores. Users from operadores group only have permissions on specific model group permissions But when I add a user to this group: user group When logging in, this user can do anything (add, modify, delete or list) in any model of the application. How should I do so that the users of the operadores group only have the permissions of that … -
Adding values to cells in a specific column in HTML
I am creating a very basic table in HTML for my Django project. I got some help from Here to learn how to pass a list from my Django app to my HTML and generate rows for my values. My question this time is: how can I target the second, third, or any particular column for my list? For example, suppose I have a list of values and want to add all of them to Column 3 of my table. Here is the code I tried to use where i wanted to have {{ name }} values added to column two, but it keeps adding the cells to the first column <html> <body> <table border="1" cellpadding = "5" cellspacing="5"> <tr> <th> IDs </th> <th> Names </th> <th> Heights </th> </tr> {% for id in myIDs %} <tr> <td>{{ id }}</td> </tr> {% endfor %} <tr> {% for name in myNames %} <td> <tr> <td>{{ name }}</td> </tr> </td> {% endfor %} </tr> </table> </body> </html> -
image post feed with django does not display images
Currently working on a very simple social media and since yesterday the images in the post feed either disappear or i get a value error: ValueError at / The 'image' attribute has no file associated with it. Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 3.2.16 Exception Type: ValueError Exception Value: The 'image' attribute has no file associated with it. Exception Location: C:\Users\Render_2\PycharmProjects\djangoProject\venv\lib\site-packages\django\db\models\fields\files.py, line 40, in _require_file Python Executable: C:\Users\Render_2\PycharmProjects\djangoProject\venv\Scripts\python.exe Python Version: 3.7.3 Python Path: ['C:\Users\Render_2\PycharmProjects\djangoProject', 'C:\Users\Render_2\AppData\Local\Programs\Python\Python37-32\python37.zip', 'C:\Users\Render_2\AppData\Local\Programs\Python\Python37-32\DLLs', 'C:\Users\Render_2\AppData\Local\Programs\Python\Python37-32\lib', 'C:\Users\Render_2\AppData\Local\Programs\Python\Python37-32', 'C:\Users\Render_2\PycharmProjects\djangoProject\venv', 'C:\Users\Render_2\PycharmProjects\djangoProject\venv\lib\site-packages'] Server time: Thu, 05 Jan 2023 12:14:48 +0000 I have honestly no idea why it is messed up now, since it was running just fine yesterday morning. Please help me out to understand this issue. Here is the rest of the code. the index.html: {% for post in posts reversed %} <div class="bg-white shadow rounded-md -mx-2 lg:mx-0"> <!-- post header--> <div class="flex justify-between items-center px-4 py-3"> <div class="flex flex-1 items-center space-x-4"> <a href="#"> <div class="bg-gradient-to-tr from-yellow-600 to-pink-600 p-0.5 rounded-full"> <img src="{% static 'assets/images/avatars/user.png' %}" class="bg-gray-200 border border-white rounded-full w-8 h-8"> </div> </a> <span class="block capitalize font-semibold "><a href="/profile/{{ post.user }}">@{{ post.user }} </a></span> </div> <div> <a href="#"> <i class="icon-feather-more-horizontal text-2xl hover:bg-gray-200 rounded-full p-2 transition -mr-1 "></i> </a> <div … -
TemplateSyntaxError Could not parse the remainder: '"{%' from '"{%'
I have TemplateSyntaxError Could not parse the remainder: '"{%' from '"{%' and I don't know how to write the code in a different way. I tried JS but it also didn't work. <ul> {% for key1, value1 in menu.items %} <li><a href="{% url key1.slug %}" {% if request.path == "{% url key1.slug %}" %} class="active" {% endif %}>{{ key1 }}</a></li> {% endfor %} </ul> Highlighted in TemplateSyntaxError: {% if request.path == "{% url key1.slug %} jQuery(function($) { var path = window.location.href; $('a').each(function() { if (this.href === path) { $(this).addClass('active'); } }); }); -
Django q process does not get cleared from memory
I have integrated Django Q in my project and i'm running a task from django q but after task ran successfully i can still see the process is in memory is there any way to clear the process from memory after it has finished the job. Here is the django q settings Q_CLUSTER = { 'name': 'my_app', 'workers': 8, 'recycle': 500, 'compress': True, 'save_limit': 250, 'queue_limit': 500, 'cpu_affinity': 1, 'label': 'Django Q', 'max_attempts': 1, 'attempt_count': 1, 'catch_up': False, 'redis': { 'host': '127.0.0.1', 'port': 6379, 'db': 0, }} -
Sum and Annotate does not returns a decimal field Sum as a decimal
I am writing a query in which I want to Sum amount using annotate and Sum decimal field in a foreign key relationship. The field is summed correctly but it returns the Sum field in integer instead of decimal. In the database the field is in decimal format. The query is like... **models.objects.filter(SourceDeletedFlat=False).annotate(TotalAmount=Sum("RequestOrderList__PurchaseOrderAmount")).all(). I do not want to use aggregate because I don't need overall column sum. -
How do I format a nested python dictionary and write it to a json file?
I am looking to run a calculation in my Django view and then write it to a json file. However I am struggling to get the formatting right. I need the output json file to look something like this: { "dates": { "year": { "total": 1586266, "upDown": 9.8, "data": { "labels": ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], "income": [2000, 4000, 6000, 8000, 10000, 12000, 14000, 16000, 18000, 20000, 22000, 24000], "expenses": [6000, 12000, 18000, 24000, 30000, 36000, 42000, 48000, 54000, 60000, 66000, 72000] } } } } Here is what I have in my view: def generateGraph(): income = [{'income':['2000','2000','2000','2000','2000','2000','2000','2000','2000','2000','2000','2000']}] expenses = [{'expenses':['1000','1000','1000','1000','1000','1000','1000','1000','1000','1000','1000','1000']}] labels = [{'labels':['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']}] total = 1586266 upDown = 9.8 data = [labels, income, expenses] year = [total,upDown,data] dates = [year] with open( "static/graph.json") as f:json.dump(dates, f) return HttpResponse(open("static/graph.json", 'r'), content_type = 'application/json; charset=utf8') However, the output I currently get in my json file is: [[1586266, 9.8, [[{"labels": ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]}], [{"income": ["2000", "2000", "2000", "2000", "2000", "2000", "2000", "2000", "2000", "2000", "2000", "2000"]}], [{"expenses": ["1000", "1000", "1000", "1000", "1000", "1000", "1000", "1000", "1000", "1000", "1000", "1000"]}]]]] Thanks! -
django html5 video plugin doesn't show in editor
i copied html5video in plugins folder and write 'html5video' in settings.py . video uploading icon doesn't show in editor, how can i fix this problem ? my configs ckeditor in settings.py : CKEDITOR_CONFIGS = { 'default': { 'skin': 'moono', # 'skin': 'office2013', 'toolbar_Basic': [ ['Source', '-', 'Bold', 'Italic'] ], 'toolbar_YourCustomToolbarConfig': [ {'name': 'document', 'items': ['Source', '-', 'Save', 'NewPage', 'Preview', 'Print', '-', 'Templates']}, {'name': 'clipboard', 'items': ['Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord', '-', 'Undo', 'Redo']}, {'name': 'editing', 'items': ['Find', 'Replace', '-', 'SelectAll']}, {'name': 'forms', 'items': ['Form', 'Checkbox', 'Radio', 'TextField', 'Textarea', 'Select', 'Button', 'ImageButton', 'HiddenField']}, '/', {'name': 'basicstyles', 'items': ['Bold', 'Italic', 'Underline', 'Strike', 'Subscript', 'Superscript', '-', 'RemoveFormat']}, {'name': 'paragraph', 'items': ['NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-', 'Blockquote', 'CreateDiv', '-', 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock', '-', 'BidiLtr', 'BidiRtl', 'Language']}, {'name': 'links', 'items': ['Link', 'Unlink', 'Anchor']}, {'name': 'insert', 'items': ['Image', 'Flash', 'Table', 'HorizontalRule', 'Smiley', 'SpecialChar', 'PageBreak', 'Iframe']}, '/', {'name': 'styles', 'items': ['Styles', 'Format', 'Font', 'FontSize']}, {'name': 'colors', 'items': ['TextColor', 'BGColor']}, {'name': 'tools', 'items': ['Maximize', 'ShowBlocks']}, {'name': 'about', 'items': ['About']}, '/', # put this to force next toolbar on new line {'name': 'yourcustomtools', 'items': [ # put the name of your editor.ui.addButton here 'Preview', 'Maximize', ]}, ], 'toolbar': 'YourCustomToolbarConfig', # put selected toolbar config here # 'toolbarGroups': … -
Django Rest Framework: Delete multiple Cookies with same name but different domain?
I have an application running on different shards and each shard has a different domain. I am setting that domain as a domain for our cookies for respective environments. And the problem I am facing is that sometimes cookies from previous sessions (might be from different environments) are present in the browser. So When I try to perform certain actions then a cookie from the different session is used and validation failed. So now I want to delete those cookies with the same name. What I am doing is response.delete_cookie('profileActionId') But after this the cookies was something like this: profileActionID: 'cookie_value' :: domain: 'usa.example.com/' profileActionID: '' :: domain: 'example.com/' So this doesn't delete cookies with the same name which have a different domain and I don't have a way to access that different domain from the code and also can't hardcode it as It will change according to different environments. Also I can't change the domain for cookies for different environments. So Is there a way in Django by which we can delete all cookies with the same name irrespective of there domains or paths? -
Do I need to use a inline formset? Or am I over complicating my models?
I’m trying to create an app that stores golf round scores. This will have things like the course being played, which tees being used, etc. what’s causing me problems is this could have 1-4 players. I would like to use 1 model for this, but I don’t think it would be possible because I need one instance of the course criteria, while 1-4 instances for the players. Am I overthinking my models? Or does this sound correct. Based on the models.py below I would do a inline formset with Golf_Round and Round_player` from django.db import models from django import template from django.urls import reverse from Courses.models import Golf_Course from accounts.models import Golfer from django.utils.timezone import now class Golf_Round(models.Model): Tee= models.ForeignKey(Golf_Tee, on_delete=models.CASCADE) round_create_date = models.DateTimeField(default=now()) is_active_round = models.BooleanField(default=False) def _str_(self): return "{}.{}.{}".format(self.round_create_date, self.course,self.pk) class Round_Player(models.Model): player = models.ForeignKey(Golfer, on_delete=models.CASCADE, default='Please_Select',blank=False) round = models.ForeignKey(Golf_Round, on_delete=models.CASCADE) hole_1_score = models.IntegerField() hole_2_score = models.IntegerField() hole_3_score = models.IntegerField() hole_4_score = models.IntegerField() hole_5_score = models.IntegerField() hole_6_score = models.IntegerField() hole_7_score = models.IntegerField() hole_8_score = models.IntegerField() hole_9_score = models.IntegerField() hole_10_score = models.IntegerField() hole_11_score = models.IntegerField() hole_12_score = models.IntegerField() hole_13_score = models.IntegerField() hole_14_score = models.IntegerField() hole_15_score = models.IntegerField() hole_16_score = models.IntegerField() hole_17_score = models.IntegerField() hole_18_score = models.IntegerField() create_date = models.DateTimeField(default=now()) … -
How can I put the elements of a form horizontally?
This is the layout and I would like the form elements to be horizontal instead of vertical This is my view code def requerimientos(request): form_procesos = forms.procesos form_impuesto = forms.impuestos return render(request, 'requerimientos.html',{"proceso" : form_procesos,"impuesto" : form_impuesto,"value": 2}) This is my HTML code <div class="col-12 col-md-6 offset-md-3"> <div class="card"> <div class="card-body"> {% if value == 1 %} <h5 style="font-family: 'Ubuntu', sans-serif;">Proceso:</h5> <form action="{% url 'contacto' %}" method="POST"> {% csrf_token %} {% crispy proceso %} </form> {% else %} <h5 style="font-family: 'Ubuntu', sans-serif;">Proceso:</h5> <form action="{% url 'contacto' %}" method="POST"> {% csrf_token %} {% crispy proceso %} </form> <h5 style="font-family: 'Ubuntu', sans-serif;">Impuesto:</h5> <form action="{% url 'contacto' %}" method="POST"> {% csrf_token %} {% crispy impuesto %} </form> {% endif %} </div> </div> <!-- Boton de enviar --> <br> <div class="d-flex justify-content-end"> <button type="submit" class="btn btn-primary">Enviar</button> </div> </div> This is my form code from django.forms import ModelForm from django import forms from crispy_forms.helper import FormHelper, Layout class procesos(forms.Form): mora = forms.BooleanField(required=False) deuda_atrasada = forms.BooleanField(required=False) class impuestos(forms.Form): inmobiliario = forms.BooleanField(required=False) baldio = forms.BooleanField(required=False) rural = forms.BooleanField(required=False) edificado = forms.BooleanField(required=False) automotor = forms.BooleanField(required=False) embarcaciones = forms.BooleanField(required=False) complementario = forms.BooleanField(required=False) I have another question, I created two forms because I needed to describe what each element was, … -
html - Add bullet piont as place holder django forms
I am using django-forms to render out my signup page and i want to add a bullet point as placholder for password field by passing the &bull; character entity from the widgets in django-forms but it doesn't work. is how it is rendered out in browser. forms.py class Signup(forms.ModelForm): class Meta: model = User fields = ["username", "email", "password", "password2", "library_no", "first_name", "last_name",] help_texts = { "username":None, } labels = { } widgets = { "username": forms.TextInput(attrs={ "id":"input_46", "name":"q46_typeA46", "data-type":"input-textbox", "class":"form-textbox validate[required]", "size":"310", "data-component":"textbox", "aria-labelledby":"label_46", "placeholder":"180591001" }), "first_name":forms.TextInput(attrs={ "id":"first_4", "name":"q4_name[first]", "class":"form-textbox validate[required]", "autoComplete":"section-input_4 given-name", "data-component":"first", "aria-labelledby":"label_4 sublabel_4_first", "required":True, "placeholder":"Chinedu" }), "last_name":forms.TextInput(attrs={ "id":"last_4", "name":"q4_name[last]", "class":"form-textbox validate[required]", "autoComplete":"section-input_4 family-name", "data-component":"last", "aria-labelledby":"label_4 sublabel_4_last", "required":True, "placeholder":"Oladapo Dikko" }), "email":forms.EmailInput(attrs={ "id=":"input_10", "name":"q10_email10", "class":"form-textbox validate[required, Email]", "placeholder":"ex: myname@example.com", "data-component":"email", "aria-labelledby":"label_10 sublabel_input_10", "required":True }), "password": forms.PasswordInput(attrs={ "id":"first_50", "name":"q50_name50[first]", "class":"form-textbox", "autoComplete":"section-input_50 given-name", "data-component":"first", "aria-labelledby":"label_50 sublabel_50_first", "required":True, "placeholder":"&bull;&bull;" }), "password2": forms.PasswordInput(attrs={ "id":"last_50", "name":"q50_name50[last]", "class":"form-textbox", "autoComplete":"section-input_50 family-name", "data-component":"last", "aria-labelledby":"label_50 sublabel_50_last", "required": False }), "library_no": forms.TextInput(attrs={"required": False}), } signup.html <!DOCTYPE html> <html class="supernova"> <head> <title>SignUp</title> <style type="text/css">@media print{.form-section{display:inline!important}.form-pagebreak{display:none!important}.form-section-closed{height:auto!important}.page-section{position:initial!important}}</style> <link rel="stylesheet" href="/static/signup/css/style.css"> <link rel="stylesheet" href="/static/signup/css/main.css"> </head> <body> <form class="jotform-form" action="/signup/" method="post" name="form_230023299150548" id="230023299150548" accept-charset="utf-8" autocomplete="on"> {%csrf_token%} <div role="main" class="form-all"> <style> .form-all:before { background: none; } </style> <ul class="form-section page-section"> <li id="cid_28" class="form-input-wide" … -
Can I return multiple values from a SerializerMethodField? I am getting an error telling me I can't. How do I then get the values?
I have a post model that represents a normal post with images and possibly a video. I have a post reply model that represents comments or replies to a post. Here is the models.py file: class Category(models.Model): name = models.CharField(max_length=100, verbose_name="name") slug = AutoSlugField(populate_from=["name"]) description = models.TextField(max_length=300) parent = models.ForeignKey( "self", on_delete=models.CASCADE, blank=True, null=True, related_name="children" ) created_at = models.DateTimeField(auto_now_add=True, verbose_name="created at") updated_at = models.DateTimeField(auto_now=True, verbose_name="updated at") class Meta: verbose_name = "category" verbose_name_plural = "categories" ordering = ["name"] db_table = "post_categories" def __str__(self): return self.name def get_absolute_url(self): return self.slug def video_directory_path(instance, filename): return "{0}/posts/videos/{1}".format(instance.user.id, filename) def post_directory_path(instance, filename): return "posts/{0}/images/{1}".format(instance.post.id, filename) def reply_directory_path(instance, filename): return "replies/{0}/images/{1}".format(instance.reply.id, filename) def reply_videos_directory_path(instance, filename): return "{0}/posts/{1}/replies/{2}/videos/{3}".format(instance.user.id, instance.post.id, instance.reply.id, filename) class Post(models.Model): EV = "Everybody" FO = "Followers" FR = "Friends" AUDIENCE = [ (EV, "Everybody"), (FO, "Followers"), (FR, "Friends"), ] category = models.ForeignKey(Category, on_delete=models.SET_DEFAULT, default=1) body = models.TextField("content", blank=True, null=True, max_length=5000) slug = AutoSlugField(populate_from=["category", "created_at"]) video = models.FileField(upload_to=video_directory_path, null=True, blank=True) can_view = models.CharField(max_length=10, choices=AUDIENCE, default=EV) can_comment = models.CharField(max_length=10, choices=AUDIENCE, default=EV) user = models.ForeignKey( User, on_delete=models.CASCADE, verbose_name="user", related_name="user" ) published = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: verbose_name = "post" verbose_name_plural = "posts" db_table = "posts" ordering = ["created_at"] def __str__(self): return self.body[0:30] … -
SRC link changed when trying to integrate paypal button on django website
I'm trying to add the paypal button to my django shopping site. I have used the code from the SDK and replaced the id: My code: Client ID being: AWeSepzeHNW8BHE8rWPVm6CTuAGKz7SS1WzpbqEOZvQw-s_6qwFg6lxCO9MSXPpcVheUBWRgNuW6yKol However i am receiving a 400 error. Also viewing the page source shows the src has changed: If you follow this link you get the following message: throw new Error("SDK Validation error: 'Invalid query value for client-id: AabgYuFGxyzy3AbeWLPa-EtEGGreyL9bDDbWOxH4zFbPbgNc7y5yMpNO7B2NMRxCvT7-Ysou8ZXDNycT¤cy=USD'" ); /* Original Error: Invalid query value for client-id: AabgYuFGxyzy3AbeWLPa-EtEGGreyL9bDDbWOxH4zFbPbgNc7y5yMpNO7B2NMRxCvT7-Ysou8ZXDNycT¤cy=USD (debug id: f3776258140b9) */ Anyone know why the src has been changed from the source to when its rendered by django? I have followed the original src link from paypal and this, however when the page renders the link is altered. -
How to Get same Connection id in django for every file
Every time I run my Django webservice the connection (django and MySQL connector) is same for every python function that I call but Connection_id from MySQL workbench is different for every python function. My temporary table keeps dropping from the DB which was created from a python function A and has to be accessed by another independent python function B at a later point of time from a different webservice. I guess the temporary table is being dropped as a result of new instances(connection_id) getting generated in the MySQL DB everytime I run a webservice to call my python functions. Example outputs of connections: Mysql Connection ID: 18423 django connection: <django.utils.connection.ConnectionProxy object at 0x00000203C0C84340> mysql connection: <mysql.connector.connection_cext.CMySQLConnection object at 0x00000203C1B7C070> Mysql Connection ID: 18424 django connection: <django.utils.connection.ConnectionProxy object at 0x00000203C0C84340> mysql connection: <mysql.connector.connection_cext.CMySQLConnection object at 0x00000203C1B7C070> Expectation Example outputs of connections: Mysql Connection ID: 18423 django connection: <django.utils.connection.ConnectionProxy object at 0x00000203C0C84340> mysql connection: <mysql.connector.connection_cext.CMySQLConnection object at 0x00000203C1B7C070> same nexttime Mysql Connection ID: 18423 django connection: <django.utils.connection.ConnectionProxy object at 0x00000203C0C84340> mysql connection: <mysql.connector.connection_cext.CMySQLConnection object at 0x00000203C1B7C070>