Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Override error representation on import model page django
I'm working with a django application and don't wanted to show users the stack trace when there is any error occurred in production. For example, I've added validation to validate import action under before_import method, and when there is any issue in the validation it shows error message along with stack trace. Please refer screenshot below: Instead I wanted to just show the error message only. This is mainly for the security purpose as on production it will disclose my server directory structure to it's users. I tried couple of things, to override import.html under my templates directory, but it didn't worked. to override exception using LOGGING in settings.py It is great, if I can show list of errors for all affected rows in a CSV/XLSX file. -
How to Add 'rest_registration' URLs to Default Routers in Django REST Framework and Include Them in API Root?
I am using the 'rest_registration' package to handle user validation and registration in my Django REST API project. I would like to integrate the 'rest_registration' URLs with the default routers in Django REST Framework and have them included in the API root. Can someone please provide guidance on how to achieve this integration? Specifically, I want to know how to configure my project to include 'rest_registration' URLs in the default routers, and I'd like these URLs to be visible in the API root. from django.urls import path, include from rest_framework import routers from rest_framework import viewsets from rest_framework.response import Response class ServerStatusViewSet(viewsets.ViewSet): def list(self, request): return Response({'status': 'Server is running'}) router = routers.DefaultRouter() router.register(r'status', ServerStatusViewSet, basename='server-status') urlpatterns = [ path('', include(router.urls)), path('auth/', include('rest_registration.api.urls')), ] -
After making a reservation, the reserved time does not disappear from the list of available times
I am working on a project where you can arrange training with a trainer. And I have a problem with booking a training session, because after making a reservation, the time that was booked does not disappear from the available time. On the same day, another person can also book this hour. Models.py class BaseModel(models.Model): created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: abstract = True class WorkingHour(models.Model): time = models.CharField(max_length=10, unique=True, null=True) is_available = models.BooleanField(default=True) def reserve_hour(self): if self.is_available: self.is_available = False self.save() def __str__(self): return self.time class Trainer(BaseModel): trainer = models.ForeignKey(UserProfile, on_delete=models.CASCADE, null=True) job = models.CharField(max_length=32, choices=type_job) working_hours = models.ManyToManyField(WorkingHour, related_name='trainers', null=True) def __str__(self): return f"{self.trainer.first_name} {self.trainer.last_name} - {self.job}" class TrainerServices(models.Model): name = models.CharField(max_length=64) price = models.DecimalField(max_digits=10, decimal_places=2) def __str__(self): return self.name class Appointment(BaseModel): date = models.DateField() chosen_hour = models.ForeignKey(WorkingHour, on_delete=models.CASCADE, null=True) class TrainerAppointment(Appointment): trainer = models.ForeignKey(Trainer, on_delete=models.CASCADE) services = models.ForeignKey(TrainerServices, on_delete=models.CASCADE) user = models.ForeignKey(MyUser, on_delete=models.CASCADE, null=True, blank=True) def __str__(self): return f"{self.user}-{self.services}" Forms.py class TrainerAppointmentForm(forms.ModelForm): chosen_hour = forms.ModelChoiceField( queryset=WorkingHour.objects.filter(is_available=True), empty_label=None, widget=forms.Select(attrs={"class": "form-select is_valid"}) ) class Meta: model = TrainerAppointment fields = "__all__" widgets = { "trainer": forms.Select(attrs={"class": "form-select is_valid"}), "date": forms.DateInput(attrs={"class": "form-control is_valid", "type": "date"}), "services": forms.Select(attrs={"class": "form-select is_valid"}), } def clean_date(self): date = self.cleaned_data.get('date') today = timezone.now().date() … -
Clean and Reusable Exception Handling in Django and DRF (Pythonic problem)
I'm working on a Django API project and I'm facing a challenge with exception handling. Specifically, I want to handle specific exceptions raised in my business logic and map them to corresponding Django REST framework (DRF) exceptions in a clean and reusable way. Here's a simplified version of my code: # My business logic class UserBusinessLogicLayer(Manager): """ This is the business logic layer for User management. """ def get_user_with_identifier(self, identifier: str, allow_username: bool = True) -> "User": # ... (omitting some code for brevity) user = self.filter(reduce(operator.or_, conditions)).first() if not user: raise self.model.DoesNotExist("User Does not exist.") if not user.is_active: logger.info( "The user with username/email/phone-number %s is not active", identifier, exc_info=True, ) raise DeactivatedUser( f"This account has been deactivated since {user.status_change}", user ) if not user.is_email_verified: logger.info( "The user %s hasn't verified the email", identifier, exc_info=True, ) raise NotVerifiedEmail("This account hasn't verified the its email") return user and this is how i use the code: try: user = User.bll.get_user_with_identifier(identifier, allow_username=False) except User.DoesNotExist as error: # this is how i normally handle the exceptions logger.info( "there is no user with username/email/phone-number %s", identifier, exc_info=True, ) raise exceptions.NotFound("Invalid input.") from error # this is api exception except Exception as error: # But I … -
arcpy.env.workspace not working in django. Its throwing this error AttributeError: ERROR 87934
class get_FeatureClassView(viewsets.ViewSet): def list(self, request, projectname): sgeometry = {} # Corrected variable name tgeometry = {} # Corrected variable name project_path = config.get('Paths', 'project_path') template_dir = config.get('Paths', 'template_dir') # project_path = r"D:\sreeraj\project\unbridge_backEnd" # Use a raw string or double backslashes project_path1 = os.path.join(project_path, projectname) print(project_path1) print(project_path) source_path = os.path.join(project_path1, "sourcegdb") # Use os.path.join for path concatenation print("----------", source_path) source_gdb = os.listdir(source_path)[0] print("source_gdb", source_gdb) source_gdb_path = os.path.join(source_path, source_gdb) print("sourceGDBPath", source_gdb_path) self.source_gdb_path = source_gdb_path target_path = os.path.join(project_path1, "targetgdb") # Use os.path.join for path concatenation target_gdb = os.listdir(target_path)[0] target_gdb_path = os.path.join(target_path, target_gdb) print("target_gdb_path", target_gdb_path) arcpy.env.workspace = source_gdb_path sourcefeature_classes = arcpy.ListFeatureClasses() #sourcefeature_classes.sort() print(sourcefeature_classes) for feature_class in sourcefeature_classes: desc = arcpy.Describe(feature_class) geometry_type = desc.shapeType sgeometry[feature_class] = geometry_type arcpy.env.workspace = os.path.join(target_gdb_path, "UtilityNetwork") # Use os.path.join for path concatenation targetfeature_classes = arcpy.ListFeatureClasses() #targetfeature_classes.sort() print(targetfeature_classes) for feature_class in targetfeature_classes: desc = arcpy.Describe(feature_class) geometry_type = desc.shapeType tgeometry[feature_class] = geometry_type featureclasslist = { "sourcefeature_classes": sgeometry, "targetfeature_classes": tgeometry } print(featureclasslist) return JsonResponse(featureclasslist) This throwing this error Traceback (most recent call last): File "C:\Users\sv67808\AppData\Local\miniconda3\envs\arcproenv\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Users\sv67808\AppData\Local\miniconda3\envs\arcproenv\lib\site-packages\django\core\handlers\base.py", line 197, in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\sv67808\AppData\Local\miniconda3\envs\arcproenv\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "C:\Users\sv67808\AppData\Local\miniconda3\envs\arcproenv\lib\site-packages\rest_framework\viewsets.py", line 125, in view return self.dispatch(request, *args, **kwargs) File … -
How to upload media files to AWS S3 within Django app without getting a ClientError
I'm getting the following error when I try to upload images within the admin panel, 'An error occurred (AccessControlListNotSupported) when calling the PutObject operation: The bucket does not allow ACLs'. I've setup the settings.py file and AWS according to the django-storages docs, but still not working. All Static files are being imported in and can be read Also tried changing the AWS_DEFAULT_ACL to 'none' and 'public-read-write' but still not working. settings.py config: if USE_S3: # aws settings AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = os.environ.get('AWS_STORAGE_BUCKET_NAME') AWS_DEFAULT_ACL = public-read AWS_S3_REGION_NAME = os.environ.get('AWS_S3_REGION_NAME') AWS_S3_CUSTOM_DOMAIN = f'{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com' AWS_S3_OBJECT_PARAMETERS = {'CacheControl': 'max-age=86400'} #Additional settings AWS_S3_FILE_OVERWRITE = False AWS_QUERYSTRING_AUTH = False # s3 static settings AWS_STATIC_LOCATION = 'static' STATIC_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/{AWS_STATIC_LOCATION}/' STATICFILES_STORAGE = 'myproject.storages.StaticStore' # s3 media settings AWS_MEDIA_LOCATION = 'media' MEDIA_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/{AWS_MEDIA_LOCATION}/' DEFAULT_FILE_STORAGE = 'myproject.storages.MediaStore' else: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) AWS Bucket Policy: { "Version": "2012-10-17", "Statement": [ { "Sid": "Statement1", "Effect": "Allow", "Action": "s3:*", "Resource": "arn:aws:s3:::my-bucket/*" }, { "Sid": "Statement2", "Effect": "Allow", "Action": "s3:*", "Resource": "arn:aws:s3:::my-bucket/" } ] } -
Godaddy not sending emails throws SMTPAuthenticationError on Django
I have the following settings on my settings file in django EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.office365.com' EMAIL_HOST_USER = 'email@website.com' DEFAULT_FROM_EMAIL = EMAIL_HOST_USER EMAIL_HOST_PASSWORD = "password" EMAIL_PORT = 587 EMAIL_USE_SSL = False EMAIL_USE_TLS = True and when I try and send an email it throws this error SMTPAuthenticationError at /contact-ajax (535, b'5.7.139 Authentication unsuccessful, SmtpClientAuthentication is disabled for the Tenant. Visit https://aka.ms/smtp_auth_disabled for more information. [BYAPR02CA0052.namprd02.prod.outlook.com 2023-10-25T10:46:26.078Z 08DBD4986B1B4B4D]') ... Traceback: File "/home/sammy/webapp/envs/prestige/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/home/sammy/webapp/envs/prestige/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "/home/sammy/webapp/envs/prestige/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/sammy/webapp/envs/prestige/lib/python3.6/site-packages/django/views/decorators/csrf.py" in wrapped_view 54. return view_func(*args, **kwargs) File "/home/sammy/webapp/prestige/prestige/views.py" in contact_ajax 130. msg.send() I know the logins are fine because I've just logged in with them to godaddy webmail I know there's no need for app password for this -
How to get InMemoryFileUpload video file's duration in django
I've searched about that in the SO, but there solutions with video file's path. I need to get file's duration by InMemoryFileUpload or BytesIO in django. How can do that? from moviepy.editor import VideoFileClip def video_skip_validator(data): video_file = data.get("video") video = VideoFileClip(video_file) print(video.duration) It raises 'InMemoryUploadedFile' object has no attribute 'endswith' error. -
API returns not found but the endpint is correct
I have a Django Rest Framework Endpoint urlpatterns_usersettings = [ path("usersettings/<int:pk>/", UpdateUserSettings.as_view()) ] and a view to deal with that endpoint: class UpdateUserSettings(generics.UpdateAPIView): permission_classes = [IsAuthenticated] serializer_class = UserSettingsSerializer def get_queryset(self): user = self.kwargs["pk"] return UserSettings.objects.all().filter(user=user) Here is the model: from django.db import models from django.contrib.auth import get_user_model User = get_user_model() class UserSettings(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="user_settings") # ACCOUNT SETTINGS gotodash = models.BooleanField(default=False) loginalert = models.BooleanField(default=False) # DISPLAY SETTINGS darkmode = models.BooleanField(default=False) button_color = models.CharField(max_length=10, null=True, blank=True) link_color = models.CharField(max_length=10, null=True, blank=True) heading_color = models.CharField(max_length=10, null=True, blank=True) title_color = models.CharField(max_length=10, null=True, blank=True) tab_color = models.CharField(max_length=10, null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True, verbose_name="created at") updated_at = models.DateTimeField(auto_now=True, verbose_name="updated at") class Meta: verbose_name = "user settings" verbose_name_plural = "users settings" db_table = "users_settings" def __str__(self): return f"{self.user}'s settings" and here is the serializer: from rest_framework import serializers from .models import UserSettings from django.contrib.auth import get_user_model User = get_user_model() class UserSettingsSerializer(serializers.ModelSerializer): class Meta: model = UserSettings fields = "__all__" If I call the endpoint I get a 404 error and in the response it says detail not found, but if I do a breakpoint and manually get the object then it works fine I can get the object, so why can the view … -
"Rollup" fields in OpenTelemetry to sum values from child spans
I'm currently in the process of migrating my Django application monitoring from beeline to OpenTelemetry. One feature of beeline was the add_rollup_field function which can specify a field to be summed in a trace's root span. For example, if we add a db.total_duration rollup field, we can use that to sum all of the db.duration values for a root span. What would be the best way to implement this in OpenTelemetry? Is there a good way to pass these values to parent spans and eventually to the root span? I've looked into Baggage but that appears to mainly be used to update a context for passing down the call stack, not up. -
How to get the name of the file that the user can download?
I have a django view that returns a FileResponse - return FileResponse(protected_pdf_file, as_attachment=True, filename='result.pdf') I am getting this response using ajax - function ajaxSend(url, data) { fetch(url, { method: 'POST', body: data, }) .then(response => { if (content_type === 'application/json') { return response.json(); } else { return response.blob(); } }) .then(data => { if (data instanceof Blob) { const url = URL.createObjectURL(data); download_link.href = url; // download_link.download = ... download_link.style.display = 'block'; } else { block_msg.textContent = data.message; } }) .catch(error => console.error(error)) } Where "download_link.download = ..." I need to substitute the file name. I tried to get the file name - const contentDisposition = response.headers.get('Content-Disposition');, but contentDisposition is null as a result. Please tell me how to get the name of the file returned from the server? -
I cannot connect pip to download any packages
I am new to programming, but my computer seems unable to utilise pip, here is an example of an error I got, I've also tried extending the duration of the connect (forcibly closed by connection host) and tried a tonne of different ways to ask it to install django even specific versions anything that requires connection through pip does not work, ive diabled ipv6 and completely turned off all my firewall safety's, jumbo packets arent a system setting I can change I feel like I'm running out of ideas here, I've been to about 150 different pages today, my goal was to get django working, which I have successfully created a virtual environment for and used git to put django into, but when I attempt to finish setting up django by installing that way in the environment, it needs to download dependencies from somewhere which again result in it getting stuck, can my computer not communicate properly with the websites? I can use curl to view the sources that were layed out and both curl and ping show a perfectly fine connection to these places, I am on a stable internet connection and have tried using a different internet connection … -
Modify Django "Select Form" Icon
I am making a Django app, and I am using Django's form.ChoiceFields to make a form! brand = forms.ChoiceField( label="Marca:", choices=[('', 'Selecionar marca')] + [(brand.id, brand.name) for brand in models.Brand.objects.all()], widget=forms.Select(attrs={'id': 'brand', 'onchange': 'filterModels()', 'class': 'select'}) ) So this is the form element that I get (with a background color), but I want to change the icon pointing up and down in the right but I cannot figure how to do it. I already tried to do it by adding an icon form FontAwesome but the problem is that when I do so, when I click on the icon the form does not open, so it can confuse the users :( I tried adding javascript codes by using implementing the click() function when clicking on the icon but it did not give me any results. So is there a way to do this by simply replacing Django's "Select Form" default arrow icon? Thanks in advance! -
How can I achieve filtering with multiple values for the same parameter in Django?
I am building a Django website that displays snowboards that will fit you based on some parameters. One of the parameters is gender and for example if the user specifies she is a girl, then I want to display Female as well as Unisex boards - and also then filter again by all the other parameters (height, style, level, etc). Same for the boys. I want to also display Male boards as well as Unisex boards. This is the code snippet in my TemplateView: def get(self, request, *arg, **kwargs): gender = request.GET.get('gender') skills = request.GET.get('skills') style = request.GET.get('style') rider_name = request.GET.get('rider_name').split("'")[1].split("'")[0] filter = process_queryset(gender, skills, style) queryset = Snowboard.objects.filter( gender=filter['gender'], style=filter['style'], level=filter['level'], ) return render(request, self.template_name, {'gender': gender, 'snowboards': queryset, 'rider_name': rider_name}) and I have this separate function for processing the filtering: def process_queryset(gender, skills, style): filter_dict = {'gender': 'Female' if gender == 'girl' else 'Male', 'level': 'Beginner' if 'rookie' in skills else 'Intermediate-Advanced'} if style == 'freestyle': filter_dict['style'] = 'Park' elif style == 'freeride': filter_dict['style'] = 'Free Ride' else: filter_dict['style'] = 'All mountain' return filter_dict So I first tried to filter by the gender and have them both (tried both with | and with &) and then nest the … -
Change the parent lookup kwarg in nested routes using Django REST Framework
In this project we use Django, Django REST Framework, DRF Nested Routers and DRF Spectacular. Let's say that we have the model classes Category and Product. We have a nested route: /categories/<category_pk>/products/<pk>/ In the Swagger UI (generated by DRF Spectacular) it is displayed as: /categories/{category_pk}/products/{id}/ I want to change the parent lookup keyword argument to be category_id, but I couldn't find a way to do it. -
I want to genarete report from different modals which are related by foriegn key
class ReporttListView(LoginRequiredMixin,ListView): model = Assignments context_object_name='assignments' template_name="workshop/report.html" login_url='workshop:custom_login' def get_queryset(self): # Filter the assignments by is_valid=True and prefetch the related item and component models return Assignments.objects.filter(is_valid=True).prefetch_related('item', 'item__component_set') class Item(models.Model): """ This is the item model has five fields name,stock_id,serial_no, status(pending,accepted,completed,not maintable),remark """ ws_id = models.CharField(max_length=15) received_date=models.DateField(auto_now=1) stock_id = models.CharField(max_length=15) Serial_no =models.CharField(max_length=15) delivered_by = models.CharField(max_length=100) received_by= models.CharField(max_length=100) status = models.CharField(choices=( ('pending', "pending"), ('on_prograss', "On_progress"), ('completed', "Completed"), ('Not maintainable', "Not maintanable"), ),default='pending' , auto_created=True ) remark= models.TextField(blank=True) is_valid=models.BooleanField(auto_created=True,default=True) is_accepted=models.BooleanField(auto_created=True,default=False) is_maintainable=models.BooleanField(auto_created=True,default=True) def __str__(self) -> str: return self.Serial_no def get_absolute_url (self): return reverse("workshop:item") class Component(models.Model): recived_date=models.DateField(auto_now=True) item = models.ForeignKey(Item, on_delete=models.CASCADE, related_name='components') stock_id = models.CharField(max_length=15) Serial_no =models.CharField(max_length=15) is_valid=models.BooleanField(auto_created=True,default=True) def __str__(self) -> str: return self.Serial_no def get_absolute_url (self): return reverse("workshop:component") class Section(models.Model): name = models.CharField(max_length=100) manager = models.ForeignKey(User, on_delete=models.CASCADE) is_valid=models.BooleanField(default=True) def __str__(self) -> str: return self.name class Assignments(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE) engineer= models.ForeignKey(User, on_delete=models.CASCADE) Section= models.ForeignKey(Section, on_delete=models.CASCADE) remark= models.TextField(blank=True) Assigned_date=models.DateField(auto_now=True) completed_date=models.DateField(default="2023-11-02",auto_created=True) is_valid=models.BooleanField(auto_created=True,default=True) def __str__(self) -> str: return str(self.item) I want my report contains list of components that is related to every assigned Item . In orrder to achieve this role . I have the above class based view. but my system did not work.It show me the below error. AttributeError at /report Cannot find 'component_set' … -
Using Crispy forms in my Django project and the input field appears to be too small
When I see other examples people can make the entire field screen-wide. Like this: Bootstrap example However what appears on my screen is too small: My example How can I fix it? For reference, I'm using Bootstrap v4.5.3 Code: models.py from django.db import models from django.utils import timezone from django.core.validators import FileExtensionValidator # Create your models here. class Video(models.Model): title = models.CharField(max_length=100) description = models.TextField() video_file = models.FileField(upload_to='uploads/video_files', validators = [FileExtensionValidator(allowed_extensions=['mp4', 'mkv'])]) thumbnail = models.FileField(upload_to='uploads/thumbnails', validators = [FileExtensionValidator(allowed_extensions=['png', 'jpeg', 'jpg'])]) date_posted = models.DateTimeField(default=timezone.now) create_videos.html {% extends 'videos/base.html' %} {% load crispy_forms_tags %} {% block content %} <div class="container mb-5"> <div class="row justify-content-center"> <div class="col-md-6 col-sm-12 col-xs-12"> <form method="post" enctype="multipart/form-data"> {% csrf_token %} <legend class="border-bottom mb-4">Upload video</legend> {{ form | crispy }} <div class="col-md-4 ml-auto"> <button class="btn btn-outline-primary btn-block mt-3">Upload</button> </div> </form> </div> </div> </div> {% endblock content %} I have tried: Messing with the 3rd to change col-md size. Editing individual fields (mainly 'title' and 'description') with {{ form.field | as_crispy_field }}. -
ImportError: DLL load failed while importing _psycopg: The specified module could not be found. and i use pip instal psycopg2 and the binary one
enter image description here I can't access tp psycopg2 no error and access to psycopg2 and not connected to django project show error no module found and server can't run and i use pip instal psycopg2 and the binary one (myvenv) C:\Users\justp>python -c "import psycopg2" Traceback (most recent call last): File "", line 1, in File "C:\Users\justp\myvenv\Lib\site-packages\psycopg2_init_.py", line 51, in from psycopg2._psycopg import ( # noqa ImportError: DLL load failed while importing _psycopg: The specified module could not be found. (myvenv) C:\Users\justp>pip freeze -
Netsuite - Multiple Page Forms / Multi Step Forms
Is there a way to setup multiple paged form in Netsuite (or Hubspot) or somehow reorganize it custom after integration in a website. Not a problem if the page is updating or fetching the next field element. The most important is the multi-page structure (as a kind of quiz card) and the completeness of the arranged data. Working on django/js, kind of PRG pattern. Have tried to use the pagination libraries or sliders to give that effect through putting the timeout after the form mounting. Didn't really work. -
Binding Ajax Search Result To TextField
The search functionality that I have implemented using Ajax works as expected, the problem that I am facing is I couldn't find a solution to bind the search result to the text field when I click an item from the search result. The Ajax search results are displayed using resultBox and the input text field used for searching is SearchInput. Upon clicking an item in the resultBox the value needs to be binded to the searchInput. But currently when I click the item in the resultBox the page is getting refreshed. console.log("Sanity check!"); const url = window.location.href window.onload = function() { const searchForm = document.getElementById("search-form") const searchInput = document.getElementById("search-box") const resultBox = document.getElementById("results-box") const csrf = document.getElementsByName("csrfmiddlewaretoken")[0].value const sendSearchData = (stock_name) =>{ $.ajax({ type: "POST", url: '', data:{ 'csrfmiddlewaretoken' : csrf, 'stock_name':stock_name }, success: (res) =>{ console.log(res.data) const data = res.data if (Array.isArray(data)) { resultBox.innerHTML= "" data.forEach(stock_name =>{ resultBox.innerHTML += ` <a href="" style="text-decoration : none;"> <div> <p> ${stock_name.symbol_name} </p> <small> ${stock_name.symbol}</small> </div> </a> ` }) } else { if (searchInput.value.length > 0) { resultBox.innerHTML =`<b>${data}</b>` } else { resultBox.classList.add('not-visible') } } }, error: (err) =>{ console.log(err) } }) } searchInput.addEventListener('keyup',e=> { console.log(e.target.value) if (resultBox.classList.contains('not-visible')){ resultBox.classList.remove('not-visible')} sendSearchData(e.target.value) }) } Please … -
i am facing django.db.migrations.exceptions.InvalidBasesError Cannot resolve bases, when i run python manage.py migrate
I have two apps, coreapp and product app. As all models in product app have common fields , i created a BaseModel in coreapp and then inherited the BaseModel in the models in product app. Then i ran python manage.py makemigrations and python manage.py migrate. After that i made some changes in the models, I added abstract = True in BaseModel and renamed some fields in the models in product app. Then i ran python manage.py makemigrations. Now, when i run python manage.py migrate i get the following error django.db.migrations.exceptions.InvalidBasesError: Cannot resolve bases for [<ModelState: 'product.Attribute'>, <ModelState: 'product.Category'>, <ModelState: 'product.Product'>, <ModelState: 'product.AttributeValue'>] This can happen if you are inheriting models from an app with migrations (e.g. contrib.auth) in an app with no migrations; see https://docs.djangoproject.com/en/4.1/topics/migrations/#dependencies for more Below are the two models coreapp/models.py from django.db import models # Create your models here. class BaseModel(models.Model): created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) product/models.py from django.db import models from project_root.coreapp.models import BaseModel # Create your models here. class Attribute(BaseModel): title = models.CharField(max_length=100) def __str__(self): return self.title class AttributeValue(BaseModel): title = models.CharField(max_length=100) attribute_object = models.ForeignKey(Attribute,on_delete=models.CASCADE, related_name='attribute_values') def __str__(self): return self.title class Category(BaseModel): title = models.CharField(max_length=200) parent= models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True) def __str__(self): return self.title … -
session cookie is working in other browser
I created log in system in Django using session(not using built in functionality), Now I face issue like : if I log in into one private tab/in my browser then Django create on cookie named "sessionid" and if I create same cookie on other pc or other browser window(Except current log in window) then that also works and shows user is logged in. Why this problem occur and how i can solve this? I want the solution of this problem and explanation why this happens? -
Creating a range of objects at once in django
I am creating a set of numbers and I want to save each of them in the database. My approach is: class NbrSetForm(forms.ModelForm): last_number = Nbr.objects.order_by("-number").first().number start_number = forms.IntegerField(required=True, initial=last_number+1) end_number = forms.IntegerField(required=True, initial=last_number+1) class Meta: model = Nbr fields = ["start_number", "end_number", ...] exclude = ["number"] def clean(self): cleaned_data = super().clean() s = int(cleaned_data["start_number"]) e = int(cleaned_data["end_number"]) + 1 self.number_list = [n for n in range(s, e)] def save(self, commit=False): for n in self.number_list: print("number to create", number) instance = Nbr.objects.create(number=n, ...) print("all done", instance) return super.save(self) I can see the output of both of the print statements in the console (number has a reasonable value here). But nothing is saved to the database and I get an IntegretyError from the return super().save(self) statement (I guess it's this one) saying: NOT NULL constraint failed: app_nbr.number. -
How to improve a complex django code to reduce database queries and avoid loops?
This code is currently making a separate query to the database for each module in the queryset, because I need to have the progress for each of them. I would like to improve the code so that it makes a single query (or as less queries as possible) to the database and does not use a loop. Can anyone help me with this? This was the best I've got. def get_queryset(self): return CourseLanguage.objects.prefetch_related( "modules", "users" ).filter( pk=self.kwargs["course_language_pk"] ).first() @property def modules(self): modules = [] queryset = self.get_queryset().modules.all().values() for module in queryset: percentage = UserContentAnswer.objects.filter( user=self.request.user, content__topic__module__pk=module["id"] ).aggregate( total=Count("pk"), completed=Count("pk", filter=Q(status=ContentStatusType.COMPLETED)), progress=ExpressionWrapper( Case( When(total=0, then=Value(0.0)), default=100.0 * F("completed") / F("total"), ), output_field=FloatField() ), )["progress"] modules.append( { **module, "percentage": f"{percentage:.1f}" } ) return modules -
Docker build failed [insufficient_scope: authorization failed]
I am trying to build an image for a django project. I tried '''sudo docker login''', after that also same error message. tried in macOS M1 & rasberrypi 4B. **Dockerfile: FROM python3.9.2-slim ENV PYTHONUNBUFFERED 1 RUN sudo apt update -y && sudo apt upgrade -y RUN mkdir /app WORKDIR /app COPY requirements.txt /app/ RUN pip install --user -r requirements.txt COPY . /app/ CMD python3 manage.py runserver Output(sudo docker build . -t ttapp-image): [+] Building 2.1s (4/4) FINISHED docker:default => [internal] load build definition from Dockerfi 0.0s => => transferring dockerfile: 279B 0.0s => [internal] load .dockerignore 0.0s => => transferring context: 2B 0.0s => ERROR [internal] load metadata for docker.io/l 2.0s => [auth] library/python3.9.2-slim:pull token for 0.0s ------ > [internal] load metadata for docker.io/library/python3.9.2-slim:latest: ------ Dockerfile:1 -------------------- 1 | >>> FROM python3.9.2-slim 2 | 3 | ENV PYTHONUNBUFFERED 1 -------------------- ERROR: failed to solve: python3.9.2-slim: pull access denied, repository does not exist or may require authorization: server message: insufficient_scope: authorization failed