Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why does the first django migration on an empty project take so much time?
The first django migration on an empty project takes a lot of time In my server, I wanted to test the installation of django. But after creating the project, I notice that the migration takes a lot of time. I have searched the web but I only find examples of projects that have already modified the code generated by django-admin. Here are the commands I did: django-admin startproject test_dj cd test_dj ./manage.py migrate # This take long time Can anyone help me? -
Column not Exist error although column is in db django
The I m running into an error that column exists. I checked the DB and found that column is present in the database Django.db.utils.ProgrammingError: column "topic" of relation "post_post" does not exist LINE 1: ... "id", "topic... I have tried the following : Post._meta.get_field('topic') got django.db.models.fields.CharField: topic So the field exists too. -
How do I reference multiple schema files in Graphene Django project settings for access in graphql?
I got a Django project with two apps. The project uses graphene-django. Each of the apps got their own schema.py file. How do i reference both the schema files in settings.py in the project folder so that I can access all the schema's in graphql? I have tried: GRAPHENE = { "SCHEMA": "blog.schema.schema", "newsletter.schema.schema", GRAPHENE = { "SCHEMA":[ "blog.schema.schema", "newsletter.schema.schema", ], ...and other combinations which I can't remember, but they all either lead to errors or to just the last schema in the list to work. -
How can I resolve the 'ModuleNotFoundError' for 'Authentication.urls' when running a Django server in VS Code?
Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last):`` File "C:\Users\vasav\AppData\Local\Programs\Python\Python311\Lib\threading.py", line 1038, in _bootstrap_inner self.run() File "C:\Users\vasav\AppData\Local\Programs\Python\Python311\Lib\threading.py", line 975, in run self._target(*self._args, **self._kwargs) File "C:\Users\vasav\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\vasav\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\management\commands\runserver.py", line 133, in inner_run self.check(display_num_errors=True) File "C:\Users\vasav\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\management\base.py", line 485, in check all_issues = checks.run_checks( ^^^^^^^^^^^^^^^^^^ File "C:\Users\vasav\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\checks\registry.py", line 88, in run_checks new_errors = check(app_configs=app_configs, databases=databases) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\vasav\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\checks\urls.py", line 42, in check_url_namespaces_unique all_namespaces = _load_all_namespaces(resolver) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\vasav\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\checks\urls.py", line 61, in load_all_namespaces url_patterns = getattr(resolver, "url_patterns", []) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\vasav\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\utils\functional.py", line 57, in __get__ res = instance.__dict__[self.name] = self.func(instance) ^^^^^^^^^^^^^^^^^^^ File "C:\Users\vasav\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\urls\resolvers.py", line 715, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) ^^^^^^^^^^^^^^^^^^^ File "C:\Users\vasav\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\utils\functional.py", line 57, in __get__ res = instance.__dict__[self.name] = self.func(instance) ^^^^^^^^^^^^^^^^^^^ File "C:\Users\vasav\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\urls\resolvers.py", line 708, in urlconf_module return import_module(self.urlconf_name) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\vasav\AppData\Local\Programs\Python\Python311\Lib\importlib_init.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1206, in _gcd_import File "<frozen importlib._bootstrap>", line 1178, in _find_and_load File "<frozen importlib._bootstrap>", line 1149, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 690, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 940, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "C:\LOGIN PAGE\lakshman\urls.py", line 23, in <module> path('',include('Authentication.urls')) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\vasav\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\urls\conf.py", … -
Time conflicts and empty messages - Realtime chat application
community. Problem: I'm working on a real-time django chat application. When user messages it shows the right current time but, it's gets changed to a different time on refershing the page. Here are the snaps for your reference: Real time chatting After refreshing the page - Note-time has been changed on refreshing and some empty messages are coming as well What i want is .... as a real-time chat application the time and empty message should not show on refreshing the page. Here is the code that i've implemented: message model class Message(models.Model): room = models.ForeignKey(Room, related_name='messages', on_delete=models.CASCADE) user = models.ForeignKey(User, related_name='messages', on_delete=models.CASCADE) content = models.TextField() date_added = models.DateTimeField(auto_now_add=True) class Meta: ordering = ('date_added',) Java Script <script> const roomName = JSON.parse(document.getElementById('json-roomname').textContent); const userName = JSON.parse(document.getElementById('json-username').textContent); const chatSocket = new WebSocket( 'ws://' + window.location.host + '/ws/' + roomName + '/' ); chatSocket.onclose = function(e) { console.log('onclose') } chatSocket.onmessage = function(e) { const data = JSON.parse(e.data); if (data.message) { const currentTime = new Date().toLocaleTimeString('en-US', { hour: 'numeric', minute: 'numeric', hour12: true }); const messageHTML = ` <div class="message ${data.username === userName ? 'self' : 'other'}"> <div class="message-content"> <b>${data.username}</b>: ${data.message} </div> <div class="message-time"> ${currentTime} </div> </div> `; document.querySelector('#chat-messages').innerHTML += messageHTML; } else { … -
Django formset with CBV: unicity constraint pass form_valid()
I try to use formset and CBV CreateView for a treatment model but validation failed. I am quite lost with validation logic in my view. I have added a try/catch in form_valid method to manage unicity constraint but this might not be the right way to do. Moreover, other form validations are not displayed in my template. @method_decorator(login_required, name="dispatch") class TraitementFormSetCreate(SuccessMessageMixin, CreateView): model = Traitement form_class = TraitementForm template_name = "ecrf/traitements_form.html" success_message = "Fiche Traitement créée." success_url = reverse_lazy('ecrf:patient_list') def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['formset'] = TraitementFormSet(queryset=Traitement.objects.filter(pat=self.kwargs['pk'])) context['action'] = 'create' context['patient'] = Patient.objects.get(ide=self.kwargs['pk']) context['model_name'] = self.model._meta.model_name context['is_locked'] = self.object.ver if self.object else None return context def post(self, request, *args, **kwargs): self.object = self.get_object() # assign the object to the view formset = TraitementFormSet(request.POST) if formset.is_valid(): return self.form_valid(formset) else: return self.form_invalid(formset) def form_valid(self, formset): print('valid') patient = Patient.objects.get(ide=self.kwargs["pk"]) traitements = formset.save(commit=False) for traitement in traitements: traitement.pat = patient traitement.arv_sai_log = self.request.user.username try: traitement.save() except IntegrityError: formset.errors.append(ValidationError('Une fiche Traitement ARV existe déjà pour ce patient avec ce numéro')) context = self.get_context_data(formset=formset) return self.render_to_response(context) return redirect("ecrf:patient_list") def form_invalid(self, formset): print('invalid',formset.errors) context = self.get_context_data(formset=formset) return self.render_to_response(context) -
Django how to handle exception (0, '') while executing sql
settings.py: import configparser config = configparser.RawConfigParser() config.read('/home/forge/django_application/config.ini') DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': config['mysqlDB']['database'], 'USER': config['mysqlDB']['user'], 'PASSWORD': config['mysqlDB']['password'], 'HOST': config['mysqlDB']['host'], 'PORT': '3306', 'CONN_MAX_AGE' : 200, } } __init__.py import pymysql pymysql.install_as_MySQLdb() views.py: cursor = "" def index(request): email_content = "" global cursor cursor = connection.cursor() try: for key, value in request.POST.items(): if key == "body-html": email_html_content = value While I running there is coming exception at the server (0, ''). Is there any solution to fix the mysql exception which handle multiple script. -
Django Complex Query Multiple Models
I have these models and need to make the query below class Quote(models.Model): company = models.ForeignKey( Company, on_delete=models.CASCADE, ) status = models.ForeignKey( StatusType, on_delete=models.CASCADE, ) class QuoteStatusHistory(StatusHistoryBase): quote = models.ForeignKey(Quote, on_delete=models.CASCADE) create_date = models.DateTimeField(auto_now_add=True) class StatusType(models.Model): type_class = models.CharField(max_length=10, choices=COMMON.CLASS_STATUS_TYPE) type_code = models.CharField(max_length=50) type_name = models.CharField(max_length=100) Here is the query: SELECT qt.id ,(SELECT qst.create_date FROM quote_status_history qst JOIN status_type st ON (type_class = 'QUOTE' AND type_code = 'AVAILABLE' AND qst.status_type_id = st.id) WHERE qst.quote_id = qt.id) send_date FROM quote qt WHERE qt.company_id = 90; Currently, I'm just doing a query_set to get all the Quotes for the specific company, and then loop through the all the company.quotes records in order to get the create_date from the QuoteStatusHistory, but the problem is the performance... it will hit database for each record and it will take forever to load the data. What is the most efficient way to get the data from this specific query? -
Linking a custom HTML form with a django model form
I want to connect my model forms to Html forms with horizontal fields. How do I manually render each field. I have tried to implement with no success. With the following method, I have manually render the fields but the form is not saving the data to the database. #add_user.html form action="#" method="POST"> {% csrf_token %} <div class="row"> <div class="col-xl-6"> <div class="form-group row"> <label class="col-lg-3 col-form-label">{{user_form.first_name.label_tag}}</label> <div class="col-lg-9"> {{ user_form.first_name }} </div> </div> <div class="form-group row"> <label class="col-lg-3 col-form-label">{{user_form.last_name.label_tag}}</label> <div class="col-lg-9"> {{ user_form.last_name }} </div> </div> </div> <div class="col-xl-6"> <div class="form-group row"> <label class="col-lg-3 col-form-label">{{user_form.password1.label_tag}}</label> <div class="col-lg-9"> {{ user_form.password1 }} </div> </div> <div class="form-group row"> <label class="col-lg-3 col-form-label">{{user_form.password2.label_tag}}</label> <div class="col-lg-9"> {{ user_form.password2 }} </div> </div> <button type="submit" class="btn btn-primary text-end">Submit</button> </div> </div> </div> </div> -
python, django, api making
I got Attribute Error:'GenericForeignKey' object has no attribute 'get_lookup'.How to solve this error? I tried this in django api making project.Everytime I get this error message.This occurs in model and viewsets of project. -
Unresolved attribute warnings when inheriting from GenericViewSet in Django with custom Mixin
I'm using Django and Django REST Framework to develop a web application. I have a custom ViewSet called ProductsViewSet that inherits from CreateAndSaveUserMixin, RetrieveModelMixin, and GenericViewSet. The code is as follows: class ProductsViewSet(CreateAndSaveUserMixin, RetrieveModelMixin, GenericViewSet): queryset = Product.objects.none() serializer_class = ProductsSerializer The CreateAndSaveUserMixin is defined as: class CreateAndSaveUserMixin: def create(self, request, *args, **kwargs): serializer = self.serializer_class(data=request.data, context=self.get_serializer_context()) if serializer.is_valid(): if isinstance(request.user, Cognito): response = serializer.save(created_by=request.user) else: response = serializer.save() return JsonResponse(self.serializer_class(response).data, safe=False) return JsonResponse(serializer.errors, status=status.HTTP_400_BAD_REQUEST) The issue I'm experiencing is that my IDE, PyCharm, shows the following warnings when I'm working with the CreateAndSaveUserMixin: Unresolved attribute reference 'serializer_class' for class 'CreateAndSaveUserMixin' Unresolved attribute reference 'get_serializer_context' for class 'CreateAndSaveUserMixin' Although my application functions correctly, the editor doesn't recognize these attributes that come from the base class GenericViewSet, which I'm inheriting in my view rather than in my mixin. How can I resolve these warnings in PyCharm and ensure that the editor correctly recognizes the inherited attributes from GenericViewSet in my CreateAndSaveUserMixin? Any help or suggestions would be greatly appreciated. Thank you in advance! i tried declare serializer_class and get_serializer_context in the custom mixin like: serializer_class = None get_serializer_context = None but only works for serializer_class -
I have two errors because of Django or Apache
Two errors: Error 404 (Not Found) on POST request to http://localhost/upload-avatar/ and SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON.When I try to send a POST request to http://localhost/upload-avatar/ I get a POST error http://localhost/upload-avatar/ 404 (Not Found) and a SyntaxError: Unexpected token '<', "< !DOCTYPE "... is not valid JSON. I would like to understand what is the reason and how to fix this problem. There are suspicions that the problem is in Apache. I am using wamp. I connected Django after some time of using and writing wamp code. I configured Apache. I also checked the routing settings and the server startup, but the problem remains. I ask for help in identifying and eliminating this problem. Thank you in advance! Code: JS: PhotoUpload.addEventListener('change', function() { const file = this.files[0]; if (file) { const reader = new FileReader(); reader.addEventListener('load', function() { photo.setAttribute('src', this.result); photo.classList.remove('alt-centered'); PhotoUpload.style.display = 'none'; const formData = new FormData(); formData.append('photo', file); fetch('/upload-avatar/', { method: 'POST', body: formData }) .then(response => response.json()) .then(data => { console.log(data); }) .catch(error => { console.error('Error:', error); }); }); reader.readAsDataURL(file); } else { photo.setAttribute('src', '#'); photo.classList.add('alt-centered'); PhotoUpload.style.display = 'block'; } }); }; views.py from django.shortcuts import render from django.views.decorators.csrf import … -
request.user return AnonymousUser in django, react project
I have a web project what back-end is coded with django and front-end is coded with react. In my project, i want to create an order to a special user so this part of project needs to know the user but when i used request.user it returned AnonymousUser. here are the react, axios code and views.py with rest_framework: react code // Hook to save game id and price const [all, setAll] = useState({'game': 0, 'price': 0}); // get state const location = useLocation(); const state = location.state; useEffect(() => { setAll({'game': state[0]}, 'price': suggestion); }, []) // To check user confirm suggestion and make order api. const orderApi = async (e) => { e.preventDefault(); try { // console.log({'state': state[0], 'suggestion': suggestion}); console.log(all); const {status} = await axios.post('http://127.0.0.1:8000/api-1/order/create/', all); if (status === 201) { console.log('created'); } } catch (err) { console.log(err) } } views.py from rest_framework import status from rest_framework.response import Response from . import serializer from rest_framework.decorators import api_view from . import models from game.models import Game @api_view(['GET', 'POST']) def orderCreate(request): # Here my program return AnonymousUser print(str(request.user) + '\n') if request.method == 'POST': ....... orders = models.Order.objects.all() serialized = serializer.OrderSerializer(orders, many=True) return Response(serialized.data, status=status.HTTP_200_OK) To write a clean code … -
Using enums in Django with error ModuleNotFoundError: No module named 'models'
I am trying to use enums in my unit tests but I'm getting an error when I try to import them. An excerpt from models.py: class SeekingConstants: MEN = 'Men' WOMEN = 'Women' BOTH_MEN_AND_WOMEN = 'Both men and women' An excerpt from test_user_api.py: from models import SeekingConstants ... def test_update_user_seeking_choice(self): """Part 1: Update the seeking choice from nothing""" payload = { 'email': 'test@example.com', 'seeking_choice': SeekingConstants.WOMEN } res = self.client.patch(ME_URL, payload) self.user.refresh_from_db() self.assertEqual(self.user.email, payload['email']) self.assertTrue(self.user.seeking_choice, payload['seeking_choice']) self.assertEqual(res.status_code, status.HTTP_200_OK) """Part 2: Update an existing seeking choice""" new_payload = { 'email': 'test@example.com', 'seeking_choice': SeekingConstants.BOTH_MEN_AND_WOMEN } res = self.client.patch(ME_URL, new_payload) self.user.refresh_from_db() self.assertEqual(self.user.email, payload['email']) self.assertTrue(self.user.seeking_choice, payload['seeking_choice']) self.assertEqual(res.status_code, status.HTTP_200_OK) I'm not sure why I can't import this enum or how I should import this enum. -
Trying to implement the django-formset library but I am unable to get any of the buttons to work. They are completely non-responsive
I am trying to utilize the django-formset library to create dynamic forms. However, I am unable to get any of the buttons to work (whether they're add/submit or add forms). The only error in the javascript console was the following: Uncaught DOMException: Failed to read the 'cssRules' property from 'CSSStyleSheet': Cannot access rules at Object.i [as convertPseudoClasses] (http://127.0.0.1:8001/static/formset/js/chunk-KFPGMBXM.js:1:354) at http://127.0.0.1:8001/static/formset/js/django-formset.js:25:29909 This is my first time working with django, html, css, javascript, and jquery but as far as I could trace the issue, I thought it maybe had something to do with not loading the typescript implementation of the 'click' webelement based on this error. But I got stuck tracing the error and so I tried to simplify/isolate the issue by creating a new project and copying the examples in the documentation. I also though there could be a conflict or issue with one of my templates, another library, or with a javascript function... ...but I can't get even the simplest model/form button to work using the example in Chapter 9 of the documentation. So I'm wondering if there's something really basic I'm missing. The following example doesn't throw any errors in the browser console but results in the same dead … -
"The client was disconnected by the server because of inactivity" using an async function in Django
I'm using Django 4.2 connected to a MySQL 8 database. I'm using asyncio for a function I really need to run asynchronously: example_object = asyncio.run(example(request)) async def example(request): object = await ModelExample.objects.filter(example=example).afirst() return object I started by having the error in the await line: MySQL server has gone away Then, by manually closing connection like: example_object = asyncio.run(example(request)) connection.close() I started having the following error: The client was disconnected by the server because of inactivity. See wait_timeout and interactive_timeout for configuring this behavior This error don't happen right away, but after a few hours (maybe 8h, like the default wait_timeout variable) after I restart the (nginx) server. Things that I tried: Adding close_old_connections() before asyncio.run. Don't understand why there is an inactive connection left open at all. Increasing the wait_timeout value and interactive_timeout variables in my MySQL config file. I find it very strange that this had no impact at all but the "SHOW VARIABLES" command shows me they are indeed currently set to 31536000. Then I thought that maybe the connection from Django is somehow independent of that and tried setting CONN_HEALTH_CHECKS option to True, in the hopes that "if the health check fails, the connection will be reestablished … -
Likes as a many to many
I'm making a public prayer journal in full stack(react w/ nextjs and python w/ django) where you can also add and like verses. As the title says the likes are the many to many but I need it to where any component that displays verse likes will need all of the likes for a user and store them in state. If a verse is in the userLikes for a user, the like button should get checked on render. I need a change handler to submit a userlike to the api whenever the like button is checked, and delete a userlike whenever the like button is unchecked. But I'm unsure of how it's supposed to look exactly, I have trouble translating sentences to code. I already have the api views and data module, as seen below: user_like class LikeView(ViewSet): def retrieve(self, request, pk): try: user_like = UserLike.objects.get(pk=pk) serializer = UserLikeSerializer(user_like) return Response(serializer.data) except UserLike.DoesNotExist as ex: return Response({'message': ex.args[0]}, status=status.HTTP_404_NOT_FOUND) def list(self, request): user_likes = UserLike.objects.all() verse = request.query_params.get('verse', None) user = request.query_params.get('user', None) if verse is not None: user_likes = user_likes.filter(verse_id=verse) if user is not None: user_likes = user_likes.filter(user_id=user) serializer = UserLikeSerializer(user_likes, many=True) return Response(serializer.data) def update(self, request, pk): user_like … -
TypeError: Cannot read properties of undefined (reading 'params') Django + React
Uncaught TypeError: Cannot read properties of undefined (reading 'params') Unabel to navigate to id can anyone help? i am woriking on django as backend and react as frontend class ArticleDetail extends React.Component{ state={ article:{} } componentDidMount(){ const id = this.props.match.params.id; axios.get(`http://127.0.0.1:8000/api/${id}`) .then(res =>{ this.setState({ article:res.data }); console.log(res.data) }) } render(){ return( <Card title={this.state.article.title} > <p>{this.state.article.content }</p> </Card> ) } }``` TypeError: Cannot read properties of undefined (reading 'params') Unabel to navigate to id can anyone help? i am working on react + django. My data from server in list is showing but when i try to navigate to particular data id it shows error -
How to add validators and constraints on Django admin form with bulk inline data
I have 3 simple Django models to create a reservation system class User(models.Model): first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) class Activity(models.Model): title = models.CharField(max_length=255) category = models.CharField(max_length=255) start_reservation = models.DateTimeField() end_reservation = models.DateTimeField() max_capacity = models.IntegerField() def clean(self): if self.start_reservation > self.end_reservation: raise ValidationError("Start date must be before end date") class Reservation(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) activity = models.ForeignKey(Activity, on_delete=models.CASCADE) class Meta: unique_together = ['user', 'activity'] My admin forms look like this @admin.register(User) class UserAdmin(admin.ModelAdmin): pass class ReservationAdmin(admin.TabularInline): model = Reservation extra = 0 @admin.register(Activity) class ActivityAdmin(admin.ModelAdmin): inlines = [ReservationAdmin] When I save an ActivityAdmin form, how can I ensure, that the number of reservations for a specific activity does not go over the max_capacity? I tried using the clean method on the reservation like this: class Reservation(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) activity = models.ForeignKey(Activity, on_delete=models.CASCADE) class Meta: unique_together = ['user', 'activity'] def clean(self): print(self.activity.reservation_set.count()) if self.activity.reservation_set.count() >= self.activity.max_capacity: raise ValidationError("Max capacity reached") But in the console, it prints the amount of reservations before any of the form data is saved to the DB. For example when I create a brand new activity (max_capactiy = 2) and I add 3 inline reservations, the console says: 0 0 0 even though … -
How to use import Geopackage data to my Django RESTful API?
I want to create a full-stack web application to let users query parks and greenspace in the UK, something like this: https://www.barnet.gov.uk/directories/parks. I want to build a Django RESTful API to query parks and greenspaces data. I am still a beginner and I am still learning. I have never imported large amounts of data to my app/database before. Usually, I manually input the data one by one for my RESTful APIS. This time, I don't want to manually input all the data. I want to build a project that is based on real-world data. Therefore, I found a public dataset for parks and greenspace (?), https://www.data.gov.uk/dataset/4c1fe120-a920-4f6d-bc41-8fd4586bd662/os-open-greenspace. I find it hard to understand what is the page about. I downloaded the Geopackage/gpkg file and I don't know how to use it. Here are some questions I have in mind: Is this the data I am looking for? Does the data contains info about the park, such as the park name? Or does it only store the geo location of the park? What I want to do is somehow transform this gpkg file into data I can play with in my Django RESTful API. And then I will write some API endpoints … -
django adding extra data to IntegerChoices
I need to add extra data to enum Class IntegerChoice in django. I have carefully read the answer here How to add extra data to TextChoices? but it does not seem to work. the definition of my enum type is : class FabricType (models.IntegerChoices): """an enumeration class with type, subclass and key words added first item is the code, second is translated verbose name, third is choice specific help, third is Group fourth is a list of keywords anychange in the number will require migration but adding new keywords will not """ CASTON = (1, _('Caston'), _('Basic'), []) JERSEY = (2, _('Jersey'), _('Basic'), []) TUBULAR = (3, _('Tubular'), _('Basic'), []) def __new__(cls, value, label, group, keywords, ): obj = int.__new__(cls, value) obj._value_ = value obj.group = group obj.keywords = keywords obj.help = help return obj def help_dict(cls): """help_dict for the FabricType""" help_dict = {'CASTON': _('the first few rows of a knit'), 'JERSEY': _('help_text'), 'TUBULAR': _('help text') return help_dict I have declared the EnumMixin as follows : class EnumMixin: ''' an Enum which Converts a DB value back to its Choices value''' def __init__(self, *args, enum=models.Choices, **kwargs): self.__enum = enum self.help_dict = kwargs.get('help_dict', None) kwargs.pop('help_dict', None) # it sets choices for … -
How to set the current proper date and time to "DateField()" and "TimeField()" respectively as a default value by "TIME_ZONE" in Django Models?
The doc says below in DateField.auto_now_add. *I use Django 4.2.1: Automatically set the field to now when the object is first created. ... If you want to be able to modify this field, set the following instead of auto_now_add=True: For DateField: default=date.today - from datetime.date.today() For DateTimeField: default=timezone.now - from django.utils.timezone.now() So, I set timezone.now and date.today to datetime's DateTimeField() and date1's DateField() respectively and I also set current_date which returns timezone.now().date() and current_time which returns timezone.now().time() to date2's DateField() and time's TimeField() respectively as shown below: # "models.py" from django.db import models from datetime import date from django.utils import timezone def current_date(): return timezone.now().date() def current_time(): return timezone.now().time() class MyModel(models.Model): datetime = models.DateTimeField(default=timezone.now) # Here date1 = models.DateField(default=date.today) # Here date2 = models.DateField(default=current_date) # Here time = models.TimeField(default=current_time) # Here Then, I set 'America/New_York' to TIME_ZONE in settings.py as shown below: # "settings.py" LANGUAGE_CODE = "en-us" TIME_ZONE = 'America/New_York' # Here USE_I18N = True USE_L10N = True USE_TZ = True But, date1's DateField() and time's TimeField() show UTC(+0 hours)'s date and time on Django Admin as shown below: Next, I set 'Asia/Tokyo' to TIME_ZONE in settings.py as shown below: # "settings.py" LANGUAGE_CODE = "en-us" TIME_ZONE = 'Asia/Tokyo' # Here … -
SyntaxError: Unexpected token '*' error when i try to load my javascript
i am getting this error SyntaxError: Unexpected token '*'. import call expects exactly one argument. when i load my javascript file in my django project. this is my code btw import * as THREE from 'three'; const scene = new THREE.Scene(); const camera = new THREE.PerspectiveCamera(75,window.innerWidth/window.innerHeight,0.1,1000); const renderer = new THREE.WebGLRenderer({ canvas: document.querySelector("#bg"), }); renderer.setPixelRatio(window.devicePixelRatio); renderer.setSize(window.innerWidth,window.innerHeight); camera.position.setZ(30); renderer.render(scene,camera); const geometry = new THREE.OctahedronGeometry(1,0); const color = new THREE.Color(134, 0, 255); const mat = new THREE.MeshBasicMaterial({color: color,wireframe: true}); const torus = new THREE.Mesh(geometry,mat); scene.add(torus); function animate(){ requestAnimationFrame(animate); renderer.render(scene,camera); } animate() i have already tried: looking if i have the correct javascript version that supports import i have and looking if i load the file correctly and triple checking if i have installed three correctly aswell. but for some reason it just does not work. -
IN DRF, how to create a POST serializer where I can add multiple values of a Foreign Key field
These are 2 models I have: class Skill(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name + " - ID: " + str(self.id) class Experience(models.Model): consultant = models.ForeignKey("Consultant", related_name="experience", on_delete=models.CASCADE) project_name = models.CharField(max_length=100) company = models.CharField(max_length=100) company_description = models.TextField(null=True, blank=True) from_date = models.DateField() to_date = models.DateField() project_description = models.CharField(max_length=100) contribution = models.TextField() summary = models.TextField() is_pinned = models.BooleanField(default=False) role = models.CharField(max_length=100, null=True) skill = models.ForeignKey("Skill", related_name="experience", on_delete=models.CASCADE) I want to do something that is quite common but apparently not possible out of the box with DRF: I want to have an endpoint /experience/ with a POST method where I can send a LIST of skill ids (skill field, ForeignKey). For example: { "project_name": "Project AVC", "company": "XYZ Company", "company_description": "Description of XYZ Company", "from_date": "2022-01-01", "to_date": "2022-12-31", "project_description": "Description of Project ABC", "contribution": "Contributions to Project ABC", "summary": "Summary of Experience", "is_pinned": false, "role": "Consultant", "skills_ids": [1,2,3], "consultant": 1 } If there are Skill records in the DB with ids 1,2,3 then it will create 3 records in the experience table (one for each skill ofc) . If there's no skill with such id, then during validation it should return an error to the user informing so. The name of the … -
i need help in django views and date
I'm new to Django and trying to do something here. Even if it is out of date, you cannot edit it because less than 1 hour is left. i get the error Thanks for your help. if shop.manager != user: messages.error(request, "You are not the manager.") return redirect('home') shop_datetime = timezone.make_aware(datetime.combine(shop.date, shop.hour)) if shop_datetime <= now: messages.error(request, "You cannot edit it because it is out of date.") return redirect('shopdetail', slug=slug) if last_edit_time >= now: messages.error(request, "You cannot edit this as there is less than 1 hour left.") return redirect('shopdetail', slug=slug) if request.method == "POST": form = ShopUpdateForm(request.POST, instance=shop) if form.is_valid(): if form.cleaned_data['date'].date() < date.today(): form.add_error('date', 'You cannot add anything to the previous date') else: etkinlik = form.save(commit=False) etkinlik.slug = slug etkinlik.save() return redirect('shopdetail', slug=slug) else: form = ShopUpdateForm(instance=shop) data = create_calendar(year, month) return render(request, 'shop/edit_shop.html', {'form': form, **data})