Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django URLs not updating after slug change
I use Slugify. After making a change in slug for all objects in Entry, slug still shows as old slug. If I refresh obj page, I get a page not found, unless I click "back" and then reopen the obj page, and that is when the obj page will load and new slug will update. Any idea how to fix this? I tried an empty migration and applied obj.save() and obj.refresh_from_db() but no luck. Below is my model, this is what generates my slug field: (My change was removed self.4 and replaced with self.5) class Entry(models.Model) 1 = ... 2 = ... 3 = ... 4 = ... 5 = ... slug = models.SlugField(null=True, unique=True, max_length=300) def save(self, *args, **kwargs): self.slug = slugify(f"{self.1}-{self.2}-{self.3}-{self.5}") return super().save(*args, **kwargs) def get_absolute_url(self): return reverse("page", kwargs={"slug": self.slug}) -
Subtract the Quantity in django
I am developing a inventory management and I have to subtract the Quantity from 2 different forms data and display the available quantity. Below is my views.py def my_form2(request): if request.method == "POST": form2 = MyForm2(request.POST) if form2.is_valid(): form2.save() return HttpResponse('Submitted Successfully') else: form2 = MyForm2() return render(request, "authentication/Incoming_QC.html", {'form2': form2}) def View_Incoming_QC(request): Incoming_QC_list = Incoming_QC.objects.all() return render(request, 'authentication/View_Incoming_QC.html', {'Incoming_QC_list': Incoming_QC_list}) def my_form3(request): if request.method == "POST": form3 = MyForm3(request.POST) if form3.is_valid(): form3.save() return HttpResponse('Submitted successfully') # return redirect('/home_page/') else: form3 = MyForm3() return render(request, "authentication/Manufacturing.html", {'form3': form3}) def View_Manufacturing(request): Manufacturing_list = Manufacturing.objects.all() return render(request, 'authentication/View_Manufacturing.html', {'Manufacturing_list': Manufacturing_list}) def my_form5(request): if request.method == "POST": form5 = MyForm5(request.POST) if form5.is_valid(): form5.save() return HttpResponse('Submitted successfully') # return redirect('/home_page/') else: form5 = MyForm5() return render(request, "authentication/Material.html", {'form5': form5}) def View_Material(request): Material_list = Material.objects.all() return render(request, 'authentication/View_Material.html', {'Material_list': Material_list}) Below is the models.py class Incoming_QC(models.Model): alphanumeric = RegexValidator(r'^[\s0-9a-zA-Z\.-_]*$', 'Only alphanumeric characters are allowed.') Manufacturing_PN = models.CharField(max_length=200, validators=[alphanumeric]) Quantity = models.IntegerField() class Manufacturing(models.Model): alphanumeric = RegexValidator(r'^[\s0-9a-zA-Z\.-_]*$', 'Only alphanumeric characters are allowed.') Manufacturing_PN = models.CharField(max_length=200, validators=[alphanumeric]) Completed_Quantity = models.IntegerField(blank=True, default='') class Material(models.Model): alphanumeric = RegexValidator(r'^[\s0-9a-zA-Z\.-_]*$', 'Only alphanumeric characters are allowed.') Manufacturing_PN = models.CharField(max_length=200, validators=[alphanumeric]) Quantity = models.IntegerField() .html file to view the data <!DOCTYPE html> <html … -
AttributeError: module 'rest_framework.serializers' has no attribute 'validationError'
def validate_name(self,value): qs=contact.objects.filter(name=value) if qs.exists(): raise serializers.validationError(f"{value} is already in contact name") return value error: in validate_name raise serializers.validationError(f"{value} is already in contact name") AttributeError: module 'rest_framework.serializers' has no attribute 'validationError' validate the name is already exists -
django find user organization by user uid
I'm trying to get user organization by user uid. I have an Organization model with the user field as ForeignKey(User) and I have the user UID, Is there any way to find the organization by the uid without querying out the user id by the uid and then finding the organization by the id? ` user_uid = "some uid" user= User.objects.get(uid=uid) Organization.objects.filter(user=user) ` how can I avoid two queries? -
Uploading multiple files using React and DRF returns success/200 but no objects created and no files saved
Trying to upload multiple files using React and DRF. I get a 200 response, but nothing actually gets saved to the database and no files are created. No issues if I remove the many=True from the serializer constructor and just upload a single file. React Post Code: const handleSubmit = (e) => { e.preventDefault(); let formData = new FormData(); for (let i = 0; i < uploadedFiles.length; i++) { formData.append('file', uploadedFiles[i]); } axiosInstance.post("productmedia/", formData, {headers: {'content-type': 'multipart/form-data'}}); }; Model class ProductMedia(models.Model): name = models.CharField(max_length=200, null=True, blank=True) file = models.FileField(upload_to=upload_to) product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='media', null=True, blank=True) Serializer class ProductMediaSerializer(serializers.ModelSerializer): class Meta: model = ProductMedia fields = ('file',) View class ProductMediaViewSet(viewsets.ModelViewSet): serializer_class = ProductMediaSerializer queryset = ProductMedia.objects.all() def create(self, request, *args, **kwargs): serializer = ProductMediaSerializer(data=request.data, many=True) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_200_OK) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
samesite none without secure browser
I'm developing with React and Django. The original plan was to send api requests from the front to the Django server to manage sessions and read data, but it seems that cookies cannot be stored in the browser due to the samesite problem on the localhost used as a test during development. (It works in postman) And when React and Django are run on the server, there is no problem with the session, so samesite=none that can be tested during development, but an environment that does not require secure is required. Try: Use old version firefox Django - check cookies's "SameSite" attribute CSRF_COOKIE_SECURE = True SESSION_COOKIE_SECURE = True CSRF_COOKIE_SAMESITE = 'None' SESSION_COOKIE_SAMESITE = 'None' Use axios proxy https://pypi.org/project/django-samesite-none/ (django middleware) -
Get related user model field using drf-writable-nested serializer in django
I'm a little stuck with something that might be very simple. I have a model that is related to a user: class Cheatsheet(VoteModel, models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) title = models.CharField(max_length=500, null=True, blank=True, default="") description = models.CharField( max_length=500, null=True, blank=True, default="") tags = TaggableManager(blank=True) def __str__(self): return self.title I have the following serializer, I'm using drf-writable-nested because I have deeply nested models and it eases creation and updates. class CheatsheetSerializer(TaggitSerializer, WritableNestedModelSerializer): sections = SectionSerializer(many=True, required=False) tags = TagListSerializerField(required=False) class Meta: model = Cheatsheet fields = ("id", "sections", "tags", "vote_score", "title", "description", "user") And the following View class CheatsheetViewSet(viewsets.ModelViewSet, VoteMixin): queryset = Cheatsheet.objects.all() serializer_class = CheatsheetSerializer http_method_names = ['get', 'post', 'retrieve', 'put', 'patch', 'delete'] When I do GET: /cheatsheets/14/ I get the following response: { "id": 14, "sections": [], "tags": [ "css", "javascript" ], "vote_score": 0, "title": "New Cheatsheet", "description": "description test", "user": 1 } I want to receive the username aswell in my response. So I proceded to create a UserSerializer from django.contrib.auth.models import User class UserSerializer(serializers.Serializer): username = serializers.CharField() id = serializers.IntegerField() class Meta: model = User fields = ['id', 'username'] and modified my CheatsheetSerializer: user = UserSerializer() Now I get the username aswell, but POST and PUT … -
Django Base Page is blank
I'm following this tutorial to learn Django and I've followed part 4 as in the video, but when I reload my page, it's always blank. I've looked at other posts that were also experiencing a blank page, but they don't address my issue and are very old. Some more info: I'm using Django 4.1.4 and all the files are appropriately saved and named like in the video. This is my views.py: from django.shortcuts import render from django.http import HttpResponse from .models import ToDoList, Item # Create your views here. def index(response, id): ls = ToDoList.objects.get(id=id) return render(response, 'main/base.html', {}) def home(response): return render(response, 'main/home.html', {}) base.html: <html> <head> <title> My Website </title> </head> <body> <p> Base Template</p> <h1> HELLO </h1> </body> </html> home.html: {% extends 'main/base.html' %} I don't know if this issue is caused by a mistake I'm not finding or a version error. -
How to make a model's instance value dependent of another model instance(as an attribute)
Basically, I am trying to have an endpoint that acts as a property of my User model. What I want my Django program to perform: I want a User instance to have its own unique friend model in which it will have its own friends. My problem: Each User instance have the same friends(so, the same friend model value). My code: # MODELS.PY class friend(models.Model): my_tag = User.usertag friend_tag = models.CharField(max_length=7, primary_key=True) class User(models.Model): f_name = models.CharField(max_length=15) l_name = models.CharField(max_length=15) usertag = models.CharField(max_length=7, default="no tags inputed!") level = models.IntegerField(default=1) profile_pic = models.URLField(max_length=10000) email = models.EmailField(max_length=100) password = models.CharField(max_length=25) # Views.py class listFriends(generics.ListAPIView): queryset = friend.objects.all() serializer_class = FriendSerializer permission_classes = [permissions.IsAuthenticated] lookup_field = "my_tag" lookup_url_kwarg = "username" list_friends = listFriends.as_view() -
Django AWS S3 object storage boto3 media upload error
I used django docker and aws s3 bucket for my project. I configure my settings file for my bucket and it is working but i got an error while uploading media files "expected string or bytes-like object" and docker log error if not VALID_BUCKET.search(bucket) and not VALID_S3_ARN.search(bucket). I used django forms and function based view. models.py def user_directory_path(instance, filename): tenant = connection.get_tenant() return 'profile_photos/{0}/{1}'.format(tenant, filename) class UserProfilePhoto(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) profilephoto = models.ImageField(blank=True,default="profile_photos/profilephoto.png",upload_to=user_directory_path ) views.py def userprofile(request,id): get_object_or_404(User,id = id) if request.user.userprofile.status == 3 or str(request.user.id) == str(id): now_today = datetime.now(pytz.timezone('Europe/Istanbul')) announcements=Announcements.objects.filter(announce_type="announcement") current_page="Kullanıcı Profili" user=User.objects.filter(id=id).first() user_doc_create=InsuranceFile.objects.filter(file_creator=user.username) user_doc_create_last_month=InsuranceFile.objects.filter(file_creator=user.username, created_at__gte=now()-relativedelta(months=1)).count() ratio_of_doc = ratio_utils(user_doc_create_last_month,user_doc_create.count()) user_doc_update=InsuranceFile.objects.filter(file_updater=user.id) user_doc_update_last_month=InsuranceFile.objects.filter(file_updater=user.id, updated_at__gte=now()-relativedelta(months=1)).count() ratio_of_doc_update = ratio_utils(user_doc_update_last_month,user_doc_update.count()) path_check=str("/account/userprofile/"+ id) profilephoto=UserProfilePhoto.objects.filter(user=request.user).first() previous_profilephoto=profilephoto.profilephoto form_user=CreateUserForm(request.POST or None , instance=request.user) form_userprofile=UserProfileForm(request.POST or None , instance=request.user.userprofile) form_userphoto=UserProfilePhotoForm(request.POST or None,request.FILES, instance=request.user.userprofilephoto,) is_confirmed=False if TOTPDevice.objects.filter(user_id=id).first(): totp=TOTPDevice.objects.filter(user_id=id).first() is_confirmed=totp.confirmed if request.method == 'POST': if form_userphoto.is_valid() and form_userprofile.is_valid() and form_user.is_valid(): with transaction.atomic(): form_userprofile.save() if str(request.FILES) != "<MultiValueDict: {}>": upload_profile_photo(request,form_userphoto,user,previous_profilephoto) messages.success(request,"Profil başarılı bir şekilde güncellendi.") return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/')) return render(request,'userprofile.html',{"now_today":now_today,"ratio_of_doc_update":ratio_of_doc_update,"user_doc_update_last_month":user_doc_update_last_month,"user_doc_update":user_doc_update,"announcements":announcements,"current_page":current_page,"user_doc_create_last_month":user_doc_create_last_month,"ratio_of_doc":ratio_of_doc,"user_doc_create":user_doc_create,"path_check":path_check,"profilephoto":profilephoto,"is_confirmed":is_confirmed,"user":user,"form_userprofile":form_userprofile,"form_userphoto":form_userphoto,"form_user":form_user}) messages.warning(request,"Bu işlemi yapmaya yetkiniz bulunmamaktadır.") return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/')) upload*_profile function* import boto3 def upload_profile_photo(request,form_userphoto,user,previous_profilephoto): s3 = boto3.client('s3', aws_access_key_id="AKIAW7UXTA7VBPUVLPGW", aws_secret_access_key= "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") if previous_profilephoto != "profile_photos/profilephoto.png": s3.delete_object(Bucket='dj-crm-tenant', Key= f'media/{previous_profilephoto}') form_userphoto.save() settings.py 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_S3_CUSTOM_DOMAIN = … -
error when giving mysql as the database (engine) in Django
In my web application which is being made in Django (Django==3.2), I am trying to use mysql as the Database, but in the settings.py, when I tried to give mysql as the engine : 'ENGINE': 'django.db.backends.mysql' and then tried ruserver command, I got the following error: Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/home/john/PycharmProjects/social_network/venv/lib/python3.6/site-packages/django/db/utils.py", line 111, in load_backend return import_module('%s.base' % backend_name) File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 941, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked ModuleNotFoundError: No module named 'django.db.backends.mysql' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/usr/lib/python3.6/threading.py", line 916, in _bootstrap_inner self.run() File "/usr/lib/python3.6/threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "/home/john/PycharmProjects/social_network/venv/lib/python3.6/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/home/john/PycharmProjects/social_network/venv/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "/home/john/PycharmProjects/social_network/venv/lib/python3.6/site-packages/django/utils/autoreload.py", line 87, in raise_last_exception raise _exception[1] File "/home/john/PycharmProjects/social_network/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 375, in execute autoreload.check_errors(django.setup)() File "/home/john/PycharmProjects/social_network/venv/lib/python3.6/site-packages/django/utils/autoreload.py", line 64, … -
How do I get every choice belonging to each poll?
Please I need help getting all queries. Here am getting just the data for the second poll only. I have two poll created but the data of the first one is not been sent to the frontend if I use print it will be printed in the terminal def index(request): context = {} instruction = "" candidate_data = [] positions = Position.objects.order_by('priority').all() for position in positions: query = position.candidates.all() if position.max_vote > 1: instruction = "You may select up to " + str(position.max_vote) + " candidates" else: instruction = "Select a candidate" context = { 'positions': positions, 'query': query, 'candidate_data': candidate_data, 'instruction': instruction, } return render(request, 'poll/index.html', context) This my frontend logic <div class="row"> <div class="mt-5"> {% for position in positions %} {{ position.name }} <br> {{ instruction }} <br> {% endfor %} {% for c in query %} {{ c.fullname }} {{ c.id }} <p>{{ c.bio }}</p> <img src="/media/{{ c.photo }}" alt="" width="200" height="200"> {% endfor %} </div> </div> -
Slugs not appearing in URLS
I want my slugs to show up in my URLS instead of the number ID of the image that is being viewed. I can't seem to get it working. Can anyone spot what I'm missing/doing wrong? TYIA models.py: class PostImage(models.Model): image = models.ImageField(null=False, blank=False, upload_to="images", default="default.png") image_title = models.CharField(max_length=100, null=False, blank=False, default="") slug = models.SlugField(null=True) def save(self, *args, **kwargs): self.slug = self.slug or slugify(self.title) super().save(*args, **kwargs) def __str__(self): return self.image_title class Meta: verbose_name_plural = 'PostImage' views.py: def galleryPage(request): images = PostImage.objects.all() context = {'images':images} return render(request, 'gallery.html', context) def viewImage(request, slug): photo = PostImage.objects.get(id=slug) return render(request, 'viewimage.html', {'photo': photo, 'slug': slug}) urls.py: path('viewimage/<slug:slug>/', views.viewImage, name='viewimage'), admin.py: @admin.register(PostImage) class PostAdmin(admin.ModelAdmin): prepopulated_fields = {'slug': ('image_title',)} -
Tastypie: ending empty POST with no request, and to a path parameter URL
I need to create two POST request with url: /create with raw body: {some JSON}, I'm able to do this, with a obj_create method provided by tastypie. /create/4, I'm stuck at this, which has the same endpoint but with a path parameter and no body. I've the following questions for which I could not figure out answers from documentation/stack overflow: Is is possible to send POST request in tastypie without a body this post request does not goes to obj_create, what is the corresponding method in tastypie to receive such post requests with path parameter and no body. Thanks for the help. -
Trouble with the password hashing and salting
I'm trying to implement a login system for my web application, but I'm having trouble with the password hashing and salting. My current code is generating different hash values for the same password, and I'm not sure what I'm doing wrong. Can anyone help me troubleshoot this issue? Here is the relevant code: import hashlib import random def hash_password(password): salt = random.randint(0, 1000000) hashed_password = hashlib.sha256((password + str(salt)).encode()).hexdigest() return (hashed_password, salt) password = 'password123' hashed_password, salt = hash_password(password) print(hashed_password) Any help would be greatly appreciated! -
partial update in django rest viewset(not modelviewset)
i am beginner in django and i was trying to learn work with djangorest viewset(not modelviewset) and i cant find any resource to undrestand it. i want to learn how to write a partial_update in with viewset. here is what i have tried: models.py : class UserIdentDocs(models.Model): owner = models.ForeignKey(User,on_delete=models.CASCADE, related_name = "user_ident_Docs") code = models.PositiveBigIntegerField(null=True) img = models.ImageField(null=True) video = models.FileField(null=True) is_complete = models.BooleanField(default=False) serializers.py: class AdminUserIdentSerializer(serializers.ModelSerializer): class Meta: model = UserIdentDocs fields = [ "owner", "code", "img", "video", "is_complete", ] views.py: from rest_framework.parsers import MultiPartParser, FormParser class UserDocAdminViewSet(viewsets.ViewSet): """User docs admin view set""" permission_classes = [AllowAny] parser_classes = (MultiPartParser, FormParser) serializer_class = AdminUserIdentSerializer queryset = UserIdentDocs.objects.filter(is_complete=False) def list(self, request): serializer = self.serializer_class(self.queryset, many=True) return Response(serializer.data) def retrive(self, request, pk=None): doc_object = get_object_or_404(self.queryset, pk=pk) serializer = self.serializer_class(doc_object) return Response(serializer.data) def create(self, request ): serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data,status=status.HTTP_201_CREATED) def partial_update(self, request, pk=None): doc_object = get_object_or_404(self.queryset, pk=pk) serializer = self.serializer_class(doc_object,data=request.data) serializer.is_valid(raise_exception=True) serializer.save() return Response({"detail":"item updated succesfuly"}, status=status.HTTP_205_RESET_CONTENT) urls.py: urlpatterns = [ ... # admin viewset for docs # list of accounts with is_complete=False path("admin/userdocs/", UserDocAdminViewSet.as_view({"get":"list", "post":"create"}), name="user-docs-list"), path("admin/userdocs/<int:pk>", UserDocAdminViewSet.as_view({"get":"retrive","patch":"partial_update"}), name="user-docs-detail"), ] i cant create user in browsable api but when i want to use partial update i can't … -
Celery can't find .settings
I installed redis and celery, set everything up, I run celery in terminal - everything is ok: (venv) Air-Evgeny:gunter_site evgenybar$ celery -A gunter_site worker -l info -------------- celery@Air-Evgeny.Dlink v5.2.7 (dawn-chorus) --- ***** ----- -- ******* ---- macOS-13.0.1-x86_64-i386-64bit 2023-01-02 18:35:10 - *** --- * --- - ** ---------- [config] - ** ---------- .> app: gunter_site:0x106d5a3a0 - ** ---------- .> transport: redis://127.0.0.1:6379/0 - ** ---------- .> results: - *** --- * --- .> concurrency: 4 (prefork) -- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker) --- ***** ----- -------------- [queues] .> celery exchange=celery(direct) key=celery [tasks] . gunter_site.celery.debug_task Next, through the Python console, I try to run debug_task.delay() from celery.py to check that everything is working fine: >>> from gunter_site.gunter_site.celery import debug_task ^Everything is ok at this stage >>> debug_task.delay() ^Here I get a long list of problems that end with: ModuleNotFoundError: No module named 'gunter_site.settings' Redis launched in docker: docker run -p 6379:6379 --name redis-celery -d redis Redis work: evgenybar@Air-Evgeny ~ % docker ps -a CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 01d5f6356e0f redis "docker-entrypoint.s…" 2 hours ago Up 2 hours 0.0.0.0:6379->6379/tcp redis-celery I have already tried to create a test project with an older … -
i am creating a shayri app in android studio , and using django admin as a backend
My app is simple , django backend has only one model named AddShayri and it has feature image and description as a field . right now i created an api in django . but it is public . i want to protect it using api key . how will i do that ? -
Vue JS Form data not sending to Django Rest database
Im doing a project that include Django, django rest and vue js. I am able to get information from api to vue js frontend. But when I try and use Vue Js frontend to post data in a form after clicking the button nothing posts to django database Ive tried different things but nothing works appreciate any help thanks. heres my vue code: AllNotes.vue <template> <div class="notes_container"> <div class="add_note"> <form v-on:@submit="submitForm"> <div class="form-group"> <label for="content">Content</label> <input type="text" class="form-control" id="content" v-model="content" /> </div> <div class="form-group"> <button>Add Note</button> </div> </form> </div> <div class="note_content"> <h1>Tweets</h1> <ul class="note_list"> <li v-for="note in notes" :key="note.id"> <p>"{{ note.content }}""</p> <button @click="toggleNote(note)"> {{ note.completed ? "Undo" : "Complete" }} </button> <button @click="deleteNote(note)">Delete</button> </li> </ul> </div> </div> </template> <script> import axios from "axios"; export default { data() { return { notes: [], content: "", }; }, methods: { async getData() { try { // fetch tasks axios.get("http://localhost:8000/notes/").then((response) => { this.notes = response.data; }); // set the data returned as tasks } catch (error) { // log the error console.log(error); } }, }, submitForm: function () { // Send a POST request to the API axios .post("http://localhost:8000/notes/", { note: this.content }) .then((response) => { this.content = ""; this.notes.push(response.data); }); // … -
Browsers not caching images from s3
I'm hosting my personal portfolio on AWS Elastic Beanstalk, using s3 to store all the data, such as images, entries etc. This uses Django for the backend, and Reactjs for the frontend. When loading the content, the browser makes a request which gets these datapoints const getAllNodes = () => { fetch("./api/my-data?format=json") .then(response => response.json()) .then((data) => { setMyData(data); }); }; The returned values are the file image urls, something along the lines of https://elasticbeanstalk-us-east-1-000000000000.s3.amazonaws.com/api/media/me/pic.png with the following options ?X-Amz-Algorithm=XXXX-XXXX-XXXXXX &X-Amz-Credential=XXXXXXXXXXXXXXXXXXXXus-east-1%2Fs3%2Faws4_request &X-Amz-Date=20230102T182512Z &X-Amz-Expires=600 &X-Amz-SignedHeaders=host &X-Amz-Signature=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX When using this method of image storage and retreival, the images don't seem to be cached on the browser, so they have to be fetched every time, and slow down the site's functioning on subsequent visits. The following is a screenshot of the network tab when loading my site. How should I handle this situation? I would like to store the images in the database (and therefore on s3) so I can update them as necessary, but also have the advantage of having them be cached -
How to relate two tables with one of the field equal?
I am new with django and django rest framework. Excuse me for my bad english... I am trying to relate two django models: First one (class ModulMess) receives messages from remote numbered modules -moduleA received message "AAA". -moduleB received message "BBB" -moduleA received message "CCC" -moduleC received message "DDD"... Second one (class Owner) is a list of users who own the modules -UserXX owns moduleA and moduleC -UserYY owns moduleB... I am tryng to make search filter in order to list this sort of message for actual user: For example, for UserXX: UserXX received from moduleA messages "AAA" and "CCC" and from moduleC message "DDD" Please could you explain me theorically how to manage it? I am not abble to visualize how to make relations between the two models, as they have one equal field each one... Thank you very much! I tried: class Owner(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE,related_name='usermod') modulkey = models.CharField(max_length=255) date_in = models.DateTimeField(default=timezone.now, blank=True) def __str__(self): return f'{self.user.first_name} {self.user.last_name} | {self.modulkey}' class ModulMess(models.Model): modulkey = models.ForeignKey(Owner, on_delete=models.CASCADE) date_ini = models.DateTimeField(default=timezone.now, blank=True) message = models.CharField(max_length=255) But cannot reach to achieve a good serializer nor view... -
hi, I am using Django Framework and I want to limit the Questions but I want to give the limit from frontend and also to make Questions random
I am using Django Framework and I want to limit the Questions but I want to give the limit number from frontend I am using flutter as frontend so how can I do it, I did something but it is not working for me so how can I do it can someone help me, please when I want to test the URL in postman the limitation is not working, I want this limit for filtering the questions in frontend and I also I want to make questions to random and I do not know how to do it I thing I have to Make it with random here is my code: views.py class QuizQuetionsList(generics.ListAPIView): serializer_class=QuizQuetionsSerializer def get_queryset(self): quiz_id=self.kwargs['quiz_id'] quiz=models.Quiz.objects.get(pk=quiz_id) if 'limit' in self.request.GET: limit=int(self.request.GET['limit']) return models.QuizQuetions.objects.filter(quiz=quiz).order_by('id')[:limit] else: return models.QuizQuetions.objects.filter(quiz=quiz) urls.py path('chapter- quetions/int:quizChapter_id/int:limit/',views.QuizChapterQuetionsList.as_view()), to get solution to my problem -
Django: how to get value from model in view
I have a view that will conditionally display a breadcrumb trail based on the value of the object's "status" field. This works if I manually set the status value (ex status = "completed"). However, as a newbie, I can't figure out how to retrieve the value? status = Project.status is not working. Here is the view: class CompanyProjectsDetailView(DetailBreadcrumbMixin, UpdateView): model = Project queryset = Project.objects.get_with_counted_notes_documents_todos() template_name = 'company_accounts/project_detail.html' context_object_name = 'project' form_class = ProjectStatusForm status = Project.status if status == "completed": @cached_property def crumbs(self): return [ ("projects", reverse( "company_project:" + CompanyProjects.list_view_name, ) ), (f"completed projects", reverse( "company_project:" + CompanyProjects.list_view_name, ) ), ] -
Trying to set a coordinate to be the origin point adds another random point instead of pushing it to the front
I am trying to make a program for the traveling salesman problem that uses a nearest neighbor method. I am using Django for this project. The problem is, when I try to set one of the coordinate objects to the front of the calculation, it adds another different point to be the origin. Is there anything obviously wrong with my program? #calcRoute.py from django.db import models from .models import Coordinate, SortedPoint import math class Point: def __init__(self, longitude, latitude, isPassed, isOrigin): self.longitude = longitude self.latitude = latitude self.isPassed = isPassed self.isOrigin = isOrigin def haversine(lat1, lon1, lat2, lon2): # haversine formula to caluclate distance between points on a globe # convert degrees to radians lat1, lon1, lat2, lon2 = map(math.radians, [lat1, lon1, lat2, lon2]) # calculate distance dlat = lat2 - lat1 dlon = lon2 - lon1 a = math.sin(dlat/2)**2 + math.cos(lat1) * math.cos(lat2) * math.sin(dlon/2)**2 c = 2 * math.asin(math.sqrt(a)) r = 6378 # radius of earth in kilometers return c * r def nearest_neighbor(points, origin): # return the nearest neighbor nearestNeighbor = None nearestDistance = float('inf') for point in points: # skip the origin point if point == origin: continue distance = haversine(origin.longitude, origin.latitude, point.longitude, point.latitude) if distance … -
How to properly update the foreign key's property of a Django model?
I have a Django Model named EmailSendingTask. This is the whole model- class EmailSendingTask(models.Model): order = models.OneToOneField(Order, on_delete=models.CASCADE, related_name='order') status = EnumChoiceField(SetupStatus, default=SetupStatus.active) time_interval = EnumChoiceField(TimeInterval, default=TimeInterval.five_mins) immediate_email = models.OneToOneField(PeriodicTask, on_delete=models.CASCADE, null=True, blank=True, related_name='immediate_email') scheduled_email = models.OneToOneField(PeriodicTask, on_delete=models.CASCADE, null=True, blank=True, related_name='scheduled_email') created_at = models.DateTimeField(auto_now_add=True) class Meta: verbose_name = 'EmailSendingTask' verbose_name_plural = 'EmailSendingTasks' def __str__(self) -> str: return f'EmailSendingTask: Order = {self.order}' The immediate_email and scheduled_email fields are responsible for holding two PeriodicTask objects. I have created a function called disable_scheduled_email, which is responsible for disabling the scheduled_email's periodic task. The detail of the function is here- def disable_scheduled_email(self): print(f'Disabling scheduled email...') self.scheduled_email.enabled = False self.save(update_fields=['scheduled_email']) Now, whenever I call this function and print the value of the self.scheduled_email.enabled, I find it False. But, when I try to look at the Django Admin site, the periodic task's enabled value remains as True. Why is it happening?