Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: User Profile Update Form Only Showing One User's Data
I'm building an e-commerce website using Django, and I'm having trouble with updating user profiles. I want to display a list of users and provide a way to view and update each user's profile. However, I'm currently only able to see and update the profile of the logged-in user. Here is my current implementation: views.py: def user_list(request): users = CustomUser.objects.all() return render(request, 'useradmin/user_list.html', {'users': users}) @login_required def user_profile_update(request): try: profile = Profile.objects.get(user_name=request.user) except Profile.DoesNotExist: return render(request, 'useradmin/error.html', {'message': 'Profile does not exist.'}) if request.method == "POST": image = request.FILES.get("image") full_name = request.POST.get("full_name") phone = request.POST.get("phone") Address = request.POST.get("Address") diamond_user = request.POST.get("diamond_user") golden_user = request.POST.get("golden_user") if image: profile.image = image profile.full_name = full_name profile.phone = phone profile.Address = Address profile.diamond_user = diamond_user == 'on' # Checkbox values need special handling profile.golden_user = golden_user == 'on' profile.save() messages.success(request, "Profile updated successfully") return redirect("useradmin:user_profile_update") context = { "profile": profile } return render(request, 'useradmin/userprofile.html', context) urls.py: path('user_profile_update/', views.user_profile_update, name='user_profile_update'), path('user_list/', views.user_list, name='user_list'), user_list.html: {% extends 'useradmin/base.html' %} {% block content %} <h1>User List</h1> <ul> {% for user in users %} <li> {{ user.email }} ({{ user.first_name }} {{ user.last_name }}) <a href="{% url 'useradmin:user_profile_update' %}">View/Update</a> </li> {% empty %} <li>No users found.</li> {% endfor … -
Jitsi UI not being updated
I am using Jitsi Meet for video call in one of projects of mine. I cloned the project using link https://github.com/jitsi/jitsi-meet and connected with my react app and is working well.Now I want to change the UI of jitsi meet ,for this purpose I went to documentation ,I followed the steps of i changed into interface.config.js file and title.html file but they are not changed ,so then i build it using "make source-package " it gives me error: p: cannot stat 'build/close3.min.js.map': No such file or directory cp \ node_modules/@jitsi/rnnoise-wasm/dist/rnnoise.wasm \ libs cp -R \ node_modules/@jitsi/excalidraw/dist/excalidraw-assets \ libs/ cp \ react/features/stream-effects/virtual-background/vendor/tflite/.wasm \ libs cp \ react/features/stream-effects/virtual-background/vendor/models/.tflite \ libs cp \ node_modules/lib-jitsi-meet/dist/umd/lib-jitsi-meet.* \ libs cp \ node_modules/@matrix-org/olm/olm.wasm \ libs cp \ node_modules/@tensorflow/tfjs-backend-wasm/dist//*.wasm \ libs ./node_modules/.bin/sass css/main.scss css/all.bundle.css && \ ./node_modules/.bin/cleancss --skip-rebase css/all.bundle.css > css/all.css && \ rm css/all.bundle.css ([ ! -x deploy-local.sh ] || ./deploy-local.sh) cp \ node_modules/@vladmandic/human-models/models/blazeface-front.bin \ node_modules/@vladmandic/human-models/models/blazeface-front.json \ node_modules/@vladmandic/human-models/models/emotion.bin \ node_modules/@vladmandic/human-models/models/emotion.json \ libs mkdir -p source_package/jitsi-meet/css && \ Anyone help me in updating my UI? I wanted to change the UI of jitsi meet and it was unable to be done -
Should I place react files inside of venv directory when making django + react app?
So, I'm new to django and new to react but I thought I'd combine them to make a nice project with a frontend and backend separate. I plan to deploy the frontend on s3 and backend on ec2. Side question but please let me know if this is viable. I'm starting with making the backend template. However, it's recommended that I do my python development inside of a virtual environment, which I understand. Should my file structure be: AppName/ backend/ venv/ - set up django starting here - frontend/ - set up react - Or should I try to put everything inside of the venv. I tried to set it up based on a tutorial and ended up not understanding where anything is (https://www.geeksforgeeks.org/how-to-connect-django-with-reactjs/). Also, it was very unorganized. I'm now restarting and going based solely on documentation, which might be a better approach learning-wise. I think the separating structure is better because I could just upload the entire venv to ec2. Not sure how ec2 set up works but I'll get there eventually. Just wanted some insight to avoid having to restructure everything. Any and all information would be super helpful! -
django FormView modify fields before validation
Is there a proper way to modify the form fields before validating the data on a Class Based FormView. More specifically a CreateView. Is necessary to use Class Based views 'cause I'm throwing in a bunch of custom mixins: class Create(HtmxRequiredMixin, CreatedByMixin, HxFormValidationMixin, BaseMixin, CreateView): template_name = 'administration/form.html' model = Object form_class = Form success_url = reverse_lazy('object-list') hx_retarget = '#CREATE' base = 'object' views_list = ('create',) I used the CreatedByMixin in the DRF viewset for the api rest. it looks like: class CreatedByMixin: def create(self, request, *args, **kwargs): data = request.data.copy() if request.user.is_authenticated: data['created_by'] = request.user.id serializer = self.get_serializer(data=data) serializer.is_valid(raise_exception=True) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) I want a similar mixin for my CreateView but I'm not sure what is the proper method to override. Also, the HxFormValidationMixin already override the form_valid and form_invalid methods. -
Why is my Django app unable to find my URL pattern?
My Django project is run in Docker and I use Celery to handle queuing. When a user submits an audio file the system starts an asynchronous task(that transcribes the audio), continuously checks its progress, and updates the UI once the transcription is complete, with a download button. However I've been getting an error after the transcription completes but before the download button appears. The error indicates that it can't find the view that provides the completed transcript to the user. Here's my code. views.py: def initiate_transcription(request, session_id): file_name = request.session.get('uploaded_file_name') file_path = request.session.get('uploaded_file_path') if request.method == 'GET': if not file_name or not file_path: return redirect(reverse('transcribeSubmit')) if request.method == 'POST': try: if not file_name or not file_path: return redirect(reverse('transcribeSubmit')) audio_language = request.POST.get('audio_language') output_file_type = request.POST.get('output_file_type') if file_name and file_path: print(str("VIEW: "+session_id)) task = transcribe_file_task.delay(file_path, audio_language, output_file_type, 'ai_transcribe_output', session_id) return JsonResponse({'status': 'success', 'task_id': task.id}) except Exception as e: return JsonResponse({'status': 'error', 'error': 'No file uploaded'}) return render(request, 'transcribe/transcribe-complete-en.html') def check_task_status(request, session_id, task_id): task_result = AsyncResult(task_id) if task_result.ready(): transcribed_doc = TranscribedDocument.objects.get(id=session_id) return JsonResponse({ 'status': 'completed', 'output_file_url': transcribed_doc.output_file.url }) else: return JsonResponse({'status': 'pending'}) JS: form.addEventListener('submit', function(event) { event.preventDefault(); const transcribeField = document.querySelector('.transcribe-output-lang-select') const errorDiv = document.querySelector('.error-transcribe-div'); transcribeField.style.opacity = '0'; setTimeout(function() { transcribeField.style.display = 'none'; … -
Can I define a field in a django model to return data from another model that meets certain conditions?
I have a model for recipes. I have a model for reviews of those recipes. The recipe's author (chef) can select a specific review as their favorite. I think I've set the constraint up correctly to only allow one favorite review per recipe. Let's assume one favorite review per recipe. I would like to reference the one favorite review using the recipe model. Is this possible? Example template snippet below. {% for recipe in recipes %} <div> <h2>{{ recipe.name }}</h2> <p>{{ recipe.favoriteReview.content }} <small>by {{ recipe.favoriteReview.author }}</small></p> <p>Email the chef: {{ recipe.chef.email }}</p> </div> {% endfor %} Here's an example of the models but I feel like I've approached this from the wrong direction and I've hit a wall. # Models as example class User(AbstractUser): pass class Recipe(models.model): name = models.CharField(max_length=64) instructions = models.TextField(max_length=1000) chef = models.ForeignKey("User", on_delete=models.SET_NULL, related_name="recipes") #favoriteReview = The review with chefsFavorite=True and recipe matches this recipe class Review(models.model): author = models.ForeignKey("User", on_delete=models.SET_NULL, related_name="reviews") rating = models.DecimalField(max_digits=2, decimal_places=2) content = models.TextField(max_length=1000) chefsFavorite = models.Boolean(default="True") recipe = models.ForeignKey("Recipe", on_delete=models.CASCADE, related_name="recipes") class Meta: constraints = [ models.UniqueConstraint(fields=['recipe'], condition=models.Q(chefsFavorite=True), name="chefs_one_favorite_recipe_review" ] -
How to validate Post arguments in Django
I've seen plenty of solutions on how to validate Form field parameters, but I am not using Django templates or implementing the front-end in Django at all. I'm looking purely for server-side backend validation. Let's say I have @api_view(['POST']) def my_func(request): And I want the data to be something like: { "username" : <user>, "password" : <pw>, "age" : <age> } I want to validate that username and password are strings, perhaps with a minimum length requirement. And that age is a number, again, perhaps with other restrictions, such as min/max. Is there a standard way to do this? -
Find periodic task's next execution time in Celery Beat
I am creating PeriodicTasks for opening user an access to the next lesson using this code: task = PeriodicTask.objects.create( interval=enrolment.course.interval, name=f"enrolment_id: {enrolment.id}", task="courses.tasks.next_program", args=json.dumps([enrolment.id]), ) enrolment.task = task enrolment.save() How to get datetime next task will be ran? -
Add 'business context' to all views Django
I've got an app handling a store, with some view of Items that are sold there and some list of Employees there etc. Now, there will be the second (physical) store, and my application is not ready for handling more than one :) So to my models will be added Location model, and foreign keys added to Item and Employee... But my question is how to rebuild views ... So my view that lists all Items, should have added some filter on the top to select location and than filter list based on that selection... and Employee view the same (and all other the same).... So - having that filter there on the top, I should set some global ('session'?) variable, and based on that filter each view? (or add it in url parameters?? or any other way?) Please advise me how to do it an elegant way. -
Disable logging of `exc_info` when raising `BadRequest`?
When a Http404 is raised, the log provides the relevant information but not the details of the exception But when a BadRequest is raised, the log includes exc_info so it makes it look like something went wrong rather than standard error handling of bad requests. So is there a way to disable or modify this behavior? -
how to customize all-auth errors for mismatch passwords to othere languge?
class PasswordVerificationMixin(object): def clean(self): cleaned_data = super(PasswordVerificationMixin, self).clean() password1 = cleaned_data.get("password1") password2 = cleaned_data.get("password2") if (password1 and password2) and password1 != password2: self.add_error("password2", _("You must type the same password each time.")) return cleaned_data I want to override this class and make the error message to 'this a test' i am stuck i tried overriding it but nothing any help? I want to override this class and make the error message to 'this a test' i am stuck i tried overriding it but nothing any help? -
How to get csrfToken for front-end to submit logins in Django
I've read all the issues about this, but it's still not clear to me. I am not using Django templates to handle login functions (login, logout, changepassword, create user, etc). I tried POSTing to the accounts/login page with "username": <user>, "password": <password> But it also wants a CsrfViewMiddleware token. It's not clear to me where I get that. Does the front-end have to requrest it first from another endpoint? Is there some other way to do the CSR checking? -
CORS Policy Error with Specific Data in React and Django Application
CORS Policy Error with Specific Data in React and Django Application I'm experiencing an issue with CORS policy in my React frontend and Django backend application. The error message I'm receiving is: Access to fetch at backend URL' from origin 'frontend URL' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. I have configured all the CORS Configuration in settings.py MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', ] CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_METHODS = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'] CORS_ALLOW_HEADERS = [ 'accept', 'accept-encoding', 'authorization', 'content-type', 'dnt', 'origin', 'user-agent', 'x-csrftoken', 'x-requested-with',] Installed apps also 'corsheader' is added The problem is i am getting this issue for only one data not for all data for my views i added Decorators like: @csrf_exempt @require_http_methods(["OPTIONS", "POST"]) As it is working fine in Local,Development only for Staging i am getting this issue that to for only some data others are working fine -
custom storage-backend class not working as expected with s3, boto3 and django-storages
I am following this tutorial here from Michael Herman, trying to setup s3 storage for my django project and I am facing some issues right from the start of the tutorial. First, when I tried running the collectstatic command, I got this error: botocore.exceptions.ClientError: An error occurred (AccessDenied) when calling the PutObject operation: Access Denied I looked up a bit, and apparently you have to set AWS_DEFAULT_ACL = None and doing that fixed it. So now my static files were being uploaded to the s3 bucket when I ran collectstatic. But when I visited the webpages, the static images and stylesheets were not getting fetched as expected. I tried many different things at this point, but none of them worked. I typed the s3 object url in the browser and this was the error I was getting: <Error> <Code>AccessDenied</Code> <Message>Access Denied</Message> <RequestId>419CX01JK1CAKYCS<RequestId> <HostId>rB7y8qLl5a5G0I1LVx2lexUbJpcvnrdKIMZ3AVq69C81B3j4BRWZwLq5THNLINwSv6q5HFSAednN1yq2tRCQ6THuxEn+S/Kj</HostId> </Error> Now the next thing I did was to make all the bucket objects as public. The tutorial doesn't do this and I'm not sure if its a bad thing or not? Anyone please point out if it is. Using this answer, I set the Block all public access setting to off and also added a Bucket … -
Bootstrap modal does not trigger inside a django for loop
I want to attach a modal to all images. But for some reason the modal is not triggered and the entire page becomes un-clickable. I have made sure that all modals triggers and modal have a unique ID without any results. Can anyone see what I am doing wrong? {% for photo in user_photos %} <div class="image-container"> <div class="image-wrapper" data-bs-toggle="modal" data-bs-target="#photoModal{{photo.id}}"> <img src="{{ photo.photo.url }}" alt="Användarbilder"> {% if request.user == photo.user %} <form method = "POST"> {% csrf_token %} <i class="bi bi-x-lg profile_delete_photo" title="Radera" data-photoId = "{{photo.pk}}" data-url = "{% url 'profilepage_app:deletePhotoAjax' %}"></i> </form> {% endif %} </div> <span>Uppladdat: {{ photo.timesince }}</span> <!-- Modal --> <div class="modal fade" id="photoModal{{photo.id}}" tabindex="-1" aria-labelledby="photoModallabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h1 class="modal-title fs-5" id="photoModal{{photo.id}}Label">Modal title</h1> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> ... </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button> <button type="button" class="btn btn-primary">Save changes</button> </div> </div> </div> </div> </div> {% endfor %} I also have this for loop and modal in another page, but it works fine. {% for diary in user_diaries %} <tr> <td> <!--Diary title--> <a href="{{diary.get_absolute_url}}">{{diary.title|truncatechars:30}}</a> {% if request.user == user %} <div> <!--Dropdown--> <svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" type="button" id="dropdownMenuButton" data-bs-toggle="dropdown" aria-expanded="false" fill="currentColor" class="dropdown-toggle bi bi-three-dots-vertical" … -
Error while using django-vite-plugin and react
I am using django-vite-plugin and react for the frontend of my project. I followed the tutorial on https://react.dev/learn/add-react-to-an-existing-project and when testing using index.js I got the error '[vite] Internal server error: Failed to parse source for import analysis because the content contains invalid JS syntax. If you are using JSX, make sure to name the file with the .jsx or .tsx extension.' I would like to kindly ask for assistance solving this problem. I first tried this and got an error import { createRoot } from 'react-dom/client'; document.body.innerHTML = '<div id="app">JS working</div>'; const root = createRoot(document.getElementById('app')); root.render(<h1>Hello</h1>); However when I commented out the last line it worked. LIke this: import { createRoot } from 'react-dom/client'; document.body.innerHTML = '<div id="app">JS working</div>'; const root = createRoot(document.getElementById('app')); //root.render(<h1>Hello</h1>); My index.html is {% load vite %} <!DOCTYPE html> <html lang="en"> <head> <!--Other elements--> <!--Vite dev client for hmr (will not be displayed on production)--> {% vite %} {% vite 'newspaper/css/styles.css' 'newspaper/js/main.js' %} </head> <body> <!--Page content--> </body> </html> My vite.config.js is //vite.config.js import { defineConfig } from 'vite' import { djangoVitePlugin } from 'django-vite-plugin' import react from '@vitejs/plugin-react' export default defineConfig({ plugins: [ djangoVitePlugin([ 'newspaper/js/app.js', 'newspaper/css/style.css', ]), react() ], }); My package.json is { … -
Drop duplicates when quering multiple tables in Django
I have a custom manager with search, which orders return results by rank: class MyManager(models.Manager): def search(self, query, fa, fb=None, fc=None, fd=None, qs=None): if not qs: qs = self.get_queryset() try: if not (1 in [c in query for c in '&|()!*:"']): query = " & ".join([f"{q}:*" for q in query.split()]) vector = SearchVector(*fa, weight="A", config="english") if fb: vector += SearchVector(*fb, weight="B", config="english") if fc: vector += SearchVector(*fc, weight="C", config="english") if fd: vector += SearchVector(*fd, weight="D", config="english") query = SearchQuery(query, search_type="raw") qs = ( qs.annotate(search=vector, rank=SearchRank(vector, query)) .filter(search=query) .order_by("-rank", "-id") .distinct("rank", "id") ) qs.count() # Trigger exception except (ProgrammingError, UnboundLocalError): qs = qs.none() return qs But when I try searching on related fields, it still returns duplicate results: class Case(models.Model): machine = models.ForeignKey(Machine, on_delete=models.CASCADE) user = models.ForeignKey(Profile, on_delete=models.SET_NULL) hashtags = models.CharField(max_length=255) closed = models.BooleanField(default=False) objects = MyManager() class CaseProgress(models.Model): case = models.ForeignKey(Case, on_delete=models.CASCADE) desc = models.TextField() class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.SET_NULL, null=True) class CaseListView(ListView): model = Case def get_queryset(self): query = self.request.GET.get("query", None) show_closed = ( True if self.request.GET.get("show_closed", False) == "true" else False ) if query: if not show_closed: qs = self.model.objects.filter(closed=False) else: qs = self.model.objects.all() fa = ( "id", "machine__serial_number", "machine__company__name", "user__user__first_name", "user__user__last_name", ) fb = ("hashtags",) fc … -
Coloured output from native Django test runner
I'm trying to get a colored output (red or green) when running my Django tests with the native Django test runner. I'm running a poetry virtualenv (python 3.11.6) with Django (5.0.3) and colorama (0.4.6) in a zsh on MacOS but the output remains colourless. Following the Django documentation, I've set export DJANGO_COLORS="error=yellow/blue,blink;notice=magenta" in my zsh before calling python manage.py test apps.myapp. Yet, the output remains colourless. Same result when adding the --force-color option. However, spinning up the same virtualenv and executing from colorama import Fore, Style print(Fore.RED + 'This is red text' + Style.RESET_ALL) returns a red text (as expected). What do I have to do to get a colored output from the native Django test runner without switching to a different one? -
init_fs_encoding during deploying django app to apache
i'm trying for hours to deploy a django app on an apache2 and still get following error: PYTHONHOME = '/home/rickmanns/bar/bar/djenv' PYTHONPATH = (not set) program name = 'python3' isolated = 0 environment = 1 user site = 1 safe_path = 0 import site = 1 is in build tree = 0 stdlib dir = '/home/rickmanns/bar/bar/djenv/lib/python3.11' sys._base_executable = '/usr/bin/python3' sys.base_prefix = '/home/rickmanns/bar/bar/djenv' sys.base_exec_prefix = '/home/rickmanns/bar/bar/djenv' sys.platlibdir = 'lib' sys.executable = '/usr/bin/python3' sys.prefix = '/home/rickmanns/bar/bar/djenv' sys.exec_prefix = '/home/rickmanns/bar/bar/djenv' sys.path = [ '/home/rickmanns/bar/bar/djenv/lib/python311.zip', '/home/rickmanns/bar/bar/djenv/lib/python3.11', '/home/rickmanns/bar/bar/djenv/lib/python3.11/lib-dynload', ] Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding Python runtime state: core initialized ModuleNotFoundError: No module named 'encodings' My Apache config looks like following: Alias /static /home/rickmanns/bar/static <Directory /home/user/myproject/static> Require all granted </Directory> <Directory /home/rickmanns/bar/bar> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess bar python-path=/home/rickmanns/bar python-home=/home/rickmanns/bar/djenv WSGIProcessGroup bar WSGIScriptAlias / /home/rickmanns/bar/bar/wsgi.py If it's helpful - i followed this tutorial: https://pimylifeup.com/raspberry-pi-django/ Thanks to everyone! -
django probleme with image in shared hosting
I have an image problem that displays locally but not on shared hosting. The site works well in hosting , the custom js and css files are ok. In my Django template, I have this image: <div class="col-sm-3 order-3 order-sm-3"> <!-- form pub --> <img class="img-thumbnail" src="{% static 'img/exemple_banner_01.png' %}" alt="..." /> </div> This image is in: static/img/myimage.png I do python manage.py collectstatic After that, this image is found here: collectstatic/img/myimage_01.ze25a48a4c2.png In settings file: STATIC_URL = 'static/' STATICFILES_DIRS = [str(BASE_DIR.joinpath('static'))] STATIC_ROOT = str(BASE_DIR.joinpath('staticfiles')) STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage My css and javascript files are ok. When displaying, my image doesn't show up. mysite.com/static/img/myimage_01.ze25a48a4c2.png "Not Found The requested URL was not found on this server." I tried to put in the settings: /home/user/public_html/myapp/static but it gives me a 500 error. I should add that I'm in debug False mode. Thank for help -
Case Insensitivity Issue with Tag Suggestions in Wagtail
I'm studying Wagtail and encountered the following issue when setting up tags. I added the following models: @register_snippet class BlogTag(TagBase): free_tagging = False name = models.CharField(max_length=25, unique=True) slug = models.SlugField(max_length=255, unique=True, blank=True) class Meta: verbose_name = "blog tag" verbose_name_plural = "blog tags" class TaggedBlog(ItemBase): tag = models.ForeignKey( BlogTag, related_name="tagged_blogs", on_delete=models.CASCADE ) content_object = ParentalKey( 'home.BlogPage', on_delete=models.CASCADE, related_name='tagged_items' ) I enabled the setting TAGGIT_CASE_INSENSITIVE = True. However, when a user fills in the tags while creating a page, the case is still taken into account - if the user enters a word in lowercase, options from the dropdown list do not appear. Here is the model, if it matters: class BlogPage(Page): tags = ClusterTaggableManager(through=TaggedBlog, blank=True) date = models.DateField("Мы это написали:") author = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True, related_name='blog_pages') body = StreamField([ ('heading', blocks.CharBlock(form_classname="title", label="Заголовок")), ('paragraph', blocks.RichTextBlock(label="Текст")), ('image', ImageChooserBlock(label="Изображение")), ('quote', blocks.BlockQuoteBlock(min_length='20', label="Цитата")), ('media', EmbedBlock(label="Ссылка на видео")), ], verbose_name='Содержимое') content_panels = Page.content_panels + [ FieldPanel('date'), FieldPanel('body'), FieldPanel('slug', permission='superuser'), FieldPanel('tags'), ] edit_handler = TabbedInterface([ ObjectList(content_panels, heading='Центр управления постами'), ObjectList(Page.promote_panels, heading='Promote', permission='superuser'), ]) def _get_unique_slug(self): slug = slugify(self.title) unique_slug = slug num = 1 while Page.objects.filter(slug=unique_slug).exists(): unique_slug = '{}-{}'.format(slug, num) num += 1 return unique_slug def save(self, *args, **kwargs): self.slug = self._get_unique_slug() super().save(*args, **kwargs) Please tell … -
Django is randomly ignoring certain days when I try to bulk_create. How do I solve this? How does this even happen?
How does Django randomly skip days when trying to bulk_create? The dataset is a CSV exported via a third party tool from a MSSQL Server. Exhibit 1 - Data from my database: Note the whole 2024-06-13 is missing. Exhibit 2 - Data dump from my dataframe: When I look at my pandas dataframe, there was data for 2024-06-13. So reading the CSV and parsing the date works. At first, I thought the issue was using too much memory to bulk_create so I tried chunking. The problem still remained. But if it was a memory problem, then it wouldn't so cleanly eliminate that day without affecting the other days around it. The session start/stop times correspond with when the shop opens and closes on the 12th and 14th. It's not the only day that randomly disappeared. There are other days before this as well that have vanished. Also, the last possible import date was 2024-06-24. After that, it won't import any more sessions that exists in my dataframe. I tried both SQLite and Postgres to no avail in case it was a database issue. This is how it's imported from my dataframe via DjangoORM: sessions = [Session(**row) for row in df.to_dict(orient='records')] … -
What is the correct way for implementing Hyphenopoly?
I'm having trouble implementing Hyphenopoly (https://github.com/mnater/Hyphenopoly) on a Django project. Sometimes it seems to work fine, sometimes not. Besides, on mobile browser the result are unpleasant, since hyphens appears in a pretty inconsistent fashion (or doesn't at all) on elements with italian language. Further, I cannot understand the documentation provided. My fault. Herein I report part of the directory structure of the project As you can see, and for what I understood, I loaded only few files from the original library, in order to hyphenate italian and english pieces of text (separated or mixed). The main language is still en, since I defined it in the lang attribute of the html element; for each element featuring italian content, I specified the language attribute accordingly (for mixed content, I used spans). In the head element of my base.html: <script src="{% static './hyphens/Hyphenopoly_Loader.js' %}"></script> <script src="{% static 'HyphenConfig.js' %}"></script> The HyphenConfig.js file, instead: $(document).ready(function() { var Hyphenopoly = { require: { 'en-us': 'ALL', 'en': 'ALL', 'it': 'ALL' }, paths: { patterndir: "./hyphens/patterns/", maindir: "./hyphens/" }, setup: { selectors: { '.hyphenate': { compound: "all", leftmin: 0, rightmin: 0, minWordLength: 4 } } } }; }); I also defined the hyphenate class in the … -
Django is unable to send email out even though conf is correct
Django is unable to send email out. But https://www.smtper.net/ was able to send a test email with same exact settings, user, pass. What do I need do more in django to send email out? settings.py ## #environment variables from .env. from dotenv import load_dotenv load_dotenv() NOREPLYEMAIL = os.getenv('NOREPLYEMAIL') NOREPLYEMAILPASS = os.getenv('NOREPLYEMAILPASS') ### Email config EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' EMAIL_HOST = 'smtppro.zoho.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = NOREPLYEMAIL EMAIL_HOST_PASSWORD = NOREPLYEMAILPASS DEFAULT_FROM_EMAIL = NOREPLYEMAIL view.py # using https://docs.djangoproject.com/en/5.0/topics/email/ @csrf_protect def test(request): testemail = EmailMessage( "Hello", #subject "Body goes here", #message body NOREPLYEMAIL, #from ["mygmail@gmail.com",], #to reply_to=[NOREPLYEMAIL], headers={"Message-ID": "test"}, ) testemail.send() -
Django - the date field in the data entered form is reset during editing
I made a model, form and views. I added some data via form. And then when i want editing, all fields are full but datefield is empty. I want to see date which i added before. But nothing. I use all ai solutions also javascript, jquery, but nothing. How can i solve this problem. I have model like this and class Cilt(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="Kullanıcı") birth_place = models.CharField(max_length=200, blank=True, null=True, verbose_name="Birth Place") birth_date = models.DateField(blank=True, null=True, verbose_name="Birth date") def __str__(self): return f"{self.user.username}" forms.py class CiltForm(forms.ModelForm): class Meta: model = Cilt exclude = ['user'] fields = '__all__' widgets = { 'birth_place': forms.TextInput(attrs={'class': 'form-control'}), 'birth_date': forms.DateInput(attrs={'class': 'form-control', 'type': 'date'}), def __init__(self, *args, **kwargs): super(CiltForm, self).__init__(*args, **kwargs) instance = kwargs.get('instance', None) if instance: initial_date = instance.ucuk_en_son_cikis_tarihi self.fields['birth_date'].initial = initial_date self.fields['birth_date'].widget = forms.DateInput(attrs={'class': 'form-control', 'type': 'date'}) edit views def cilt_duzenle(request, user_id): ciltler = get_object_or_404(Cilt, user__id=user_id) if request.method == 'POST': form = CiltForm(request.POST, instance=ciltler) if form.is_valid(): form.save() return redirect('cilt_detay', user_id=user_id) else: form = CiltForm(instance=ciltler) return render(request, 'cilt/cilt_duzenle.html', {'form': form})