Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
not able to authenticate access_token comming from flutter app in django using google-oauth2 errors come up like your "credentials are not correct"
@api_view(['POST']) @permission_classes([AllowAny]) @psa() def register_by_access_token(request, backend): token = request.data.get('access_token') user = request.backend.do_auth(token) print(request) if user: token, _ = Token.objects.get_or_create(user=user) return Response( { 'token': token.key }, status=status.HTTP_200_OK, ) else: return Response( { 'errors': { 'token': 'Invalid token' } }, status=status.HTTP_400_BAD_REQUEST, ) so above is the code and this is the URL re_path('api/register-by-access-token/' + r'social/(?P<backend>[^/]+)/$', register_by_access_token), But all the time user = request.backend.do_auth(token) this thing is giving error that "credentials are not correct" -
How to retrieve random records of Django ORM on a weekly basis
I am new to Django and I'd need some help for a project I have. I am currently building the API using Django-Rest-Framework and I would like to have a view which returns a weekly list of exercises. I am not sure how i could make it so the queried objects change weekly... atm I've created a custom Manager which retrieves a random amount of exercises from the exercise db Models.py class ExerciseManager(models.Manager): random_exercises = [] def random(self, amount=20): self.random_exercises.clear() exercises = Exercise.objects.all() for i in range(amount): self.random_exercises.append(random.choice(exercises)) return self.random_exercises class Exercise(models.Model): name = models.CharField(max_length=100, unique=True) objects = ExerciseManager() def __str__(self): return f"{self.name}" views.py @api_view(['GET']) def exercise_list(request): exercises = Exercise.objects.random() serializer = ExerciseSerializer(exercises, many=True) return Response(serializer.data) -
I use django auth in my project. how can i overwrite login view to add a remember me view?
This is my urls.py: from django.urls import path, reverse_lazy from django.contrib.auth import views as auth_views from .forms import EmailValidationOnForgotPassword from . import views app_name = 'account' urlpatterns = [ path('', views.dashboard, name='dashboard'), path('login/', auth_views.LoginView.as_view(), name='login'), path('logout/', auth_views.LogoutView.as_view(), name='logout'), path('password_change/', auth_views.PasswordChangeView.as_view(success_url=reverse_lazy('account:password_change_done')), name='password_change'), path('password_change/done', auth_views.PasswordChangeDoneView.as_view(), name='password_change_done'), path('password_reset/', auth_views.PasswordResetView.as_view(form_class=EmailValidationOnForgotPassword, success_url=reverse_lazy('account:password_reset_done')), name='password_reset'), path('password_reset/done', auth_views.PasswordResetDoneView.as_view(), name='password_reset_done'), path('reset/<uidb64>/<token>', auth_views.PasswordResetConfirmView.as_view(success_url=reverse_lazy('account:password_reset_complete')), name='password_reset_confirm'), path('reset/done', auth_views.PasswordResetCompleteView.as_view(), name='password_reset_complete'), ] Is there any attributes i can use like 'success_url' or 'form_class' -
form is not submit and load another page in production
i have a form page which work perfectly in locally but after uploading it to railway it start showing this error I also checked locally it worked perfectly fine and load the page when click forms submit button but in production it throws above mentioned error here is my form template <form action="{% url 'personal_readme:preview' %}" method="POST" enctype="multipart/form-data"> **{% csrf_token %}** <div class="name_tag"> <h2><iconify-icon icon="bi:person-circle"></iconify-icon> ( Title )</h2> {{ form.name.label_tag }} <span>{{ form.name }}</span> </div> <hr> <div class="support_tag"> <h2><iconify-icon icon="fa-solid:handshake"></iconify-icon> ( Support )</h2> <iconify-icon icon="line-md:buy-me-a-coffee-filled"></iconify-icon> {{ form.buy_me_coffee.label_tag}} {{ form.buy_me_coffee}} <iconify-icon icon="simple-icons:patreon"></iconify-icon> {{ form.patreon.label_tag}} {{ form.patreon}} </div> <hr> <div class="genrate text-center"> <button type="submit" class="gen_btn"><iconify-icon icon="bxs:file-md"></iconify-icon> Genrate File</button></div> </form> my views.py for def home(request): if request.method == 'POST': form = Personal_Readme_form(request.POST) if form.is_valid(): form.save() return redirect('personal_readme:preview') else: form = Personal_Readme_form() return render(request, 'home.html', {'form': form}) any suggestion might be helpful -
Django-forms: ValidationError not working / check if attribute exists
I am trying to get an error for the form if name of a created process already exists. Now what happens is that the form just doesn't submit, but it doesn't raise any errors to the form itself noting what is going on. I have looked all different ways to get the ValidationError to do something, but I cannot get it work at all. Form works otherwise as it submits if value doesn't already exist. What am I missing here? Here is models.py class Process(models.Model): name = models.CharField('Process name', max_length=100, unique=True, error_messages={'unique':"Name already in use"}) Here is forms.py class NewProcess(forms.ModelForm): class Meta: model = Process fields = [ 'name', ] def __init__(self, *args, **kwargs): super(NewProcess, self).__init__(*args, **kwargs) def clean_name(self): process_name = self.cleaned_data.get('name') existing = Process.objects.filter(name=process_name).exists() if existing: raise forms.ValidationError(u"Name already in use") return process_name Here is views.py def process_create(request, *args, **kwargs): createprocess = NewProcess(request.POST or None) processes = Process.objects.all() if request.method == 'POST': createprocess = NewProcess(request.POST) if createprocess.is_valid(): process = createprocess.save(commit=False) #other functions here creatprocess.save() context = { 'processes':processes, } return render(request, "process/process-list.html", context) context = { 'createprocess':createprocess, } return render(request, "process/process-create.html", context) -
Django Error: 'WSGIRequest' object has no attribute 'order'
I'm trying to render out the get_cart_total to the email template I'm working on, which gets sent when the success view is triggered and the boolean is True, currently it gets an error message saying 'WSGIRequest' object has no attribute 'order', what's causing this and how do I fix it? Model class Customer(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE, blank=True, null=True) email = models.EmailField(max_length=150) class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True) @property def get_cart_total(self): orderitems = self.orderitem_set.all() total = sum([item.get_total for item in orderitems]) return total Views def success(request): if order.complete == True: email = request.user.customer.email #error cart_total = request.order.get_cart_total html_message = render_to_string('check/emails/test.html', {'cart_total': cart_total}) recipient_list = [email, ] send_mail( subject, plain_message, email_from, recipient_list, html_message=html_message ) Traceback Traceback (most recent call last): File "D:\test\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "D:\test\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\test\shop\views.py", line 364, in success cart_total = request.order.get_cart_total AttributeError: 'WSGIRequest' object has no attribute 'order' -
I have HTML page stored in javascript variable how to show it in the page
this is my variable have HTML code fetched from database const z = " <div id="div_idadnan"><div class="accordion" id="accordionExample0"><div class="accordion-item"> <h2 class="accordion-header" id="headingOne"><button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#collapseOneadnan" aria-expanded="true" aria-controls="collapseOne">adnan</button></h2><div id="collapseOneadnan" class="accordion-collapse collapse show" aria-labelledby="headingOne" data-bs-parent="#accordionExample0">"<div style="background-color:#eecf9e" class="accordion-body" id="adnan"><table class="table table-bordered border-primary"><thead><tr><th style="font-size:20px;" scope="col">اللاعب</th><th style="font-size:20px;" scope="col">الحرف </th> <th style="font-size:20px;" scope="col">إسم </th><th style="font-size:20px;" scope="col">إسم بنت</th><th style="font-size:20px;" scope="col">حيوان </th><th style="font-size:20px;" scope="col">نبات </th><th style="font-size:20px;" scope="col">جماد </th><th style="font-size:20px;" scope="col">بلاد </th><th style="font-size:20px;" scope="col">الغرفة </th><th style="font-size:20px;" scope="col">مجموع </th></tr></thead><tbody id="divvadnan"><tr><th scope="row">⭐<button id="removeme" type="button" onclick="userremove('adnan')" class="btn btn-primary btn-rounded" data-hover="CLICK ME" data-active="IM ACTIVE"><span>adnan</span></button> </th><td style="font-size:18px;" id="letter">ق</td><td style="font-size:18px;" id="noun">ق</td><td style="font-size:18px;" id="gnoun">ق</td><td style="font-size:18px;" id="animalNoun">ق</td><td style="font-size:18px;" id="plants">ق</td><td style="font-size:18px;" id="inanimate">ق</td><td style="font-size:18px;" id="countries">ق</td><td style="font-size:18px;" id="room">1234567</td><td style="font-size:18px;" id="sum">NaN</td></tr><tr><td scope="row"></td><td scope="row"></td><td><select style="font-size:16px;" onchange="OnSelectedIndexChange('adnan','noun_result')" id="noun_resultadnan" disabled=""><option style="font-size:16px;" href="#">0</option> <option style="font-size:16px;" href="#">5</option><option style="font-size:16px;" href="#">10</option></select><div id="noun_resulttdadnan"></div></td><td><select style="font-size:16px;" onchange="OnSelectedIndexChange('adnan','gnoun_result' )" id="gnoun_resultadnan" disabled=""><option style="font-size:16px;" href="#">0</option> <option style="font-size:16px;" href="#">5</option><option style="font-size:16px;" href="#">10</option></select><div id="gnoun_resulttdadnan"></div></td><td><select style="font-size:16px;" onchange="OnSelectedIndexChange('adnan','animal_result')" id="animal_resultadnan" disabled=""><option style="font-size:16px;" href="#">0</option> <option style="font-size:16px;" href="#">5</option><option style="font-size:16px;" href="#">10</option></select><div id="animal_resulttdadnan"></div></td><td><select style="font-size:16px;" onchange="OnSelectedIndexChange('adnan','plants_result')" id="plants_resultadnan" disabled=""><option style="font-size:16px;" href="#">0</option> <option style="font-size:16px;" href="#">5</option><option style="font-size:16px;" href="#">10</option></select><div id="plants_resulttdadnan"></div></td><td><select style="font-size:16px;" onchange="OnSelectedIndexChange('adnan','countries_result')" id="countries_resultadnan" disabled=""><option style="font-size:16px;" href="#">0</option> <option style="font-size:16px;" href="#">5</option><option style="font-size:16px;" href="#">10</option></select><div id="countries_resulttdadnan"></div></td><td><select style="font-size:16px;" onchange="OnSelectedIndexChange('adnan','inanimate_result')" id="inanimate_resultadnan" disabled=""><option style="font-size:16px;" href="#">0</option> <option style="font-size:16px;" href="#">5</option><option style="font-size:16px;" href="#">10</option></select><div id="inanimate_resulttdadnan"></div></td><td class="success" id="sumadnan">0</td></tr><button type="submit" class="btn btn-primary" id="calcadnan" onclick="calc('adnan' , 'ق' , 'ق' ,'ق','ق','ق','ق','ق','1234567')" style="">Calculate</button></tbody></table></div></div></div></div></div><div id="div_idkaram"><div class="accordion" id="accordionExample1"><div class="accordion-item"> <h2 class="accordion-header" id="headingOne"><button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#collapseOnekaram" … -
Django - Stop Page from reloading after GET Request
I'd like to show all grades from one user on Button Click. Now I wanted to integrate an expandable Button from Bootstrap. The GET Request works perfectly, but the JavaScript for the expandable Button gets triggered on Button Click and then the Page gets reloaded. That means the Button now is back at the original state. Do you guys maybe have a way to fix that? noten.html {% if subject_list %} <form name="subject-list" method="GET"> <ul> {% for subject in subject_list %} <p> <button class="btn btn-primary" type="submit" data-bs-toggle="collapse" data-bs-target="#{{ subject }}" aria-expanded="false" aria-controls="collapseExample" value="{{ subject }}" id="{{ subject }}" name="subject"> {{ subject }} </button> </p> <div class="collapse" id="{{ subject }}"> <div class="card card-body"> {% if grades %} {% for grade in grades %} <li>{{ grade }}</li> {% endfor %} {% else %} <p>Du hast keine Noten in diesem Fach!</p> {% endif %} </div> </div> {% endfor %} </ul> </form> {% endif %} views.py def noten(request): if request.user.is_authenticated: # if user is logged in object_list = Subject.objects.order_by('name') subject_list = [] for subject in object_list: subject_list.append(subject.name) if request.method == 'GET': subject = request.GET.get('subject', '') if subject != '': print(f"GET {subject}") grades = Test.get_grades(student=request.user.id, subject=subject, self=Test) return render(request, 'noten.html', {'subject_list': subject_list, 'grades': grades}) else: … -
Python inside a virtualenv is broken (Django)
TL;DR - Microsoft Store Apps are broken (0 bytes), hence the Python interpreter is unable to create process and run "Python" inside virtualenv, I failed to follow numerous explanations of how to change virtualenv path for Python. Recently, without any changes to my computer/environment, an issue started occurring when executing (also tried python3, which brings the same): python manage.py runserver This brought back the following issue: Unable to create process using '"C:\Users\MyUser\AppData\Local\Microsoft\WindowsApps\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\python.exe"' As I dug deeper, I realized that all of the apps installed under this folder are 0 bytes, hence they are completed broken, all of a sudden. Therefore I figured it's not an issue with Django, rather the python itself. I tried changing the virtualenv path for Python.exe, instead of using WindowsApps version, I installed the original Python from the original website. I failed to do so, multiple times. I tried: "https://stackoverflow.com/questions/4757178/how-do-you-set-your-pythonpath-in-an-already-created-virtualenv/47184788#47184788" - Adding the path inside "activate" and "activate.bat", as set PYTHONPATH="C:\Users\MyUser\AppData\Local\Programs\Python\Python310\python.exe" And the issue persists. I tried every solution/article I found in regards to the issue I have. Many of them claim a simple result, whereas the rest claim a complete refactor is required. Even downloading from Microsoft store is broken, it always fails. Since I'm … -
Django models foreign key validation
I have the following Django models: class Owner(models.Model): name = models.CharField(max_length=30) class Dog(models.Model): name = models.CharField(max_length=30) owner = models.ForeignKey(Owner) class GoForAWalk(models.Model): date = models.DateTimeField() location = models.CharField() owner = models.ForeignKey(Owner) dog = models.ForeignKey(Dog) I want that a Owner can only GoForAWalk with one of his own Dog. Currently any owner can go for a walk with any dog. Would you restrict this via model validators or via some logic during the creation of a new GoForAWalk object? Can anyone provide an example? I'm quite stuck. Thanks a lot! Cheers, Philipp -
Why does Django debugger keep saying the variable is 'None' when its not?
I have a problem with Django sessions. I am trying to create a clinic website which has a booking functionality so users can book their appointments online. Unfortunately the Django sessions not working properly! The booking is in two steps: Getting the first two datas which are: 'service' and 'day'. Then showing the user the hours (time) available in that day for user to choose for appointment. In the first step in the booking process I get the datas "day" and "service" and then store it in the session so I can check what hour (time) is free in that day and only show the ones that are not booked before. But when we move to the second step of the booking process Django raises a ERROR that the 'day' and 'service' data are 'None'! but they are not 'None' as shown in the 'Debug picture2' link at the end of this question. Views.py: from django.shortcuts import render, redirect from datetime import datetime, timedelta from .models import * from django.contrib import messages def tehranBooking(request): today = datetime.now() minDate = today.strftime('%Y-%m-%d') deltatime = today + timedelta(days=21) strdeltatime = deltatime.strftime('%Y-%m-%d') maxDate = strdeltatime times = [ "3 PM", "3:30 PM", "4 PM", … -
Override error from django image extensions in models
I want to get my custom error from validate_image this is my models.py def validate_image(image): valid_image_extensions = ['jpg', 'png', 'jpeg'] input_extension = str(image).split('.')[1] if input_extension not in valid_image_extensions: raise ValidationError( f"We aren't accepted your extension - {input_extension} only accepted {','.join(valid_image_extensions)}" ) class Image(models.Model): description = models.CharField(null=True, default='Image', blank=True, max_length=120) image = models.ImageField(upload_to='images', validators=[validate_image]) When i try upload image with .raw extension i expected my custom validation but i have error from django. { "image": [ "File extension “raw” is not allowed. Allowed extensions are: bmp, dib, gif, tif, tiff, jfif, jpe, jpg, jpeg, pbm, pgm, ppm, pnm, png, apng, blp, bufr, cur, pcx, dcx, dds, ps, eps, fit, fits, fli, flc, ftc, ftu, gbr, grib, h5, hdf, jp2, j2k, jpc, jpf, jpx, j2c, icns, ico, im, iim, mpg, mpeg, mpo, msp, palm, pcd, pdf, pxr, psd, bw, rgb, rgba, sgi, ras, tga, icb, vda, vst, webp, wmf, emf, xbm, xpm." ] } How i can run custom validation before django validation ? -
Why i can't get variable name from Django
I have a Django project that i'm working on. I need to print something to CLI to make it easier to debug. This is what i need print('============================================') print('VARIABLE_NAME_IN_CAPS') print(variable) print(f'LENGTH : {len(variable)}') print('============================================') this is my function to get variable name. This is where i got the snippet def get_variable_name(variable): globals_dict = globals() return [var_name for var_name in globals_dict if globals_dict[var_name] is variable] But when i called the function i get empty array []. I've tried to do it without function and do a separate test in another file and it worked. Is there anything that prevent this to happen in Django ? -
ValueError at / The 'image' attribute has no file associated with it
How can i solve this error??i cannot see uploaded picture from users.it give ValueError at / The 'image' attribute has no file associated with it. error everytime. The job was to display user uploaded post in the social media site. I first created a model named “uploade” and added fields such name, location, number and profile picture. It worked excellent until I tested imageField associated with profile picture. [i cant understand whts wrong here,for this error][1] [1]: https://i.stack.imgur.com/yvffJ.png **---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/avatar-2.jpg' %}" class="bg-gray-200 border border-white rounded-full w-8 h-8"> </div> </a> --> <span class="block 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 class="bg-white w-56 shadow-md mx-auto p-2 mt-12 rounded-md text-gray-500 hidden text-base border border-gray-100 " uk-drop="mode: hover;pos: top-right"> <ul class="space-y-1"> <!-- <li> <a href="#" class="flex items-center px-3 py-2 hover:bg-gray-200 hover:text-gray-800 rounded-md "> <i class="uil-share-alt mr-1"></i> Share </a> </li> --> <!-- <li> <a href="#" class="flex items-center px-3 py-2 hover:bg-gray-200 hover:text-gray-800 rounded-md "> <i class="uil-edit-alt … -
The content published by wagtail using the RichTextField field does not support spaces and indents
I am a beginner and use the blog developed by wagtail to take notes. After the record code part is saved, the blank space and indentation disappear. This problem is stuck. Help me. Thank you! class BlogPage(Page): body = RichTextField(blank=True) saved e.g: class BlogPage(Page): body = RichTextField(blank=True) -
MongoDB with Django: TypeError: Model instances without primary key value are unhashable
I'm trying to connect MongoDB with Django. settings.py DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': '<name>', 'ENFORCE_SCHEMA': False, 'CLIENT': { 'host': f'mongodb+srv://{mongodb_username}:{mongodb_password}@{mongodb_cluster}/?retryWrites=true', 'uuidRepresentation': 'standard', 'waitQueueTimeoutMS': 30000 } } } models.py import uuid from django.db import models # Create your models here. class ModernConnectUsers(models.Model): user_id = models.UUIDField(primary_key=True, default=uuid.uuid4()) user_name = models.CharField(max_length=30, null=False) The model has not been used anywhere for now. python manage.py makemigrations && python manage.py migrate outputs: Migrations for 'modern_connect': modern_connect/migrations/0003_alter_modernconnectusers_user_id.py - Alter field user_id on modernconnectusers Operations to perform: Apply all migrations: admin, auth, contenttypes, modern_connect, sessions Running migrations: No migrations to apply. Your models in app(s): 'modern_connect' have changes that are not yet reflected in a migration, and so won't be applied. Run 'manage.py makemigrations' to make new migrations, and then re-run 'manage.py migrate' to apply them. Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/sarvesh/PycharmProjects/modernConnect/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/home/sarvesh/PycharmProjects/modernConnect/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/sarvesh/PycharmProjects/modernConnect/venv/lib/python3.8/site-packages/django/core/management/base.py", line 414, in run_from_argv self.execute(*args, **cmd_options) File "/home/sarvesh/PycharmProjects/modernConnect/venv/lib/python3.8/site-packages/django/core/management/base.py", line 460, in execute output = self.handle(*args, **options) File "/home/sarvesh/PycharmProjects/modernConnect/venv/lib/python3.8/site-packages/django/core/management/base.py", line 98, in wrapped res = handle_func(*args, **kwargs) File "/home/sarvesh/PycharmProjects/modernConnect/venv/lib/python3.8/site-packages/django/core/management/commands/migrate.py", line 317, in handle emit_post_migrate_signal( File … -
Python Jsonschema validation returning error on correct input
I am quite new to Python, and trying to validate a json file in the following way with jsonschema validation: carsSchema = {"type": "object", "properties" : { "model_year": {"type" : "string"}, "make": {"type" : "string"}, "model": {"type" : "string"}, "rejection_percentage": {"type" : "string"}, "reason_1": {"type" : "string"}, "reason_2": {"type": "string"}, "reason_3": {"type" : "string"}} then reading a json file with inputs: file = json.loads(request.FILES['file'].read()) for instance in file: print(validate(instance, carsSchema)) the file inputs looks like this: [ { "model_year": "2013", "make": "Mercedes-Benz", "model": "CLS", "rejection_percentage": "0,0", "reason_1": "", "reason_2": "", "reason_3": "" } ] I am receiving None on all the file inputs even though they are in correct format. Thanks in advance :) -
If statement in Django template always runs the code no matter the condition is True or False
I'm using a Key-Value model to make static template's data dynamic. This is my model's code: class SiteDataKeyValue(models.Model): key = models.CharField(max_length=200, verbose_name="Text title") value = models.TextField(verbose_name="Text") def __str__(self): return self.key For each static page, e.g. About us or Contact us, first I've created the texts in the admin panel. Then, I've written the views below: class ContactUsPageView(ListView): """ In this view we are fetching site data from database, in a function named get_context_data. In this function, we filter the model for objects that contains the word 'contact', therefore fetching data referring to the about page only. After that the context list is sent to the template, and there with a for loop and an if statement, each key, value set is chosen for the proper place. """ model = SiteDataKeyValue template_name: str = "core/contact-us.html" def get_context_data(self, **kwargs): context = super(ContactUsPageView, self).get_context_data(**kwargs) context["contact_page_data"] = self.model.objects.filter(key__contains="contact") return context Finally, in the template, I'm trying to use these data with a for loop and an if statement as shown below: {% for text in contact_page_data %} {% if text.key == "contact us factory address" %} <p class="card-text"><i class="bi bi-geo-alt me-2"> {{ text.value }} </p> {% endif %} {% endfor %} I have just … -
OSError: [Errno 63] File name too long: db.sqlite3 when doing collectstatic on django
I already have done collectstatic before, and it went well. Now I tried to deploy the app to Heroku, and got the error. It reproduces locally as well. OSError: [Errno 63] File name too long: '/Users/admin/Desktop/Programming/Python/UkranianFunds/src/app/staticfiles/app/staticfiles/app/staticfiles/app/staticfiles/app/staticfiles/app/staticfiles/app/staticfiles/app/staticfiles/app/staticfiles/app/staticfiles/app/staticfiles/app/staticfiles/app/staticfiles/app/staticfiles/app/staticfiles/app/staticfiles/app/staticfiles/app/staticfiles/app/staticfiles/app/staticfiles/app/staticfiles/app/staticfiles/app/staticfiles/app/staticfiles/app/staticfiles/app/staticfiles/app/staticfiles/app/staticfiles/app/staticfiles/app/staticfiles/app/staticfiles/app/staticfiles/app/staticfiles/app/staticfiles/app/staticfiles/app/staticfiles/app/staticfiles/app/staticfiles/app/staticfiles/app/staticfiles/app/staticfiles/app/staticfiles/app/staticfiles/app/staticfiles/app/staticfiles/app/staticfiles/app/staticfiles/app/staticfiles/app/staticfiles/app/staticfiles/app/staticfiles/app/staticfiles/app/staticfiles/app/staticfiles/app/staticfiles/app/staticfiles/app/staticfiles/app/staticfiles/app/staticfiles/app/staticfiles/db.sqlite3' Here is my project structure: https://monosnap.com/file/Jkom9ug3DJFMDcwOz4UkY3OUfS1bUY I have my db.sqlite3 in gitignore if that matters. Here is my settings: PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) STATIC_URL = '/static/' STATIC_ROOT = os.path.join(PROJECT_ROOT, 'staticfiles') STATICFILES_DIRS = [ os.path.join(BASE_DIR), 'static' ] -
CANT_FIND_SAVED_IMPORT, Can't import CSV file
I have got an error every time, this is because the mappingId is wrong, where I need to create/get mappingId? any solution. {"type":"error.SuiteScriptError","name":"CANT_FIND_SAVED_IMPORT","message":"No saved import with internalId 123","stack":["createError(N/error.js)","<anonymous>(adhoc$-1$debugger.user:13)","<anonymous>(adhoc$-1$debugger.user:1)"],"cause":{"type":"internal error","code":"CANT_FIND_SAVED_IMPORT","details":"No saved import with internalId 123","userEvent":null,"stackTrace":["createError(N/error.js)","<anonymous>(adhoc$-1$debugger.user:13)","<anonymous>(adhoc$-1$debugger.user:1)"],"notifyOff":false},"id":"","notifyOff":false,"userFacing":false} require(["N/task","N/file"],function(task,file){ var fileObj = file.create({ name:"temporary.csv", fileType:file.Type.CSV, contents: "1,1" }); var obj = task.create({taskType: task.TaskType.CSV_IMPORT}); obj.mappingId = 123; obj.importFile = fileObj; obj.name = "TestingCSV"; var objId = obj.submit(); log.debug(objId); }); -
How to use reporting and statistics capabilities for blog post using django
models.py from django.db import models from django.contrib.auth.models import User STATUS = ( (0,"Draft"), (1,"Publish") ) class BlogModel(models.Model): id = models.AutoField(primary_key=True) blog_title = models.CharField(max_length=200) blog = models.TextField() status = models.IntegerField(choices=STATUS, default=0) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: ordering = ['-created_at'] def __str__(self): return f"Blog: {self.blog_title}" class CommentModel(models.Model): your_name = models.CharField(max_length=20) comment_text = models.TextField() created_at = models.DateTimeField(auto_now_add=True) blog = models.ForeignKey('BlogModel', on_delete=models.CASCADE) class Meta: ordering = ['-created_at'] def __str__(self): return f"Comment by Name: {self.your_name}" admin.py from django.contrib import admin from blog.models import BlogModel,CommentModel class PostAdmin(admin.ModelAdmin): list_display = ('blog_title', 'status','created_at','updated_at') list_filter = ('status',) search_fields = ('blog_title', 'content',) admin.site.register(BlogModel, PostAdmin) admin.site.register(CommentModel) I created a simple blog post website with comments and I want to create reports and on the admin panel I have to see how to achieve this. Like how many posts are created and how many have comments and how many post are draft and published -
how to return 5 top names per month, truncMonth
I've these models: class City(models.Model): name = models.CharField(max_length=150) class Hospital(models.Model): name = models.CharField(max_length=150) city = models.ForeignKey(City, on_delete=models.CASCADE, related_name="hospital") class Patient(models.Model): name = models.CharField(max_length=150) city = models.ForeignKey(City, on_delete=models.CASCADE, related_name="patients") hospital = models.ForeignKey(Hospital, on_delete=models.CASCADE, related_name="patients", blank=True, null=True) date_visited = models.DateTimeField(auto_now_add=True) i want to return top 5 hospitals per month which has most patients visited for example: month : 10/1/2022 hospital A : 100 patient hospital B : 95 patient hospital C : 80 patient hospital D : 60 patient hospital E : 55 patient and so on. my views.py from django.db.models.functions import TruncMonth Patient.objects.annotate(month=TruncMonth('date_visited')) #im not sure how to complete it! I appreciate your helps Thank you -
How to save html tags with text to database? django & react
I am using CKEditor to enter text and saving into database. When I retrieve it description, it also shows the html p tags which i dont want. How can I save it into database such that the p tags don't show but tags like are still applied. Essentially I want to save it as html itself and not text. Is there a way I can do that? Currently I am using TextField to store the description. -
Django Guardian with Data Migration (adding Anonymous user to public group)
I'm trying to perform a data migration in an app. I would like to add the anonymous user (the django-guardian AnonymousUser) to a public group. Somehow the user does not exist when i'm running test. It does work with my develop. Thanks in advance. As it seems that the anonymous user is created on management init, I tried to import the module in apply_migration without success. # Generated by Django 4.1 on 2022-10-19 12:11 from django.db import migrations from guardian.utils import get_anonymous_user from recipebook.settings import PUBLIC_GROUP_NAME from django.contrib.auth.models import Group def apply_migration(apps, schema_editor): import guardian.management.__init__ public_group = Group.objects.get( name=PUBLIC_GROUP_NAME ) user = get_anonymous_user() user.groups.add(public_group) def revert_migration(apps, schema_editor): public_group = Group.objects.get( name=PUBLIC_GROUP_NAME ) user = get_anonymous_user() user.groups.remove(public_group) class Migration(migrations.Migration): dependencies = [ ('recipebook', '0031_recipenutrition_vitamine_b3'), ('guardian', '0001_initial'), ] operations = [ migrations.RunPython(apply_migration, revert_migration) ] -
Error "mysqlclient‑1.4.6‑cp39‑cp39‑win_amd64.whl" is not a supported wheel on this platform
I am trying to create Django backend and and I am getting this error while installing MySQL client how can I solve this issue?