Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django custom field sorting
I have a problem in my django, I want to sort with my custom fields (get_total_opened, get_total_reply and the get_total_email_sent) in my serializer: class PersonListSerializer(serializers.ModelSerializer): org = OrgSerializer(many=False) # prompts = PromptResponseSerializer(read_only=True, many=True) # emails = EmailSerializer(read_only=True, many=True) custom_fields = PersonCustomFieldValueSerializer(many=True) tags = TagSerializer(many=True, default=[]) total_click_count = serializers.SerializerMethodField() total_opened = serializers.SerializerMethodField() total_reply = serializers.SerializerMethodField() total_email_sent = serializers.SerializerMethodField() scheduled_emails = serializers.SerializerMethodField() class Meta: model = Person fields = [ "id", "first_name", "last_name", "job_title", "company_name", "work_email", "company_website", "sent_emails", "last_contacted", "next_scheduled_email", "custom_fields", "org", "tags", "total_click_count", "total_opened", "total_reply", "total_email_sent", "got_data", "force_enable", "assigned_user", "status", "person_city", "state", "industry", "phone", "linkedin", "scheduled_emails", ] def get_scheduled_emails(self, obj): return EmailSerializer(obj.get_scheduled_emails(), many=True).data def get_user_created_emails(self, _obj): return _obj.emails.filter(created_by=self.context["request"].user) def get_total_click_count(self, obj): total_click_count = sum( click_count or 0 for email in self.get_user_created_emails(obj) for click_count in email.click_tracking.values_list( "click_count", flat=True ) ) return total_click_count def get_total_opened(self, obj): opened_emails = [ email for email in self.get_user_created_emails(obj) if hasattr(email, "trackings") and email.trackings.opened ] return len(opened_emails) def get_total_reply(self, obj): total_reply_count = ( self.get_user_created_emails(obj).aggregate( total_reply_count=Sum("reply_count__count") )["total_reply_count"] or 0 ) return total_reply_count def get_total_email_sent(self, obj): sent_email_count = obj.emails.filter( status=0, created_by=self.context["request"].user ).count() return sent_email_count and now I am having a problem on returning a sort from api, I have this full code on my modelviewset below but it doesn't work. … -
Uploading large file to GCS with django and django-storages -- direct or multi-part uploads?
I'm creating a django application that uploads multimedia to Google Cloud Storage using django-storages. My application is running on Google App Engine. Right now I'm having trouble with models that contain a large number of images -- for example, some of my models contain several 4K images, and at 25MB/ea I'm easily hitting hundreds of MB per save operation. django-storages is working great for smaller operations, but larger operations are causing issues. I'm currently getting an HTTP 413 error on larger save operations -- my app is POSTing about 100 MB, and Google App Engine's limit is 32MB. So my question is: to get around the limit, is it possible to make multiple POST requests using django-storages? Like, if my model has 4x 4K images, can I upload them each in a sequential upload? I've also read that I should upload files "directly" to GCS -- is it possible to do a "direct" upload using django? How would I go about doing that? thanks! -
How to create callback page for oauth with nextjs with a django grapql backend
I'd like to give some context to the setup I have going on. I'm creating a software web application and below is the setup: Backend - Django with a GraphQL API using graphene. Frontend - NextJS (/app directory) with Apollo GraphQL to speak to the backend. My app will allow users to link their accounts to eBay using OAuth. I have attached how I envisage my flow working: The issue I am running into is on the /ebay-callback page. It is making multiple calls to the GraphQL API and then for some reason it fails redirect as the compiler fails (although not sure if the compiler issue is actually related). The code for my callback page is as follows: 'use client' import { gql, useMutation } from '@apollo/client'; import { useRouter, useSearchParams } from 'next/navigation'; import { useEffect } from 'react'; const INITIATE_OAUTH_GET_ACCESS_TOKEN = gql` mutation InitiateOauthGetAccessToken($name: String!, $code: String!) { initiateOauthGetAccessToken(code: $code, name: $name) { success ebayAccount { id } } } `; export default function EbayCallbackPage() { const router = useRouter(); const searchParams = useSearchParams(); const [initiateOauthGetAccessToken] = useMutation(INITIATE_OAUTH_GET_ACCESS_TOKEN); useEffect(() => { const handleOAuth = async () => { console.log(searchParams); const code = searchParams.get('code'); const state = searchParams.get('state'); … -
unable bring footer down in wagtail and in Django html
In Django, if the footer renders correctly on sub-pages but not on the main page, you should examine the main page template and related files. Check for potential issues in the HTML structure, template blocks Verify that the main page correctly extends the base template and includes the footer within the appropriate block. Additionally, inspect any conditional logic or specific settings in the footer.html file that may affect its rendering. Ensure consistency in the template hierarchy and investigate any page-specific configurations that might impact the footer display. By addressing these aspects, you can troubleshoot and resolve the discrepancy in footer rendering. <section class="py-4 mt-lg-5 mt-0" style='background-color: #814EBF; background-image: url("{% static 'images/contact-overlay.png' %}");'> <div class="container"> <div class="row align-items-center"> <div class="col-lg-8 text-lg-left text-center"> <h2 class="h2 cc-contact-footer-h2"> Global CTA Title </h2> <p class="cc-contact-footer-p mb-0"> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Veniam laboriosam consequatur saepe. </p> </div> <div class="col-lg-4 text-lg-right text-center"> <a href="@todo" class="btn btn-light btn-lg mt-lg-0 mt-3"> @todo </a> </div> </div> </div> </section> <footer class="bg-dark py-4 text-light text-md-left text-center cc-footer"> <div class="container"> <div class=" row mx-lg-n3"> <div class="px-lg-3 col-lg-3 col-md-6 col-sm-12"> <div class="cc-footer-title">Links</div> {% for i in "123" %} <a class="cc-footer-link-lg d-block" href="@todo"> Link #{{i}} </a> {% endfor %} </div> <div … -
Problem when trying to fill out a django form with MultiSelectField field
When filling in the field and clicking send, the message "Make sure the value has a maximum of 5 characters (it has 10) appears." I've already tried several manipulations in models.py but nothing worked. I need this field to accept more than one value selected by the user to be saved in the database.I don't think I know where to move. models.py: `from django.db import models from django.contrib.auth.models import AbstractUser from courses.models import CourseCategory from multiselectfield import MultiSelectField class CustomUser(AbstractUser): areas_of_interest_choices = ( ('TI', 'Tecnologia da Informação'), ('ADM', 'Administração'), ('CTB', 'Contabilidade'), ('EC', 'Economia'), ('FI', 'Finanças'), ('SA', 'Saúde'), ('LI', 'Linguagens'), ('GA', 'Gastronomia'), ) escolaridade_choices = ( ('FC', 'Fundamental Completo'), ('FI', 'Fundamental Incompleto'), ('MC', 'Médio Completo'), ('MI', 'Médio Incompleto'), ('SC', 'Superior Completo'), ('SI', 'Superior Incompleto') ) full_name = models.CharField(max_length=50, null=False, blank=False) cpf = models.CharField(max_length=11, verbose_name='CPF', blank=False, null=False) date_of_birth = models.DateField(blank=True, null=True, verbose_name='Data de Nascimento') email = models.EmailField(max_length=100, blank=False, null=False) telephone = models.CharField(max_length=11, blank=False, null=False, verbose_name='Telefone') zip_code = models.CharField(max_length=8, blank=False, null=False, verbose_name='CEP') education = models.CharField(max_length=2, choices=escolaridade_choices, verbose_name='Escolaridade') areas_of_interest = MultiSelectField(blank=True, null=True, max_choices=3, max_length=5,choices=areas_of_interest_choices) def __str__(self): return self.username ` forms.py: `from django.contrib.auth.forms import UserCreationForm, UserChangeForm from .models import CustomUser, CourseCategory from django import forms class CustomUserCreationForm(UserCreationForm): class Meta: model = CustomUser fields = ("username", … -
Why would a check constraint be violated on a cascade delete?
When I delete an object ('item') in my Django app, a related object (in another table) that points to it via a foreign key should also get deleted due to its "on_delete=models.CASCADE" setting. But the cascade delete is failing because of a check constraint on the related model: MySQLdb.OperationalError: (3819, "Check constraint 'item_or_container' is violated.") My question is, why would a check constraint be triggered on a delete? Does Django modify the record somehow before deletion? The record in question does pass the constraint, and if I just delete that record directly it works as expected; it only fails during a cascade delete. The "violated" constraint is as follows: models.CheckConstraint(check=Q(item__isnull=False) ^ Q(is_container=True), name='item_or_container') (Which is an XOR ensuring that an object can EITHER have an assigned item OR be a container - not both.) My expectation is that both records should simply be deleted. Thank you for your help! -
I can't find the cause of the errors UserWarning: {% csrf_token %} was used in the template but the context did not provide a value
**My code should implement the function of user registration when entering non-existing data in the database, and when entering already existing data, the account is logged in. ** views.py: from django.http import HttpResponse, HttpResponseNotFound from django.shortcuts import redirect, render from django.template import RequestContext from django.template.loader import render_to_string from .forms import LoginForm from .models import user def register_view(request): if request.method == 'POST': form = LoginForm(request.POST) if form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password'] if not user.objects.filter(username=username).exists(): user.objects.create_user(username=username, password=password) return redirect('login') else: # Здесь вы можете выдать сообщение о том, что пользователь с таким именем уже существует return render(request, 'main/index.html', {'form': form}) else: form = LoginForm() return render(request, 'index.html', {'form': form}) index.html: <form class="login", method="post"> {% csrf_token %} <div class="auth__form"> <input class="username__email" type="text" name="username" placeholder="Имя пользователя" autocomplete="off", maxlength="30", minlength="2"> </div> <div> <input class="user__password" type="password" name="password" placeholder="Пароль" autocomplete="off", minlength="10"> </div> <button class="enter__btn" type="submit">Войти</button> <div class="auth__footer"> <div class="auth__label"> Ещё нет аккаунта? <a class="create__pass" href="">Создать</a> </div> </div> </form>``` When running the local server, it displays the warning UserWarning: A {% csrf_token %} was used in a template, but the context did not provide the value. When entering data into a form, it displays the error: Forbidden (CSRF token missing.): / I can't understand why these … -
How to Remove the Option to Add Users as Superusers to a Group in Wagtail
In my Wagtail project, I have a group that is allowed to add new users to the system. However, users belonging to this group can add others as superusers. How can I disable the option for this group to add users as superusers? Remove Admnistrador -
Dockerized react app cant communicate with dockerized django app
I have created a django app running at https://localhost:8000 using sslserver with self-signed certificates. My react app running at https://localhost:8000 also with self-signed certificates. When i run those two in a terminal both of them running perfectly and they communicate with each other. My problem is that when i try to run those two from docker desktop when i make a call from the frontend to the backend returns: 2024-01-12 21:43:00 Proxy error: Could not proxy request /main.dd206638be0188052640.hot-update.json from localhost:3000 to https://localhost:8000/. I should mention that when i make a call to the backend with Postman it runs normaly. Django settings.py: ALLOWED_HOSTS = [ 'localhost' # Provide the host that the server allows. ] # Config for CORS-Headers. CORS_ALLOWED_ORIGINS = [ # Provide frontend address. "https://localhost:3000" ] React package.json: "proxy": "https://localhost:8000", docker-compose.yml version: '3.10' services: django-backend: container_name: proxmox-project-backend build: context: ./django-backend dockerfile: Dockerfile image: django-backend:0.0.1 ports: - '8000:8000' react-frontend: container_name: proxmox-project-frontend build: context: ./react-frontend dockerfile: Dockerfile image: react-frontend:0.0.1 ports: - '3000:3000' stdin_open: true tty: true environment: - HTTPS=true - SSL_CRT_FILE=/app/ssl/react.crt - SSL_KEY_FILE=/app/ssl/react.key -
Overriding delete method in django model
I have a Page model that during the saving of objects calls the print within the save method. However, when objects are being deleted, no prints are triggered, and it seems like the delete method is never being called. How should I override the default delete method then? class Page(models.Model): image = models.ImageField() number = models.PositiveIntegerField(default=0, blank=True, null=True) chapter = models.ForeignKey(Chapter, on_delete=models.CASCADE) def get_upload_path(self, filename): work_slug = self.chapter.volume.work.slug translator_name = slugify(self.chapter.volume.translator) volume_number = self.chapter.volume.number chapter_number = self.chapter.number name, extension = filename.rsplit('.', 1) return f'media/{work_slug}/{translator_name}/volumes/volume-{volume_number}/chapters/chapter-{chapter_number}/page-{self.number}.{extension}' def save(self, *args, **kwargs): if not self.pk: last_page = self.chapter.page_set.last() if last_page: self.number = last_page.number + 1 self.image.name = self.get_upload_path(self.image.name) self.image.storage = s3 print(f"Saving Page with image: {self.image.name}") super().save(*args, **kwargs) def delete(self, *args, **kwargs): print(f"Deleting Page with image: {self.image.name}") image_name = self.image.name try: s3.delete(image_name) print(f"Successfully deleted from S3: {image_name}") except Exception as e: print(f"Error deleting from S3: {e}") super().delete(*args, **kwargs) -
How to use Django's ORM to update the value for multiple keys in a JsonField using .update() method?
I have a model field I am trying to update using Django's .update() method. This field is a JsonField. I am typically saving a dictionary in this field. e.g. {"test": "yes", "prod": "no"} Here is the model: class Question(models.Model): # {"test": "yes", "prod": "no"} extra_data = models.JSONField(default=dict, null=True, blank=True) I am able to update a key inside the dictionary using this query (which works fine by the way): Question.filter(id="123").update(meta_data=Func( F("extra_data"), Value(["test"]), Value("no", JSONField()), function="jsonb_set", )) The question now is, is there a way I can update the multiple keys at once(in my own case, two) using the .update() as shown in the above query? I want to use the .update() method instead of .save() to achieve this so I can avoid calling a post_save function. -
getting the media url right in django and nginx (I must be doing it wrong in nginx)
I am stuck with a server 500 server error at a form only when it is about to save the pictures (the rest of the forms belonging to other models are saved in the db ok) I didn't have the problem in development, but I think I know why I am not coming on, because there is an extra configuration for media URL, and that is nginx Could anyone tell me how to to this well? I have in my production server pulled the github app at: /home/boards/myapp In the settings.py: MEDIA_ROOT = BASE_DIR /'media' MEDIA_URL = "/media/" In urls.py ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) In Nginx (Here is where I must be screwing up because I don't nginx in development and it works well) location /media/ { alias /home/boards/media/; } Well, this is the model but like I said, it works great in development class Photos(models.Model): def user_directory_path(instance, filename): # file will be uploaded to MEDIA_ROOT/user_<id>/<filename> return 'user_{0}/{1}'.format(instance.user, filename) images = ResizedImageField(size=[500, 300], upload_to=user_directory_path, blank=True, null=True) I am running gunicorn, nginx and supervisor. If I make changes to nginx, do I have to reload, restart etc or does supervisor take care of that? -
Pydantic: pass the entire dataset to a nested field
I am using django, django-ninja framework to replace some of my apis ( written in drf, as it is becoming more like a boilerplate codebase ). Now while transforming some legacy api, I need to follow the old structure, so the client side doesn't face any issue. This is just the backstory. I have two separate models. class Author(models.Model): username = models.CharField(...) email = models.CharField(...) ... # Other fields class Blog(models.Model): title = models.CharField(...) text = models.CharField(...) tags = models.CharField(...) author = models.ForeignKey(...) ... # Other fields The structure written in django rest framework serializer class BlogBaseSerializer(serializers.Serializer): class Meta: model = Blog exclude = ["author"] class AuthorSerializer(serializers.Serializer): class Meta: model = Author fields = "__all__" class BlogSerializer(serializers.Serializer): blog = BlogBaseSerializer(source="*") author = AuthorSerializer() In viewset the following queryset will be passed class BlogViewSet(viewsets.GenericViewSet, ListViewMixin): queryset = Blog.objects.all() serializer_class = BlogSerializer ... # Other config So, as I am switching to django-ninja which uses pydantic for schema generation. I have the following code for pydantic schema AuthorSchema = create_schema(Author, exclude=["updated", "date_joined"]) class BlogBaseSchema(ModelSchema): class Meta: model = Blog exclude = ["author", ] class BlogSchema(Schema): blog: BlogBaseSchema author: AuthorSchema But as you can see, drf serializer has a parameter called source, where … -
Django paginate table without get the entire table
there is some way to paginate a django model table without get all the db? Something like Db => 100 records => [id:0...,id:1...,id:n] Query => ...?page=1 Return => [id:0...,id:1...,id:25] Query => ...?page=2 Return => [id:26...,id:27...,id:50] -
Daphne Docker Django ModuleNotFoundError: No module named 'yourproject'
When I try to run daphne in docker I have this problem. I have no idea to fix it :) I use docker compose to build it. my project -nginx -redis -daphne -django channels ~/pyprj/Django# docker logs 3517329befc9 New pypi version: 0.2.0.2 (current: 0.1.8.7) | pip install -U g4f Traceback (most recent call last): File "/usr/local/bin/daphne", line 8, in <module> sys.exit(CommandLineInterface.entrypoint()) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/daphne/cli.py", line 171, in entrypoint cls().run(sys.argv[1:]) File "/usr/local/lib/python3.12/site-packages/daphne/cli.py", line 233, in run application = import_by_path(args.application) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/daphne/utils.py", line 12, in import_by_path target = importlib.import_module(module_path) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/importlib/__init__.py", line 90, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1387, in _gcd_import File "<frozen importlib._bootstrap>", line 1360, in _find_and_load File "<frozen importlib._bootstrap>", line 1331, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 935, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 994, in exec_module File "<frozen importlib._bootstrap>", line 488, in _call_with_frames_removed File "/Django/gptweb/gptweb/asgi.py", line 16, in <module> django_asgi_app = get_asgi_application() ^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/django/core/asgi.py", line 12, in get_asgi_application django.setup(set_prefix=False) File "/usr/local/lib/python3.12/site-packages/django/__init__.py", line 19, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) ^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/django/conf/__init__.py", line 89, in __getattr__ self._setup(name) File "/usr/local/lib/python3.12/site-packages/django/conf/__init__.py", line 76, in _setup self._wrapped = Settings(settings_module) ^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/django/conf/__init__.py", line 190, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/importlib/__init__.py", line 90, in … -
Scheduling tasks with Django
I have a site I'm working on that I'd like to add an option to sign up for a weekly newsletter type thing. I did a lot of looking around, and I was wondering if the python schedule library is an okay thing to use for this (https://schedule.readthedocs.io/en/stable/). Could I have my website running and then a scheduler running in tandem that runs a django management command to send emails to those who sign up? I'm fairly new to this kind of thing, so I just wanted to check since I couldn't really find any info of other people doing this. I have a script that sends emails and when I use the scheduler to send them every however many minutes it works, but I'm just wondering about the scalability of this. I think I'd like to avoid using something like celery since it seems like sort of a big solution to a small problem. -
Issue with Editing Custom User Models in Wagtail Projec
I have a custom user model in my Wagtail project. I created this custom model following the guidelines in the Wagtail documentation (https://docs.wagtail.org/en/stable/advanced_topics/customisation/custom_user_models.html#custom-user-forms-example). However, in the administrative part, when editing a user, I am unable to make edits to a user, and only a button to add a new user appears. models.py class User(AbstractUser): """ Default custom user model for SciELO Content Manager . If adding fields that need to be filled at user signup, check forms.SignupForm and forms.SocialSignupForms accordingly. """ #: First and last name do not cover name patterns around the globe name = models.CharField(_("Name of User"), blank=True, max_length=255) first_name = models.CharField(max_length=150, blank=True, verbose_name="first name") last_name = models.CharField(max_length=150, blank=True, verbose_name="last name") journal = models.ForeignKey("journal.Journal", on_delete=models.SET_NULL, verbose_name=_("Journal"), null=True, blank=True) collection = models.ManyToManyField("collection.Collection", verbose_name=_("Collection"), blank=True) def get_absolute_url(self): """Get url for user's detail view. Returns: str: URL for user detail. """ return reverse("users:detail", kwargs={"username": self.username}) forms.py from django import forms from django.utils.translation import gettext_lazy as _ from wagtail.users.forms import UserEditForm, UserCreationForm from collection.models import Collection from journal.models import Journal class CustomUserEditForm(UserEditForm): journal = forms.ModelChoiceField(queryset=Journal.objects, required=False, label=_("Journal")) collection = forms.ModelMultipleChoiceField(queryset=Collection.objects.filter(is_active=True), required=True, label=_("Collection")) class CustomUserCreationForm(UserCreationForm): journal = forms.ModelChoiceField(queryset=Journal.objects, required=False, label=_("Journal")) collection = forms.ModelMultipleChoiceField(queryset=Collection.objects.filter(is_active=True), required=True, label=_("Collection")) base.py WAGTAIL_USER_EDIT_FORM = 'core.users.forms.CustomUserEditForm' WAGTAIL_USER_CREATION_FORM = 'core.users.forms.CustomUserCreationForm' WAGTAIL_USER_CUSTOM_FIELDS … -
Getting this error : FOREIGN KEY constraint failed in my django application
I have created a BaseUser model to create users and i have also created a Profile for every single user when new user gets created. But when i try to update the information's or try to delete the specific user from the admin panel i get this error :- [12/Jan/2024 15:05:29] "GET /admin/accounts/baseuser/16/change/ HTTP/1.1" 200 17895 [12/Jan/2024 15:05:30] "GET /static/admin/js/jquery.init.js HTTP/1.1" 200 347 Not Found: /favicon.ico Internal Server Error: /admin/accounts/baseuser/16/change/ Traceback (most recent call last): File "/home/mohit/okk/django_pinterest/myenv/lib/python3.8/site-packages/django/db/backends/base/base.py", line 313, in _commit return self.connection.commit() sqlite3.IntegrityError: FOREIGN KEY constraint failed The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/mohit/okk/django_pinterest/myenv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/home/mohit/okk/django_pinterest/myenv/lib/python3.8/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/mohit/okk/django_pinterest/myenv/lib/python3.8/site-packages/django/contrib/admin/options.py", line 688, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "/home/mohit/okk/django_pinterest/myenv/lib/python3.8/site-packages/django/utils/decorators.py", line 134, in _wrapper_view response = view_func(request, *args, **kwargs) File "/home/mohit/okk/django_pinterest/myenv/lib/python3.8/site-packages/django/views/decorators/cache.py", line 62, in _wrapper_view_func response = view_func(request, *args, **kwargs) File "/home/mohit/okk/django_pinterest/myenv/lib/python3.8/site-packages/django/contrib/admin/sites.py", line 242, in inner return view(request, *args, **kwargs) File "/home/mohit/okk/django_pinterest/myenv/lib/python3.8/site-packages/django/contrib/admin/options.py", line 1889, in change_view return self.changeform_view(request, object_id, form_url, extra_context) File "/home/mohit/okk/django_pinterest/myenv/lib/python3.8/site-packages/django/utils/decorators.py", line 46, in _wrapper return bound_method(*args, **kwargs) File "/home/mohit/okk/django_pinterest/myenv/lib/python3.8/site-packages/django/utils/decorators.py", line 134, in _wrapper_view response = view_func(request, *args, **kwargs) File "/home/mohit/okk/django_pinterest/myenv/lib/python3.8/site-packages/django/contrib/admin/options.py", line 1747, … -
what are some of the best Resources for Learning and making projects?
I was searching for some great resources for learning React, DSA, and Django all with some bigger Projects. I tried youtubeing but some only are good, if I get someone explaining better on youtube its also fine. other resource like udemy courses are also fine. -
FullCalendar I have the standard event model working, how do I add a dropdown to select additional data in the Javascript/Ajax area?
The events in the FullCalendar are just using fields: name, start and end as in the html-> $(document).ready(function () { var calendar = $('#calendar').fullCalendar({ header: { left: 'prev,next today', center: 'title', right: 'month,agendaWeek,agendaDay' }, events: '/list_events', selectable: true, selectHelper: true, editable: true, eventLimit: true, businessHours: true, select: function (start, end) { let title = prompt("Enter Event Title"); if (title) { var start = prompt("enter start", $.fullCalendar.formatDate(start, "Y-MM-DD HH:mm:ss")); var end = prompt("enter end", $.fullCalendar.formatDate(end, "Y-MM-DD HH:mm:ss")); $.ajax({ type: "GET", url: '/add_event', data: {'title': title, 'start': start, 'end': end}, dataType: "json", success: function (data) { calendar.fullCalendar('refetchEvents'); alert("Added Successfully"); }, error: function (data) { alert('There is a problem!!!'); } }); } }, Question: I would like the function to collect additional data such as status, venue and instructor, where status is a selection, and venue and instructor are DB lookups from Django event model My Event model: class Event(models.Model): name = models.CharField('Event Name', max_length=120) status = models.CharField(choices=EventStatus, default=EventStatus.PENDING, max_length=25) start = models.DateTimeField('start', default="2024-01-01 00:00:00") end = models.DateTimeField('end', default="2024-01-01 00:00:00") venue = models.ForeignKey(Venue, blank=True, null=True, on_delete=models.PROTECT) instructor = models.ForeignKey(Consultant, blank=True, null=True, on_delete=models.PROTECT) # 'name', 'start', 'end', 'venue', 'contact', 'instructor' def __str__(self): return self.name I see there are many code snippets and examples online, … -
when i export with the command flutter build app it generates complex javascript codes but i want only HTML,CSS , Javascript codes, is it Possible?
when i export with the command flutter build web it generates complex javascript codes , but i want only HTML,CSS and Javascript codes . is it Possible ? i have intended to make the front end with flutter and the back with django after exporting , but it is generating complex JS codes i cant get HTML tags and CSS styling , please help me if you have any idea i have tried with flutter build web but it is generating complex javascript codes -
Why do I need to configure volumes for running Django and MySQL in Docker containers?
I had a Django project with a MySQL database running on localhost and I wanted to migrate it to Docker containers. First I migrated the database. I didn't have any problems and I could connect to it from my Django project perfectly. However, when I migrated the Django project to another container, I couldn't connect it to the database. I would always get the following error: django.db.utils.OperationalError: (2002, "Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)") I tried all sorts of solutions and nothing worked. I was using the following docker-compose configuration: version: '3.9' services: my-db: build: ./localhost-db container_name: my-db ports: - 3306:3306 volumes: - my-db-vol:/var/lib/mysql my-server: build: . container_name: my-server ports: - 8000:8000 command: python3 manage.py runserver 0.0.0.0:8000 depends_on: - my-db volumes: my-db-vol: external: true Then I came across this blog post: https://dev.to/foadlind/dockerizing-a-django-mysql-project-g4m Following the configuration in the post, I changed my docker-compose file to: version: '3.9' services: my-db: build: ./localhost-db container_name: my-db ports: - 3306:3306 volumes: - /tmp/app/mysqld:/var/run/mysqld - my-db-vol:/var/lib/mysql my-server: build: . container_name: my-server ports: - 8000:8000 command: python3 manage.py runserver 0.0.0.0:8000 volumes: - /tmp/app/mysqld:/run/mysqld depends_on: - my-db volumes: my-db-vol: external: true Now everything works perfectly, but I can't figure out why adding /tmp/app/mysqld:/var/run/mysqld to … -
2 Django services with common Model
I'm developing some project that needs to be split into two separate Django services, but with one common database (and some of their own for each service). I know that I can provide the database as not default in both applications in settings.py. I know that I can create db_router in both services. I know there may not be the best architecture here. I know that I can make one of this services as "client" which requests another for some operations. But are these all possible solutions? What is the best practice? -
why update is not working when customising the save() in the modle class?
class Person(models.Model): SHIRT_SIZES = [ ("S", "Small"), ("M", "Medium"), ("L", "Large"), ] first_name = models.CharField("person's first name:", max_length = 30, help_text = "User First name") last_name = models.CharField("Person's Last Name:",max_length = 30, help_text = "User Last name") shirt_size = models.CharField(max_length=1, choices=SHIRT_SIZES, default = "S", help_text = "User shirt size") def __str__(self) -> str: return self.first_name + ' ' + self.last_name def full_name(self): return '%s %s' %(self.first_name, self.last_name) def get_absolute_url(self): return "/people/%i/" % self.id; def save(self, *args, **kwargs): self.first_name = "%s %s" %('Mr', self.first_name) return super().save(self, *args, **kwargs) Creating a new record is working fine but it's generating an error when updating the existing record. IntegrityError at /admin/members/person/14/change/ UNIQUE constraint failed: members_person.id Request Method: POST Request URL: http://127.0.0.1:8000/admin/members/person/14/change/ Django Version: 3.2.23 Exception Type: IntegrityError Exception Value: UNIQUE constraint failed: members_person.id Exception Location: C:\wamp\www\python\myproject\lib\site-packages\django\db\backends\sqlite3\base.py, line 423, in execute Python Executable: C:\wamp\www\python\myproject\Scripts\python.exe Python Version: 3.6.6 Python Path: ['C:\\wamp\\www\\python\\vleproject', 'C:\\wamp\\www\\python\\myproject\\Scripts\\python36.zip', 'C:\\Program Files (x86)\\Microsoft Visual Studio\\Shared\\Python36_64\\DLLs', 'C:\\Program Files (x86)\\Microsoft Visual Studio\\Shared\\Python36_64\\lib', 'C:\\Program Files (x86)\\Microsoft Visual Studio\\Shared\\Python36_64', 'C:\\wamp\\www\\python\\myproject', 'C:\\wamp\\www\\python\\myproject\\lib\\site-packages'] Server time: Fri, 12 Jan 2024 13:11:09 +0000 -
Django not updating latest date on form and website?
I'm doing a website using Django, it's hosted on AWS (EC2 with gunicorn for Django server, S3 + cluodfront for static files). I'm doing tests on several days before deployment, but I have an issue : the data on the website seems to not be updated when new values are coming. For exemple on one page : I have an insight with a total "files" value (each days, there are more files so the number is growing) I have a form with a date range (min and max date from the database) I have a div with a max date insight. The server is running for 3 days and the max date is the same as the first day (09/01), same for the insight : value for the 09/01. I've tried to set up a cache that's updated every day. Surprisingly, the update seems to work: if I print the cached value, it's correct and shows the last day, but on the website, nothing updates. The form always displays the maximum date as 09/01 and the insight seems to be frozen. How to solve this problem? In settings.py DEBUG is False. Here are the contents (shortened with the elements concerned) …