Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Groupby using Django's ORM to get a dictionary of lists from the queryset of model with foreignkey
I have two models, Business and Employee: from django.db import models class Business(models.Model): name = models.CharField(max_length=150) # ... class Employee(models.Model): business = models.ForeignKey( Business, related_name="employees", on_delete=models.CASCADE, ) name = models.CharField(max_length=150) # ... Here's a sample data: Business.objects.create(name="first company") Business.objects.create(name="second company") Employee.objects.create(business_id=1, name="Karol") Employee.objects.create(business_id=1, name="Kathrine") Employee.objects.create(business_id=1, name="Justin") Employee.objects.create(business_id=2, name="Valeria") Employee.objects.create(business_id=2, name="Krista") And I want to get a dictionary of lists, keys being the businesses and values being the list of employees. I can do so using prefetch_related on the Business model. A query like this: businesses = Business.objects.prefetch_related("employees") for b in businesses: print(b.name, '->', list(b.employees.values_list("name", flat=True))) Which gives me this: first company -> ['Karol', 'Kathrine', 'Justin'] second company -> ['Valeria', 'Krista'] And this is exactly what I want and I can construct my dictionary of lists. But the problem is that I only have access to the Employee model. Basically I only have a QuerySet of all Employees and I want to achieve the same result. I figured I could use select_related, because I do need the business objects, but this query: Employee.objects.select_related("business") Gives me this QuerySet: <QuerySet [<Employee: Employee object (1)>, <Employee: Employee object (2)>, <Employee: Employee object (3)>, <Employee: Employee object (4)>, <Employee: Employee object (5)>]> And I don't … -
Django wanted to use existing student.db
Can anyone share me a tutorial on how to connect this .db file to django project Thanks in advance I tried to connect via dbshell im new to this can any1 help -
'cannot write mode RGBA as JPEG' when saving image
I'm getting: OSError at /admin/blog/post/add/ cannot write mode RGBA as JPEG error when uploading an image file other than 'jpeg' with Pillow. This is the function I'm using to resize the image: def resize_image(image, size): """Resizes image""" im = Image.open(image) im.convert('RGB') im.thumbnail(size) thumb_io = BytesIO() im.save(thumb_io, 'JPEG', quality=85) thumbnail = File(thumb_io, name=image.name) return thumbnail Most solutions to this same error seem to be solved by converting to 'RGB', but I'm already doing that in my function except it still keeps giving error when uploading, for example, a .png image. How can I fix it? -
djangoCMS : Resources and Flow
Could anyone please suggest me any flow for learning djangoCMS and any video tutorials/articles. I have good knowledge of both python and django. I was suggested to learn the djangocms framework for my internship. When I looked into the documentation i thought it will be easy to understand. But I am not getting anything from it. I am in full confusion to understand (sometimes even when i typed the same code in documentation i am not getting the same result shown in documentation) Thanks in advance. -
(Python) have existing "mySQL Database" and "website", want to connect/synchronize both part
Main problem: I have existing mySQL Database and website, how do I connect/synchronize both, that input or update from mySQL, can also result in website too I did learn HTML, CSS but was required to find the way, instead input from <p> </p>, need to find a way CRUD from mySQL, and result to website after a day of research, python django seems has the possiblity solve my problem, but all the tutorial is buttom up create an new website and new mySQL, I'm stock on connecting existing one (that the "mySQL Database" and "website"), that how far I reach , therefore want to ask the export in here, thanks environment: I'm using python, window and mySQL the already set website screenshot the existing mySQL Database screenshot (MySQL Database, and using HeidiSQL ) -
Is it possible to connect AWS Dynamodb with django, I'm trying to connect more than a week. Will anybody find solution with this
I can able to create table in dynamodb using django, but I keep on gettin g configural error while I migrate the errror is- (django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details.) will anyone has idea about settings.py configuration in django. some one says we django cannot access nosql but I configured Mongodb and cassendra I'm trying to migrate and runserver , while migration i'm getting (django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details.) when i run the server i get Object 'EXCLUDE' is not a valid value for the 'unknown' parameter -
how to add form as data in class-base views?
I used to send form as content in function-base-view and I could use for loop to simply write down fields and values like: {% for x in field %} <p>{{ x.label_tag }} : {{ x.value }} </p> I don't remember whole the way so maybe I wrote it wrong but is there anyway to do this with class-based-views, because when I have many fields its really hard to write them 1by1 -
How to send back a numerical value to Django serialiser to display as JSONResponse?
I have a function that calculates a value from Django models/data. def protein_coverage(request, protein_id): try: proteins = Protein.objects.filter(protein_id=protein_id) domain_length = 0 for protein in proteins.all(): protein_length = protein.protein_length for protein_domains in protein.protein_domains.all(): length = protein_domains.stop - protein_domains.start domain_length += length coverage = domain_length / protein_length except Protein.DoesNotExist: return HttpResponse({'message': 'This Protein does not exist'}, status=status.HTTP_404_NOT_FOUND) if request.method == 'GET': serializer = ProteinCoverageSerializer(coverage) return JsonResponse(serializer.data,safe=False) serializer: class ProteinCoverageSerializer(serializers.ModelSerializer): class Meta: model = Protein fields = ('coverage',) lookup_field = 'protein_coverage' 'coverage' is correctly calculated, I can print it. I just don't know how to display it as JSON response, I get errors like: ImproperlyConfigured at /api/coverage/xxx Field name `coverage` is not valid for model `Protein`. How can I display this calculated numerical value as a JSONresponse? -
how to make alert pop up in html while error in django function
I have a function, where if the function has an error in it, a "wrong key" message will pop up in the html. I tried to use messages, but it has a condition that it must use request. because i call this messages inside the function, so there is no request. how can I display the "wrong key" pop up, if the iv cannot be used/wrong? I use try and except, so if it can't be processed, then except runs. here's my function code: def decrypt(cipher_text, key): if len(key) <= key_bytes: for x in range(len(key),key_bytes): key = key + "0" assert len(key) == key_bytes private_key = hashlib.sha256(key.encode("utf-8")).digest() cipher_text = base64.b64decode(cipher_text) try: iv = cipher_text[:16] cipher = AES.new(private_key, AES.MODE_CBC, iv) return unpad(cipher.decrypt(cipher_text[16:]).decode('utf-8')) except: print("WRONG PASSWORD") messages.error(request, 'wrong key!') return redirect('decode') here's my html: {% for message in messages %} <div class="alert alert-warning" role="alert" id="some_flag"> <a class="close" href="#" data-dismiss="alert">×</a> {{message}} </div> {% endfor %} -
Second Model form is over riding the first model form of same model Django
Hello i am having an issue in django forms. i am passing 2 forms in a same view. these both forms are model forms with the same fields and same model as well. the code is: class IncomingOrderForm(forms.ModelForm): class Meta: model = connector_models.Order fields = ['message_type', 'position', 'field'] widgets = { "message_type": forms.TextInput( attrs={"data_icon": "fa fa-envelope", "required": "", "col_cls": "col-md-4"}), "position": forms.TextInput( attrs={"data_icon": "fa fa-hashtag", "required": "", "type": "number", "col_cls": "col-md-4", "value": "0"}), "field": forms.TextInput(attrs={"data_icon": "fa fa-keyboard", "required": "", "col_cls": "col-md-4"}) } class OutgoingOrderForm(forms.ModelForm): class Meta: model = connector_models.Order fields = ['message_type', 'position', 'field'] widgets = { "message_type": forms.TextInput( attrs={"data_icon": "fa fa-comment", "required": "", "col_cls": "col-md-4"}), "position": forms.TextInput( attrs={"data_icon": "fa fa-hashtag", "required": "", "type": "number", "col_cls": "col-md-4", "value": "0"}), "field": forms.TextInput(attrs={"data_icon": "fa fa-keyboard", "required": "", "col_cls": "col-md-4"}) } i am showing these both forms in a same view for getting 2 different entries. for example i am typing values for incoming form: message_type : 'A',position :1, field:1 and for outgoing form:message_type : 'B',position :2, field:2 and when i save these forms it saves outgoing form entries 2 times instead of saving both forms once please give me any solution, thanks in advance -
ordering is not working with django model seralizer
I am using 2.2.16 django versiong and 3.11.2 django_rest_framework version and using serializers.ModelSerializer CRUD operation is working but ordering is not working. models.py code is below, class Ticket(models.Model): title = models.CharField(max_length=255) description = models.CharField(blank=True, max_length=255) notes = models.TextField() eg: code in seralizers.py from rest_framework import serializers class Ticket(serializers.ModelSerializer): title = serializers.CharField() description = serializers.CharField(required=False) notes = serializers.CharField(required=False) class Meta(object): fields = '__all__' depth = 1 model = Ticket ordering_fields = ["title"] def __init__(self, *args, **kwargs): super(Ticket, self).__init__(*args, **kwargs) When i do GET operation as below, ordering is not working with query parameters eg: http://localhost:4200/api/ticket?ordering=title Above api call is returning add data with default ordering as ID (auto created field), but not returning in the assenting of title field (which is a char field). How can I fix this? Also how can i add filtering to the same eg: http://localhost:4200/api/ticket?title=abc # this should give me result of only matching title field with abc or starts with abc -
I want a logged in user to see only its saved information
I just started learning django. i created a model and i expect when a user logs in, the user should see only info it saved but when another user logs in, it sees saved information from other users view.py def user_locker(request): saved_info = Locker.objects.all() all_saved_info = {'saved_info': saved_info} return render(request, 'pwdbank/user_locker.html', all_saved_info) model.py class Locker(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) site_name = models.CharField(max_length=55) site_url = models.URLField(max_length=55) username = models.CharField(max_length=55) email = models.EmailField(max_length=100) password = models.CharField(max_length=55) created_date = models.DateField(auto_now_add=True) updated_date = models.DateField(auto_now=True) def __str__(self): return f'{self.site_name}' Thank you. Please Help! -
django.core.exceptions.ImproperlyConfigured
`I have watched a tutorial. But that was an old version of Django 1.1 and now I am using Django 4.1.So there is a problem that is telling me about django.core.exceptions.ImproperlyConfigured: "post/(?\d+)$" is not a valid regular expression: unknown extension ?<p at position 6. I didn't get it what it was views.py from django.shortcuts import render,get_object_or_404,redirect from django.utils import timezone from blog.models import Post,Comment from blog.forms import PostForm,CommentForm from django.urls import reverse_lazy from django.contrib.auth.decorators import login_required from django.contrib.auth.mixins import LoginRequiredMixin from django.views.generic import (TemplateView,ListView,DetailView,DeleteView,CreateView,UpdateView) # Create your views here. class AboutView(TemplateView): template_name = 'about.html' class PostListView(ListView): model = Post def get_queryset(self): return Post.objects.filter(published_date__lte=timezone.now()).order_by('-published_date') class PostDetailView(DetailView): model = Post class CreatePostView(LoginRequiredMixin,CreateView): login_url = '/login/' redirect_field_name = 'blog/post_detail.html' form_class = PostForm model = Post class PostUpdateView(LoginRequiredMixin,UpdateView): login_url = '/login/' redirect_field_name = 'blog/post_detail.html' form_class = PostForm model = Post class DraftListView(LoginRequiredMixin,ListView): login_url = '/login/' redirect_field_name = 'blog/post_list.html' model = Post def get_queryset(self): return Post.objects.filter(published_date__isnull=True).order_by('created_date') class PostDeleteView(LoginRequiredMixin,DeleteView): model = Post success_url = reverse_lazy('post_list') ####################################### ## Functions that require a pk match ## ####################################### @login_required def post_publish(request, pk): post = get_object_or_404(Post, pk=pk) post.publish() return redirect('post_detail', pk=pk) @login_required def add_comment_to_post(request, pk): post = get_object_or_404(Post, pk=pk) if request.method == "POST": form = CommentForm(request.POST) if form.is_valid(): comment = … -
What's the difference between Cleaned data and is valid in django
What is the difference between cleaned_data and is_valid functions in django?, I just came across forms and immediately i got stuck there can anyone play with some simple examples. I've read many documentation but i cant able to differentiate it. -
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, …