Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django-tinymce working with django-admin but not working in form template
in django admin django-tinymce is working but in template tinymce widget is not working. Please provide a solution django model my model.py class Question(models.Model): nameuser = models.ForeignKey(Profile,on_delete=models.CASCADE) title = models.CharField(max_length=200,blank=True,null=True) timestamp = models.DateTimeField(auto_now_add=True) contents = tinymce.HTMLField(blank=True,null=True) tags = models.ManyToManyField(Tags) id = models.UUIDField(default=uuid.uuid4, unique=True,primary_key=True,editable=False) form.py class QuestionForm(forms.ModelForm): class Meta: model = Question fields = ('title','contents','tags') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['title'].widget.attrs.update({'class': 'form-control','placeholder':'Enter Title'}) self.fields['tags'].widget.attrs.update({'class': 'form-control'}) in temlate it show only blank form-control template view -
Django admin: how to increase field label width in admin change form view?
I want to customize Django admin change_form.html template for some of my model. I would like to increase field label size and try by ovverriding change_form.html template. But it dosen't work. My own change_form.html is displayed but css style is not applied . When I open debug, an error is raised for change_form.js: django is not defined change_form.html {% extends "admin/change_form.html" %} {% load static %} {% block extrahead %} <!-- Custom --> <link rel="stylesheet" href="{% static 'ecrf/css/custom_change_form.css' %}"> {% endblock %} custom_change_form.css // pat is one of my field .column-pat { color: red !important; min-width: 200px; } admin.py class VisiteAdmin(SimpleHistoryAdmin): list_display = ('pat','vis_dat',timing_visit,'sai_log','sai_dat','ver','ver_usr','ver_dat') change_form_template = 'ecrf/admin/change_form.html' -
flutter web with django on diffrent host make error minifield:b6
hi guys i have one host my flutter web run on it and another one for django to send data to my flutter web after go to my website my site not show parametr just show this error minifield:b6 and in offline all works...like this: what can i do to solve this issue Doctor summary (to see all details, run flutter doctor -v): [√] Flutter (Channel beta, 2.9.0-0.1.pre, on Microsoft Windows [Version 10.0.19044.1586], locale en-US) [√] Android toolchain - develop for Android devices (Android SDK version 32.0.0) [√] Chrome - develop for the web [√] Android Studio (version 2020.3) [√] Connected device (2 available) • No issues found! [enter image description here][1] [1]: https://i.stack.imgur.com/Og2MG.jpg -
run django project without databasei,removed this code find some errors like this," settings.DATABASES is improperly configured."
DATABASES{ 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'xys', 'USER': 'postgres', 'PASSWORD': 'xyz', 'HOST': 'localhost', 'PORT': '5432', } No need of this code in django settings. My requirement in my project no need database in django settings -
How can i fix filter and pagination to work
I am trying to filter items based on prince range and then paginate the result. I have gone through the documentation but still doesnt work. i have tried all the logics i could come up with but not working still. Kindly help out if you know any means I can fix the error. The search shows the first page items but once i click on the subsequent pages, it doesnt display anything.If i use 'if request.Method==''POST:"',IT shows ,variable used before assignment. I aslo tried using 'if request.method =="GET" but it still didnt work. The search shows the first page items but once i click on the subsequent pages, it doesnt display anything.If i use 'if request.Method==''POST:"',IT shows ,variable used before assignment. I aslo tried using 'if request.method =="GET" but it still didnt work. Below is the code: # model.py class Property(models.Model): name =models.CharField(max_length=200) price = models.IntegerField(default=1000) bedroom = models.IntegerField(default=1) bathroom =models.IntegerField(default=1) status =models.CharField(max_length=200,blank=True,null=True) sqft =models.CharField(max_length=10,blank=True,null=True) acre =models.CharField(max_length=10,blank=True,null=True) Location = models.CharField(max_length=200,blank=True,null=True) describe =models.CharField(max_length=200,blank=True,null=True) img = CloudinaryField(blank=True,null=True) def __str__(self): return self.name class Meta: #db_table='accommodation' verbose_name_plural='Property' # view.py #i dont know if there's an error here because it doesnt show any result apart from the first page def availableProperty(request): #if request.method =="POST": name … -
Image sometimes does not display in HTML page (Django 3.0)
I created a somewhat clone of Instagram main page (for full transparency, please know that I do this for a psychological experiment). One of my users got a very strange bug : when going on my page, two images seemed to not be loaded (there was no broken link, and the images simply appeared to be skipped, see illustration below). Images not displaying illustration On reloading the page, the images indeed appeared normally, and other users did not get any bug. The thing is, I do not quite understand how this could happen, since I show the page only when all resources are loaded, through these lines of code : window.addEventListener('load', function () { document.getElementById("main-page").style.visibility = "visible"; }); Please find the code for the page below (I removed navbar code for lisibility, please let me know if full version is needed). <body id="main-page" style="visibility:hidden"> <section class="main"> <div class="wrapper"> <div class="left-col"> {% include 'instapp/status.html' %} {% include 'instapp/post.html' %} </div> <div class="right-col"> {% include 'instapp/recommandations.html' %} </div> </div> </section> <script> window.addEventListener('load', function () { document.getElementById("main-page").style.visibility = "visible"; }); </script> </body> And here is the code for displaying a single post : {% load static %} <div class="post"> <div class="info"> <div class="user"> … -
Django table connection based on the value type
I really want some help with this problem, because somehow I cannot solve it. The problem: I have a Parameter table, which is stores parameters I want to store the values in different parameters, based on the type of the parameter These are the type models: class JsonParameter(models.Model): value = models.JSONField() class StringParameter(models.Model): value = models.CharField(max_length=100) class DateParameter(models.Model): value = models.DateField() And I have a parameter model: class Parameter(TimeStampedModel): name = models.CharField(max_length=64) is_mandatory = models.BooleanField(default=True) value = SomekindOfMagic() So if I would like to create some parameters, like this param_1 = Parameter.objects.create(name="name of the param", is_mandatory=True, value="This is a string value") param_2 = Parameter.objects.create(name="name of the param", is_mandatory=True, value='{"object": "string"}') param_3 = Parameter.objects.create(name="name of the param", is_mandatory=True, value="2022-03-20") The param_1.value will be saved into the StringParameter table, the param_2.value will be saved into the JsonParameter table, and the param_3.value will be saved into the DateParameter table and the Parameter.value will contain a foreign key like object. Can I use the generic foreign key for this? Or do I have to use something else ? There is any solution for this ? Thanks guys :) -
Django HTML minifer removes closing tags for HTML and body
My django template renders this: <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>List of events</title> <link rel="stylesheet" href="/static/COMPILED/css/styles.css" /> <script src="/static/js/main.js"></script> </head> <body> <!-- insert default navigation text for every page --> aaaaaaaaaaaa </body> </html> When enabling the html minifier: INSTALLED_APPS = [ ... 'django_minify_html', ] MIDDLEWARE = [ ... 'django_minify_html.middleware.MinifyHtmlMiddleware', ] Now I get this: <!doctypehtml><html lang=en><meta charset=utf-8><title>List of events</title><link href=/static/COMPILED/css/styles.css rel=stylesheet><script src=/static/js/main.js></script><body> aaaaaaaaaaaa This is not a valid HTML. It is missing </body> and </html>. What is wrong? -
Signal Problem in creating instance of my model
please help I have a problem I'm trying to write a signal in my code when the user registers, create a portfolio and profile for the user, it can create a user and profile and portfolio correctly but when I want to create a market in admin(because only admin can create a market, not user) I got an error from my signal this line('instance.Portfolio.save(market=instance)'), My Signal @receiver(post_save, sender=User) def create_user_portfolio(sender, instance, created, **kwargs): if created: Portfolio.objects.create(user=instance) @receiver(post_save, sender=Market) def save_user_portfolio(sender, instance, **kwargs): instance.Portfolio.save(market=instance) And it is my portfolio model class Portfolio(models.Model): name = models.CharField(max_length=50, blank=False, null=True, default='portfolio') user = models.ForeignKey('accounts.User', on_delete=models.DO_NOTHING, related_name='investor') assets = models.ManyToManyField(Assets, related_name='assets') My user model class User(AbstractBaseUser, PermissionsMixin): username = models.CharField(max_length=255) email = models.EmailField(max_length=255, unique=True, db_index=True) is_verified = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_author = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) auth_provider = models.CharField( max_length=255, blank=False, null=False, default=AUTH_PROVIDERS.get('email')) I have to say my portfolio and user are in a different app And it's my market model maybe you need it class Market(models.Model): name = models.CharField(max_length=50, unique=True, blank=False, null=False) currency = models.CharField(max_length=25, blank=False, null=False) My error is: 'Market' object has no attribute 'Portfolio' -
How to send user data and its profile image using POST request from axios api to Django Rest Framework?
User Data let final_data = { 'personal_data': { 'first_name': data.first_name, 'password': data.password, 'phone': data.phone, 'username': data.username, 'email': data.email, 'image': data.profile[0] }, 'address_data': { "address_1": data.address_1, "address_2": data.address_2, "city": data.city, "pin_code": data.pin_code, "state": data.state, "country": data.country } } Above Code is my form data which i have passed. I had also tried to pass this data using json.stringify still it not works AXIOS POST Request import API from "../Axios/AxiosService" const registerUser = (data) => API.post(`registration/`, data) export default { registerUser } HEADERS if (config.url = 'registration/') { requestOptions['headers'] = {'Content-Type': 'multipart/form-data;boundary=----WebKitFormBoundaryyrV7KO0BoCBuDbTL', 'Accept' : 'application/json'} } else { requestOptions['headers'] = {'Content-Type': 'application/json'} } if (localStorage.getItem("access_token")) { requestOptions['headers'] = {"Authorization": "Token " + localStorage.getItem("access_token")} } Above Code is AXIOS POST Request and also Passed headers accrodingly. Using Application/Json i get all data except image and from data i also tried to pass data.profile instead of data.profile[0] but it didn't works. Django Rest Framework error **In POST method of Django Rest Framework i had used below listed ways to get but in all methods i didn't get any data ** request.POST request.data request.Files -
How to change the name of image while uploading
models.py def productFile(instance, request, filename): old_name = str(filename) new_name = "http://" + str(request.get_host()) + "/"+ str(instance.id)+".png" renamed_image = os.rename(old_name, new_name) return 'profile/'.join( [renamed_image] ) class User(models.Model): mobile = models.CharField(max_length=20) otp = models.CharField(max_length=6) name = models.CharField(max_length=200) username = models.CharField(max_length=200) profile_dp = models.ImageField(upload_to = productFile ,null=True, blank=True) profile_url = models.CharField(max_length=200) settings.py STATIC_URL = '/static/' STATIC_ROOT = BASE_DIR / 'staticfiles' STATICFILES_DIRS = [BASE_DIR / 'static'] MEDIA_URL = '/images/' MEDIA_ROOT = BASE_DIR /'static/images' Required Output When i upload image in profile_dp the name image name should change into this format("http://" + str(request.get_host()) + "/"+ str(instance.id)+".png") Error i am getting productFile() missing 1 required positional argument: 'filename' -
Button for selection data of database from django app
enter image description hereI have a django app and database I need to create a button in my index.html , you click on it and can choose wich country you want to select but i have a probleme my button is like in the picture I have all the names in the same line and i have words .. who can help me ? I created models: class Country(models.Model): id = models.IntegerField(primary_key=True) name = models.CharField(max_length=1, blank=True, null=True) class Meta: db_table = 'country' def __str__(self): return f'{self.name}' my index.html <form method="POST"> <div class="form-group"> <div class="input-group"> <div class="input-group-prepend"> <span class="input-group-text"> <i class="fa fa-arrow-circle-o-right"></i> </span> </div> <select name="start_time" id="id_start_time" class="form-control"> <option>{{name}}</option> </select> </div> <!-- input-group.// --> </div> <!-- form-group// --> <div class="form-group"> <div class="input-group"> -
Openlitespeed - Unable to load static files in production
I am using a ubuntu server with openlite speed and cyberpanel. I have successfully deployed my app but regarding the static files, the browser throughs an error saying 'refused to load as its MIME type....', I have tried to include my static files in app/public/static folder and collectstatic command worked fine. but my static files are not loaded yet. In my settings.py I have given STATIC_URL = 'python/static/' STATIC_ROOT = '/home/example.com/public_html/public/static' & also tried, STATIC_URL = '/static/' STATIC_ROOT = '/home/example.com/public_html/public/static' Kindly guide me to solve this issue. -
The `request` argument must be an instance of `django.http.HttpRequest`, not `builtins.str`
Please help me guys to solve this problem. Thanks in advance. Here, if phone number exists it shows me that it's exists, otherwise throws me an error like: `AssertionError at /validate_phone/ The request argument must be an instance of django.http.HttpRequest, not builtins.str. ` @permission_classes((permissions.AllowAny,)) class ValidatePhoneSendOTP(APIView): def post(self, request, *args, **kwargs): phone_number = request.data.get('phone') # I THINK PROBLEM IS HERE if phone_number: phone = str(phone_number) user = UserModel.objects.filter(phone__iexact=phone) if user.exists(): return Response({ 'status': False, 'detail': 'Phone number already exists' }) else: key = send_otp(phone) if key: old = PhoneOTP.objects.filter(phone__iexact=phone) if old.exists(): old = old.first() count = old.count() if count > 10: return Response({ 'status': False, 'detail': "Sending otp error. Limit exceeded. Please contact customer support." }) old.count = count + 1 old.save() print("count increase", count) return Response({ 'status': True, 'detail': "OTP sent successfully." }) else: PhoneOTP.objects.create( phone=phone, otp=key, ) return Response({ 'status': True, 'detail': 'OTP sent successfully' }) -
Attribute Error: 'list' object has no attribute 'get'
I'm trying to get the data from the POST method, it's JSON inside the list. Whenever I tried to read the JSON I'm getting an error as ticketid = request.data.get('TicketId') AttributeError: 'list' object has no attribute 'get' Here, what I have tried views.py @api_view(['POST']) def SaveUserResponse(request): if request.method == 'POST': auditorid =request.data.get('AuditorId') print('SaveUserResponse auditorid---', auditorid) ticketid = request.data.get('TicketId') qid = request.data.get('QId') answer = request.data.get('Answer') sid = 0 cursor = connection.cursor() cursor.execute('EXEC [dbo].[sp_SaveAuditResponse] @auditorid=%s,@ticketid=%s,@qid=%s,@answer=%s,@sid=%s', (auditorid,ticketid,qid,answer, sid,)) result_st = cursor.fetchall() for row in result_st: print('sp_SaveAuditResponse', row[0]) return Response(row[0]) return sid Payload data: [ 0: {AuditorId: 122, Agents: "", Supervisor: "", TicketId: "12111", QId: 1, Answer: "2", SID: "0",…} 1: {AuditorId: 122, Agents: "", Supervisor: "", TicketId: "12111", QId: 2, Answer: "2", SID: "0",…} 2: {AuditorId: 122, Agents: "", Supervisor: "", TicketId: "12111", QId: 3, Answer: "2", SID: "0",…} 3: {AuditorId: 122, Agents: "", Supervisor: "", TicketId: "12111", QId: 4, Answer: "2", SID: "0",…} 4: {AuditorId: 122, Agents: "", Supervisor: "", TicketId: "12111", QId: 5, Answer: "5", SID: "0",…} 5: {AuditorId: 122, Agents: "", Supervisor: "", TicketId: "12111", QId: 6, Answer: "5", SID: "0",…} 6: {AuditorId: 122, Agents: "", Supervisor: "", TicketId: "12111", QId: 7, Answer: "3", SID: "0",…} 7: {AuditorId: 122, Agents: … -
what is "request" in request.session in Django?
I just start to learn Django and i want to know that Where did this come from? def home(request): if "login" in request.session: return render(request, "home.html") return redirect("login") thanks:) -
How to add multiple lists to a variable in order
[templatetag.py] @register.filter def after_teacher(value): split_teacher = re.split('[ -> |/]', value) return split_teacher [len(split_teacher ) - split_teacher [::-1].index(''):] @register.filter def compare_teacher(v1, v2): for diff in difflib.unified_diff(v1, v2): return diff [statistic.html] {% for h in educate.history %} {% if h.summary_json.field_summary.teacher|length > 0 %} {{ h.summary_json.field_summary.teacher|after_teacher }} -> I'm going to add the compare_teacher template tag: {{ h.summary_json.field_summary.teacher|after_teacher}} {% endif %} {% endfor %} The output of html is as follows. ['Halen', 'Lisa'] ['Halen', 'Kenji'] ['Halen'] ['Halen', 'Kenji'] ['who'] I want to apply the "compare_teacher" template tag to this result(multiple list). I need two variables and I want to compare them in the order of the list. index 0 list, index 1 list and index 1 list, index 2 list and index 2 list, index 3 list and index 3 list, index 4 list and index 4 list, index 5 list -
Redirect() function isn't working in Django
I wrote a login function in Django that works fine, but the redirect() function didn't get executed and I don't know why. Here are the code snippets (print lines are for debugging): Views.py def login_view(request): if request.method == 'POST': username=request.POST.get('username') password=request.POST.get('password') user = authenticate(request,username=username, password=password) print('ya aya hai') if user is not None: print('if me aya hai') login(request, user) print('login hua') return redirect('/') print('hogya hai') else: return redirect('login_url') else: return render(request, "login.html") urls.py from django.urls.conf import path from . import views urlpatterns = [ path('',views.index,name='home'), path('login/',views.login_view,name='login_url'),] login.html <form action="{% url 'login_url' %}" method="POST"> {% csrf_token %} <label for="login_username">Username :</label> <input type="text" name="username" id="username" placeholder="Enter your username"> <label for="login_password">Password :</label> <input type="password" name="password" id="password" placeholder="Enter your password"> <input type="submit" value="Login" style="display: block;width: 95%;"> </form> -
Django Rest Viewset Error: "CSRF Failed: CSRF token missing or incorrect."
I'm using Django Rest Framework. I have the standard API endpoints (/login, /logout, /registration...) and I can use them without any problems but when I want to create a new record I got this "Csrf token missing" error. MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] if PRODUCTION: MIDDLEWARE += ['django.middleware.csrf.CsrfViewMiddleware'] these are my middleware and I'm in develop mode now so there is no CsrfViewMiddleware. I'm using ModelViewSets and ModelSerializers. I've tried using @csrf_exempt decorator but it didn't work, I had the same error. I want to use my code without having csrf token for development mode, do you guys have any idea what should I do? -
The submission form was duplicated in the ajax response page using Django views.py
I am trying to use a form to submit the parameter to views.py and get the results back to the html. However, the form part was repeatedly display in the page. enter image description here Here is my views.py def fund_main_py(request): last_trade_date = request.GET['last_trade_date'] print(last_trade_date) plot_div1, plot_div2 = fund_main_main(last_trade_date) return render(request, 'optionsfund.html', context={'plot_div1': plot_div1, 'plot_div2': plot_div2}) Here is my stocksettle.js $(document).ready(function(){ $("#btn_submit").click(function(){ document.getElementById("result").innerHTML = '抓取中.... 若期限過長,請稍後1分鐘!'; var stock_code = $("#stock_code").val(); var last_trade_date = $("#last_trade_date").val(); $.ajax({ type: "GET", url: "/fund_main_py", data:{ "stock_code":stock_code, "last_trade_date":last_trade_date }, success: function (Data) { $("#result").html(Data); }, error: function (e) { console.log(e); } }); }) }); Here is my optionsfund.html <table border="0"> <tr> <td><fieldset> <span> 指數/股票代號 :</span> <input type="button" id="btn_submit" value=" 查詢 "> </fieldset></td> </tr> </table> <span id="result"> <span id="plot1"> {% autoescape off %} {{ plot_div1 }} {% endautoescape %} </span><br><br> <span id="plot2"> {% autoescape off %} {{ plot_div2 }} {% endautoescape %} </span> </span><br><br> -
Django is doing a text editor using QuillField. This is a problem on the front-end (ReactJS)
models.py enter image description here db enter image description here enter image description here enter image description here enter image description here -
Resizing TinyMCE in django
I am trying to write a widget to resize my django tinymce but it doesn't seem to work... this is my code, what am i doing wrong? from django import forms from .models import blog, comment, reply, like, subscription from tinymce.widgets import TinyMCE class blogform(forms.ModelForm): class Meta: model = blog fields = ['content', 'title', 'blog_pic' ] widgets = { 'content': (TinyMCE(attrs={'style':'height:100vh; width:60%'})) } -
How to compare multiple lists in order in django template
I have an "Educate" class model, which consists of fields such as class name, class description, and the teacher in charge of the class. And I have a "History" class model, which is written to the database whenever the contents of the "Educate" class change. Every time the teacher in charge of Educate changes, it is tracked in the "History" class model, and what I want to get is the duration of each teacher. The "History" class model has a "summary" field, in which the contents of the changed fields are stored. If I check in DB, it is as below, and you have to load json format from template to output as string. DB: {"field_summary": {"teacher": "\ub...json...9bc -> \ub...json...9c", "contact": "010-1111-1111-> 010-0000-0000"}, "file_summary": {}} [educate/models.py] class Educate(models.Model): educate_name = models.CharField(max_length=2000, null=True) educate_explanation = models.CharField(max_length=2000, null=True) teacher = models.ManyToManyField(Contact, related_name="teacher") @property def history(self): history = self.history_set.all().order_by('-create_date') for h in history: setattr(h, 'summary_json', json.loads(h.summary)) return history class History(models.Model): educate = models.ForeignKey(Educate, on_delete=models.SET_NULL, null=True, blank=True) summary = models.TextField(blank=True, null=True) create_date = models.DateTimeField(auto_now_add=True) def json(self): return { 'id': self.id, 'educate': { 'id': self.educate.id, 'educate_name': self.educate.educate_name, 'educate_explanation': self.educate.educate_explanation, }, 'summary': self.summary, 'create_date': self.create_date } [educate/views.py] def statistic(request): educate = Educate.objects.get(id='117') return render(request, 'statistic.html', {'educate': … -
Run celery task for maximum 6 hour, if it it takes more then 6 hour, rerun the same task again?
i have using django project with celery + rabbitmq , some of my task takes like 6 hour or more ,even stack , so i want to re-run the same task if its takes more than 6 hour how to do that ,im new with celery ? -
Django AJAX "Uncaught TypeError: $(...).attrs is not a function"
When I tap the anchor tag to send the data, I get this error Uncaught TypeError: $(...).attrs is not a function. I did console.log($(this)), the output is [object Object]. I also did console.log(JSON.stringify($(this))), the output is {"0":{},"length":1} HTML, My anchor tag: <a href="{% url 'my-site' slug=object.anotherObject.slug %}" id="update-done" data-donePk="{{object.pk}}" >Done</a> JS, My AJAX $(document).on('click', '#update-done', function(e) { e.preventDefault() let confirmation = confirm("Are you sure you want to make done?"); if (confirmation) { console.log("this: " + JSON.stringify($(this))) alert($(this)) // Error comes from this line below var objectPk = $(this).attrs('data-donePk') var makeDone = 'post' $.ajax({ url: "/site/make_done/", data: { 'csrfmiddlewaretoken': "{{ csrf_token }}", "objectPk":objectPk, "makeDone": makeDone, }, type: "POST", dataType: 'json', cache: false, success: function(data) { console.log(data) }, }) } });