Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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) }, }) } }); -
How to avoid port number in django app url in comination with apache2
My django website is hosted on ubuntu apache2 vps which reserves port 80. I want to hide or avoid portnumber in django url. By googling i learnt using port 80 will help for that. But apache2 has reserved port 80. Is there any workaround to fix it ? Any hint will be greatly apprecitated. -
how to include a page in every page? (django)
I have a file named common.html. I want to show this HTML page in every page; with Django. like when you include something with WordPress hooks. -
Save() is prohibited to prevent data loss
I'm getting a save() prohibited to prevent data loss due to unsaved related object 'user' in my account views. The line with account = form.save() to be exact. Here's my views, account model, and registration form: Registration form: class RegistrationForm(UserCreationForm): steam_uid = forms.CharField(max_length=17, help_text="Required. Add a valid id") email = forms.EmailField(max_length=255, help_text="Required. Add a valid email") class Meta: model = account fields = ('steam_uid', 'email', 'username', 'password1', 'password2') def clean_email(self): email = self.cleaned_data['email'].lower() try: account = account.objects.get(email=email) except Exception as e: return email raise forms.ValidationError(f"Email {email} is already in use.") def clean_username(self): username = self.cleaned_data['username'] try: account = account.objects.get(username=username) except Exception as e: return username raise forms.ValidationError(f"Username {username} is already in use.") class AccountAuthenticationForm(forms.ModelForm): password = forms.CharField(label="Password", widget=forms.PasswordInput) class Meta: model = account fields = ("username", "password") def clean(self): if self.is_valid(): username = self.cleaned_data['username'] password = self.cleaned_data['password'] if not authenticate(username=username, password=password): raise forms.ValidationError("Invalid Login") Register view: def register_view(request, *args, **kwargs): user = request.user if user.is_authenticated: return HttpResponse("You are already authenticated as " + str(user.email)) context = {} if request.POST: form = RegistrationForm(request.POST) if form.is_valid(): account = form.save() email = form.cleaned_data.get('email').lower() raw_password = form.cleaned_data.get('password1') # Account has already been authenticated at this point. Causes 'AnonymousUser' object has no attribute '_meta' error. … -
Django - Left Click on the link not working but right click with new tab works
I have a DropDown Menu in my Navbar which shows the recent Notifications for the user. The data is coming dynamically from the Database through Django, and every notification is linked to another Page (to access that, I am getting the ID of the Notification and sending that to views.py) My problem is, I can not left click on the Notification. I have tried to make lots of changes but still with no result. The links do work if I Right Click on any of them and open them in New Tab. The .html file contains this following code which shows all the notifications, <ul class="setting-area"> <li> <a href="#" title="Notification" data-ripple=""> <i class="ti-bell"></i> {% if fetch_notification_count > 2 %} <span class="text-danger"> (2+) </span> {% else %} <span>{{fetch_notification_count}}</span> {% endif %} </a> <div class="dropdowns"> <span>{{fetch_notification_count}} New Notifications</span> <ul class="drops-menu"> {% for i in fetch_notification %} <li> <span><a href="{% url 'opennotification' i.post_id.id %}" title=""></span> <div> {% if i.show_user.User_Image %} <img class="card-img-top" style=" vertical-align: middle;width: 50px;height: 50px;border-radius: 50%;" src={{ i.show_user.User_Image.url}} alt=""> {% elif t == 1 %} <img class="card-img-top" style=" vertical-align: middle;width: 50px;height: 50px;border-radius: 50%;" src={{ i.User_Image.url}} alt=""> {% else %} <img class="card-img-top" style=" vertical-align: middle;width: 60px;height: 60px;border-radius: 50%;" src="static\images\resources\no-profile.jpg"> {% endif %} … -
Django send_mail() is not grouping emails together based on subject in outlook and apple mail
I am using Django's send_mail() for my email notifications, and I need to send multiple follow up mails which needs to be grouped together based on the same subject. Gmail groups the emails automatically based on the same subject line, but for some reason Outlook and Apple Mail doesn't group them. This results in email spamming in the inbox.I even tried to change the outlook settings to thread conversations, but still no luck.Is there anything I am missing out here ? -
how to separate sentences and assign each sentence to a list element on template
how do I separate the list of strings by "." and render them into separate "li" elements on the template. Currently, it just displays everything in one "li" element. I would really appreciate it if someone can help, thx! models.py class Product(models.Model): benifits = ArrayField(models.CharField(max_length=800), blank=True) @property def benifits_slicing(self): benifit = self.benifits for point in benifit: test = point.split(".") return point HTML <div id="BENIFITS"> <li class="benifits-style">{{ products.benifits_slicing }}</li> </div> what it looks like rn: -
database does not exist postgresql
I am working on connecting a Postgres DB to Django. I have created the db through pgAdmin 4 under the user postgres. I've set my environment variables as followed DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } try: if sys.argv[1:2] != ['test']: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'HOST': env('PGHOST'), 'USER': env('PGUSER'), 'NAME': env('PGDATABASE'), 'PASSWORD': env('PGPASSFILE'), 'PORT': env('PGPORT'), } } except: pass with my .env file containing each variable. When I try to migrate it through ubuntu command line I get the error database <dbname> does not exist I've installed psycopg2 and pillow and set local all postgres peer to local all postgres md5. my os is windows 11 so I am wondering if this is happening because my project directory is through ~/directory/to/path and postgres and pgAdmin are installed in /etc/postgresql/ and /mnt/c/'Program Files'/PostgreSQL? Should I move those files from / to ~? NOTE: I've run psql canvasDB and got back role "awilbur" does not exist -
change superuser password in django
I tried to change my admin password but I have an error while running user = User.objects.get(username='normaluser') -
How to get a url param in a django template?
I need to get the param of the url inside a html file, but I need to know if is possible in a tag, or how can I get the url params using Class-based views? My urls.py file from django.urls import path from .views import UsersView urlpatterns = [ path('list/<int:pk>/', UsersView.as_view(), name='user_list'), ] My html file: <!DOCTYPE html> <html lang="en"> <head> <title>Users</title> </head> <body> {{ request.GET.pk }} </body> </html> -
Is there a way to use both UserPassesTestMixin and PermissionRequiredMixin?
I'm trying to create a moderator using Django class-based views in my blog app. It uses the UserPassesTestMixin to prevent other users from editing content that's not theirs. What I'm trying to implement is a group called Manager that has change_blog permissions and I am using PermissionsRequiredMixin in views.py Here is my code so far class UserAccessMixin(PermissionRequiredMixin): def dispatch(self, request, *args, **kwargs): if (not self.request.user.is_authenticated): return redirect_to_login(self.request.get_full_path(), self.get_login_url(), self.get_redirect_field_name()) if not self.has_permission(): return redirect('/') return super(UserAccessMixin, self).dispatch(request, *args, **kwargs) class IssueUpdateView(LoginRequiredMixin, UserPassesTestMixin, UserAccessMixin, UpdateView): raise_exception = False permission_required = 'issues.change_issue' model = Issue fields = ['title', 'content', 'mark_as', 'assignee'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) def test_func(self): issue = self.get_object() if self.request.user == issue.author: return True return False When I test this code out as written, the permissions don't work and I get a 403 error page, but everything else functions normally. However, if I delete UserPassesTestMixin and leave PermissionRequiredMixin in, it works but then new problems arise. The original poster can no longer update their own post but when a mod user updates the post, it completely overwrites everything as if the mod user was the original poster. Is there a way to tweak either UserPassesTestMixin or …