Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
QuerySet' object has no attribute 'save'
I'm getting this error when trying to get the image attribute and set some values according to the content of service_name attribute, both service_name and image_url are attributes of the same model, but I want to set the image according to the content service_name using condition statements. Any help or other way of doing it is highly appreciated Here is the models module: class JobServices(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) service_name = models.CharField(max_length=100, default="nom du service") hour = models.IntegerField(default="Heures") amount = models.FloatField(default="Cout") service_date = models.DateTimeField(auto_now_add=True, null=True) description = models.CharField(max_length=2000, null=True, default="annonce") image_url = models.CharField(max_length=2000, null=True, blank=True) image = models.ImageField() And here is the view module def taches(request): taches = JobServices.objects.all() if request.user.is_authenticated: service_name = request.POST.get('service_name') image_url = request.POST.get('image_url') if service_name == 'don du sang': image_url = 'https://images.pexels.com/photos/4226902/pexels-photo-4226902.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500' taches.save() elif service_name == 'cours de soutien': image_url = 'https://images.pexels.com/photos/1181529/pexels-photo-1181529.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500' taches.save() elif service_name == 'jardinage': image_url = 'https://images.pexels.com/photos/4505166/pexels-photo-4505166.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500' taches.save() elif service_name == 'reparation': image_url = 'https://www.pexels.com/photo/gray-scale-photo-of-gears-159298/' taches.save() else: image_url = 'https://images.pexels.com/photos/8080823/pexels-photo-8080823.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500' taches.save() return render(request, 'taches.html', {'taches': taches}) else: return redirect('login') -
AllowAny CreateAPIView returns 401 for unauthenticated users
I use DRF with djangorestframework-simplejwt package. In my settings.py: INSTALLED_APPS = [ ... 'rest_framework', ... ] ... REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.AllowAny', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTTokenUserAuthentication', ), } SWAGGER_SETTINGS = { 'SECURITY_DEFINITIONS': { 'Bearer': { 'type': 'apiKey', 'name': 'Authorization', 'in': 'header', 'description': 'E.g. \'Bearer jwt.token.here\'' } } } And in my apps' views.py: ... class PublicCreateView(generics.CreateAPIView): """ Should be available for unauthenticated users """ serializer_class = PublicThingSerializer def post(self, request, *args, **kwargs): return Response("It works!", 200) ... Yet for some reason this view returns 401 response for unauthenticated users. I tried a lot of things, the best I got was noticing that when I remove the REST_FRAMEWORK config from my settings.py completely, the response code changes to 403 forbidden. Any ideas? -
I am trying to load a modified pdf through the response of an ajax call. But always getting 404 error in Django python
I am very new to Django and infact its my first project using Django. My HTML page "verify.html" is containing a pdf inside an iframe in the right side and in the left side there are input tags with values. Onclick on any of these input tags loadDoc() javascript call is fired and through ajax call I am calling a python function to highlight some text and save that highlighted pdf in url: "static_ocr/invoices/Grger - Invoice_high.pdf". The pdf file is properly modified and saved in the specified location but with the response when I am trying to load the pdf, I am getting a 404 error: "GET /verify/static_ocr/invoices/Grger - Invoice_high.pdf HTTP/1.1" 404 4298 urls.py path('verify/', views.map_invoice, name='verify'), path('verify/highlight/', views.highlight, name='highlight'), views.py def map_invoice is rendering verify.html page def highlight is for highlighting the pdf and storing the same. verify.html function loadDoc(){ ------------ $.ajax({ type: "POST", url: '{{ 'highlight/' }}', data: {csrfmiddlewaretoken: '{{ csrf_token }}', text: val}, success: function(response){ alert(response); $("#pdfview").attr("src", "static_ocr/invoices/Grger - Invoice_high.pdf"); <iframe id="pdfview" src="{% static pdf_url %}" width="85%" height="750px"></iframe> Pdf is highlighted and stored but not getting displayed with error: "GET /verify/static_ocr/invoices/Grger - Invoice_high.pdf HTTP/1.1" 404 4298 Thanks in advance. -
'No active account found with those credentials' when trying to log in with Django REST + Simple JWT
I'm trying to set up this API with user authentication but I keep getting the error message in the title when trying to log in. Registration seems to work and the super user can log in. I believe it is due to the password hashing, because when I go to the admin panel, every user has the same message: 'Invalid password format or unknown hashing algorithm.' except the super user (which I created in the terminal). Have I made a mistake in the user creation part? Serializers.py from rest_framework import serializers from rest_framework.permissions import IsAuthenticated from django.db import models from django.contrib.auth.models import User from django.contrib.auth import authenticate from django.contrib.auth.hashers import make_password class RegisterSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username', 'password') def create(self, validated_data): user = User.objects.create_user(**validated_data) return user class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = '__all__' def validate(self, data): user = authenticate(**data) if user and user.is_active: return user Views.py from django.shortcuts import render from rest_framework.response import Response from rest_framework import generics, permissions, mixins from django.contrib.auth.models import User from .serializers import RegisterSerializer class RegisterAPI(generics.GenericAPIView): serializer_class = RegisterSerializer def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.save() return Response({ "message": "User created successfully!" }) … -
How to load the defualt value in combo box and how can add product to the cart without reloading the page in django?
Problem I want to the following things but am unable to understand that how can I do the following things. Firstly, I want that when the page is loaded the defualt values should be displayed from using the value from the combox. For example pack of 1KG is the defualt value so it's price and other values should be updated when the page is loaded. Secondly, I want that when the product is added to the cart the page is not reloaded or refreshed and a popup is shown that the product is added to the cart. CODE Script $(document).on("change", '.tranactionID', function (event) { event.preventDefault(); //get closest outer div.. var selector = $(this).closest(".productID") //find to get required elements.. selector.find('.id_price').text($(this).children(":selected").attr("price")); selector.find('.price-sale').text($(this).children(":selected").attr("sale_price")); selector.find('.id_discount').text($(this).children(":selected").attr("discount")); let id = $(this).find("option:selected").attr('transID'); let Url = `{% url 'cart:cart_add' 0 %}`.replace(0, id); selector.find("form").attr('action', Url); }); HTML {% regroup transaction by productID as ProductList %} {% for productID in ProductList %} <div class="col-sm-3 productID" > <div class="product"> <a href="{% url 'main:product-detail' productID.grouper.id %}" class="img-prod"><img class="img-fluid" src={{productID.grouper.product_image.url}} alt="" height="200px"> <span class="status id_discount">%</span> <div class="overlay"></div> </a> <div class="text py-3 pb-4 px-3 text-center"> <h3><a href="#">{{productID.grouper}}</a></h3> <div class="d-flex"> <div class="pricing"> <p class="price"><span class="mr-2 price-dc id_price">Rs. </span><span class="price-sale">Rs. </span></p> </div> </div> <select class="tranactionID" id="ItemID" … -
I cant access the files I upload with django inside the website with nginx when I try to download them
In my python Django project I can't figure out how to download .pdf files with nginx. In the site there will be constant uploads from an admin an the site shows the download links for this button in html and I direct to download with href. I tried to define a dynamic location in nginx locations but it just gives me a "404 not found" or " the requested resource was not found on this server.". I checked that files exists at the correct path but nginx still does not work. Nginx Location File : server { listen 80; server_name 134.209.252.222; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/mjr/hedefcekilis/mysite; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } location /static/admin { root /home/mjr/hedefcekilis/cekilisenv/lib/python3.8/site-packages/django/contrib/admin; } location ~ \.(pdf) { root /home/mjr/hedefcekilis/mysite/media/ibra/~; } } The pdf files are in different folders in the "ibra" folder. And these folder names change over time. How can I solve this problem? -
Training Deep Learning Model using Django
I am trying to train Deep Learning Model using Django. I faced OSError: Cannot understand given URI: False error. Anyone who solved this problem, please help me. -
django error: was blocked due to MIME type (“text/html”) mismatch (X-Content-Type-Options: nosniff)
I'm creating a django project. Everything was fine and I had no problem with loading fontawesome files. But now it can not show the fontawesome icons and in the console there are some errors: Recently, I've made some changes somewhere, and didn't attention when these errors occur and when fontawesome icons start not showing. But I'm sure the changes where not in fontawesome files or where I link to those files. So What has happend? And this is the result when I used curl -I the-path: ╰─$ curl -I http://localhost:8000/blog/static/blog/fontawesome/css/fontawesome.css HTTP/1.1 404 Not Found Date: Wed, 30 Jun 2021 08:35:31 GMT Server: WSGIServer/0.2 CPython/3.9.2 Content-Type: text/html X-Frame-Options: DENY Content-Length: 3376 X-Content-Type-Options: nosniff Referrer-Policy: same-origin And this is where I link to the css files: -
Improving API Performance in DRF with select_related and prefetch_related
the below serializer and view which I am using to get data from multiple models is taking around 4 secs to get data. I have added select_related and prefetch_related and still the num of queries are around 16. I am not sure what else can be down to make sure the api is faster. class WalletTransactionsSerializer(serializers.Serializer): id= serializers.IntegerField(read_only=True) transaction_date= serializers.DateTimeField(read_only=True) student_transaction= StudentsTransactionSerializer(many=True,read_only=True) staff_transaction= StaffPartnerSerializer(many=True,read_only=True) transaction_amount= serializers.DecimalField(max_digits=12, decimal_places=2,read_only=True) closing_balance= serializers.DecimalField(max_digits=12, decimal_places=2,read_only=True) remarks=serializers.CharField(read_only=True) updated_on=serializers.DateTimeField(read_only=True) transaction_status=serializers.CharField(read_only=True) refund_transaction= RefundTransactionsSerializer(many=True,read_only=True) wallet=WalletPartialSerializer(read_only=True) razorpay_info=RazorpaySerializer(many=True,read_only=True) class Meta: model=WalletTransactions fields=['id','transaction_date','transaction_amount','closing_balance','remarks','updated_on','transaction_status','staff_transaction','student_transaction','refund_transaction','wallet','razorpay_info'] @staticmethod def setup_eager_loading(queryset): """ Perform necessary eager loading of data. """ queryset= queryset.select_related('wallet','wallet__user') queryset= queryset.prefetch_related('refund_transaction') queryset= queryset.prefetch_related('staff_transaction__wallet_transaction_id') queryset=queryset.prefetch_related('student_transaction__student_id','student_transaction__application_id','student_transaction__course_id','student_transaction__university_id','student_transaction__promocodeid') queryset= queryset.prefetch_related('razorpay_info','razorpay_info__wallet_transaction_id') return queryset #view def transaction_search(request): user_id = request.GET.get('user_id') user_role= request.GET.get('role') transactions= WalletTransactions.objects.all().distinct() if (user_id and user_role) and str(user_role)=='abc': transactions = WalletTransactions.objects.filter(wallet__user=str(user_id)).distinct() # print("data is",transactions) if (user_id and user_role) and str(user_role)=='def': transactions = WalletTransactions.objects.all().distinct() # print(transactions) return transactions.distinct() class TransactionsViewSet(viewsets.ModelViewSet): serializer_class=WalletTransactionsSerializer pagination_class=StandardResultsSetPagination filter_backends=(filters.DjangoFilterBackend,) filterset_class = TransactionsFilter def get_queryset(self): transactions = transaction_search(self.request) transactions= self.get_serializer_class().setup_eager_loading(transactions) return transactions def dispatch(self, *args, **kwargs): response = super().dispatch(*args, **kwargs) # For debugging purposes only. from django.db import connection print('# of Queries: {}'.format(len(connection.queries))) print('Queries: {}'.format(connection.queries)) # print("Query",connection.queries) return response -
How to properly kill MySQL/ MariaDB connections in Django using custom connectors
I am currently working on a project and I use the MariaDB connector to run the queries. I can't use ORM so I have to use raw queries. In general, the system works fine, as expected, but when I make a bit 'big' queries I get a Too many connections error message. This has happened to me for both MySQL and MariaDB connectors, but I mainly use MariaDB. Example of my code (truncated / simplified): import mariadb def get_cursor(): conn = mariadb.connect( user="user", password="pass", host="localhost", database="db") return conn, conn.cursor(named_tuple=True) def get_duplicated_variants(): results = [] conn_cursor = get_cursor() cursor = conn_cursor[1] conn = conn_cursor[0] try: cursor.execute("SELECT * FROM `db`.s_data;") columns = [column[0] for column in cursor.description] results = [] for row in cursor.fetchall(): results.append(dict(zip(columns, row))) cursor.close() conn.close() return results except mariadb.Error as e: print(f"Error: {e}") What I've tried: show status like '%onn%'; And also: show variables like 'max_connections'; So the max_used_connections = 152 and I have 2503 Connections. I also tried to execute the following query: SELECT CONCAT('KILL ', id, ';') FROM INFORMATION_SCHEMA.PROCESSLIST WHERE `User` = 'user' AND `Host` = 'localhost' AND `db` = 'db'; As seen in this question. But the number of connections is the same after running the … -
how to make a message model in Django where you can choose more than one person as the recipient
So, I'm trying to make a messaging model(between users) in Django admin where the sender can choose more than one recipient for the message. Models.py: class Message(models.Model): body = models.TextField(verbose_name=") sender = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete = models.CASCADE,editable=False) recipient = models.ManyToManyField(settings.AUTH_USER_MODEL) admin.py: class MessageAdmin(admin.ModelAdmin): def get_queryset(self, request): qs = super().get_queryset(request) if request.user.is_superuser: return qs sender_query = qs.filter(sender=request.user) recipient_query = qs.filter(recipient=request.user) return sender_query | recipient_query My current approach is the code above using a ManyToManyField. But this has created two bugs: The sender will see the same message more than once if more than one recipient are chosen, for example if the sender chooses three recipients, he will have three of the same message in his queryset The sender will not be able to open the message he has sent(if more than one recipient are chosen) because this error will get raised:get() returned more than one Message -- it returned 2!. of course the "2" can be any other number The thing I can't figure out Is that these bugs won't produce if the sender is superuser(And I assume that means there is a problem with my get_queryset code) What am I doing wrong in here? P.S: the reason of sender field being … -
Getting logic error while making put request in Django rest framework
my model class QuestionModel(models.Model): question = models.TextField() author = models.ForeignKey(User, on_delete=models.CASCADE) doubt_class_id = models.ForeignKey(DoubtClasses, on_delete=models.CASCADE, null=True, blank=True) conceptual_class_id = models.ForeignKey(LiveClass_details, on_delete=models.CASCADE, null=True, blank=True) mentor = models.ForeignKey(Mentor, on_delete=models.CASCADE, null=True, blank=True) answer = models.TextField(default='') I have created a answer field to only superuser editable by using question admin class QuestionAdmin(admin.ModelAdmin): readonly_fields = ['answer'] def get_readonly_fields(self, request, obj=None): if request.user.is_superuser: return [] else: return self.readonly_fields admin.site.register(QuestionModel, QuestionAdmin) my views.py def put(self, request, type_of_class=None,pk=None): if int(request.data.get('author')) != self.request.user.id: return Response("you cannot edit othe user question", status=status.HTTP_405_METHOD_NOT_ALLOWED) if pk: question_id = models.QuestionModel.objects.filter(id=pk).first() #if answer originally exists if len(question_id.answer) > 0: self.update(request, type_of_class, pk) #this means answer is just updated if len(question_id.answer) > 0 : return Response("Successfully updated answer", status=status.HTTP_200_OK) # this means that answer is deleted so decrease doubt address count else: if type_of_class =='doubtclass': class_id = question_id.doubt_class_id elif type_of_class == 'liveclass': class_id = question_id.conceptual_class_id class_id.doubtsAddressed -= 1 class_id.save() return Response("Successfully deleted answer", status=status.HTTP_200_OK) #if answer is not originally there self.update(request, type_of_class, pk) #this means that a student has updated his answer if question_id.answer == '': return Response("successfully updated a question", status=status.HTTP_200_OK) #this means that a mentor has posted a answer if type_of_class =='doubtclass': print("type_of_class =='doubtclass'") class_id = question_id.doubt_class_id elif type_of_class == 'liveclass': print("type_of_class =='conceptual_class'") … -
can't create data for testing in async function?
goal Test async function with test database Issu I have async functions for Django channels and when I create data in setUp the data are not reflected in the project!!! my tests: note: these tests inside a APITestCase class class WebsocketTests(APITestCase): def setUp(self): user1 = User.objects.create(username='Alex',email='Alex@g.com') user2 = User.objects.create(username='Sam',email='Sam@g.com') user3 = User.objects.create(username='Clover',email='Clover@g.com') async def test_connect(self): communicator = WebsocketCommunicator(application, 'alerts/') connected, subprotocol = await communicator.connect() assert connected await communicator.disconnect() @database_sync_to_async def get_user(querys): ic(User.objects.count()) #<======= this returns 0 while it should return 3 try: token = parse_qs(querys.decode("utf8"))['token'][0] token_data = UntypedToken(token) user_id = token_data["user_id"] except: return 'token is invalid' try: return User.objects.get(id=user_id) except User.DoesNotExist: return 'AnonymousUser' class QueryAuthMiddleware: def __init__(self, app): self.app = app async def __call__(self, scope, receive, send): scope['user'] = await get_user(scope["query_string"]) return await self.app(scope, receive, send) application = ProtocolTypeRouter({ "http": django_asgi_app, "websocket": QueryAuthMiddleware( URLRouter( websocket_urlpatterns ) ), }) #settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), 'OPTIONS': { 'timeout': 20, # in seconds # see also # https://docs.python.org/3.7/library/sqlite3.html#sqlite3.connect }, 'TEST': { 'NAME': os.path.join(BASE_DIR, "db_test.sqlite3"), }, } } I tride replace APITestCase with django TestCase switch to postgres use from asgiref.sync import sync_to_async -
Django - how to handle form using jquery multiple emails
I'm trying to make a form where users can input more than 1 email in the input form. I'm planning to jquery plugin multiple-email, how can I handle this in Django to get the user emails. -
How to create an account/login using google api client in django
I want to implement the same scenario for use in Android Kotlin which is given in this url. For Web Application I have created login with apple for web application by follow this link. Here is my Google Login View in views.py for access token (as one user have explained here ) class GoogleLogin(SocialLoginView): adapter_class = GoogleOAuth2Adapter And It's working for me as I expected. For Android Application Now, Somehow I have managed a code for this google scenario. Here is my Google Client login View.view.py code class GoogleClientView(APIView): def post(self, request): token = {'id_token': request.data.get('id_token')} print(token) try: # Specify the CLIENT_ID of the app that accesses the backend: idinfo = id_token.verify_oauth2_token(token['id_token'], requests.Request(), CLIENT_ID) print(idinfo) if idinfo['iss'] not in ['accounts.google.com', 'https://accounts.google.com']: raise ValueError('Wrong issuer.') return Response(idinfo) except ValueError as err: # Invalid token print(err) content = {'message': 'Invalid token'} return Response(content) When I am requesting POST method with IdToken then this is providing below information and ofcourse we need this. { // These six fields are included in all Google ID Tokens. "iss": "https://accounts.google.com", "sub": "110169484474386276334", "azp": "1008719970978-hb24n2dstb40o45d4feuo2ukqmcc6381.apps.googleusercontent.com", "aud": "1008719970978-hb24n2dstb40o45d4feuo2ukqmcc6381.apps.googleusercontent.com", "iat": "1433978353", "exp": "1433981953", // These seven fields are only included when the user has granted the "profile" and // … -
Javascript code is not working but file is linked correctly
First function working correctly when i delete second one but when i rewrite it it doestn't work! Here is the javascript file. window.onload=function(){document.getElementById('loader').style.display='none';}; function toggle(){var blur = document.getElementsByClassName('blur'); blur.classList.toggle('active'); }; Please help me to solve it out. Here is HTML file. {% load static %} <html> <head> <meta name="website" content="Coding Tutorials" /> <meta name="keywords" content= /> <meta name="robots" content="nofollow" /> <meta http-equiv="author" content="Navneet Kaur" /> <meta http-equiv="pragma" content="no-cache" /> <meta http-equiv="cache-control" content="no-cache"/> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title> Just Code </title> <link rel="stylesheet" href="{% static '/css/home.css' %}" type="text/css"/> <link rel="stylesheet" href="{% static '/css/googlesearch.css' %}"> <link rel="preconnect" href="https://fonts.gstatic.com"/> <link href="https://fonts.googleapis.com/css2?family=Limelight&display=swap" rel="stylesheet"> <link rel="shortcut icon" href="{% static 'images/favicon48.png' %}" sizes="48×48" type="image/png"> <link rel="shortcut icon" href="{% static 'images/favicon96.png' %}" sizes="96×96" type="image/png"> <link rel="shortcut icon" href="{% static 'images/favicon144.png' %}" sizes="144×144" type="image/png"> <link rel="shortcut icon" href="{% static 'images/favicon192.png' %}" sizes="192×192" type="image/png"> <link rel="shortcut icon" href="{% static 'images/favicon288.png' %}" sizes="288×288" type="image/png"> <link rel="shortcut icon" href="{% static 'images/favicon384.png' %}" sizes="384×384" type="image/png"> <link rel="shortcut icon" href="{% static 'images/favicon576.png' %}" sizes="576×576" type="image/png"> <style> @font-face { font-family: 'Blanka-Regular'; src: local('Blanka-Regular'), url('{% static 'fonts/Blanka-Regular.otf' %}'); } </style> </head> <body> <div id="loader"> <img src="{% static 'images/preloader.gif' %}" alt="Loading"/> </div> <div class="blur"> <div id="searchoverall"> <div class="dropdown"> <a href="#"class="divasigninbttn dropbttn"><img id="signinbttn"src="{% static 'images/signinbttn.jpg' %}" alt="signin"></img></a> … -
How to modify the id field in django-rest-framework-simplejwt?
I have a custom token serializer: from rest_framework_simplejwt.serializers import TokenObtainPairSerializer class TokenObtainPairWithoutPasswordSerializer(TokenObtainPairSerializer): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['password'].required = False def validate(self, attrs): attrs.update({'password': ''}) return super(TokenObtainPairWithoutPasswordSerializer, self).validate(attrs) This worked but now I'd like to change the id -field of my User to be userId and after that I can't get tokens anymore because it is searching for a field id. There must be some pretty simple way to modify this? -
multiple Modelform, multiple selection and multiple records
My aim is to put all the questions(IsSoru) of the relevant section and the options(IsSecenek) under the questions from the questions table on a page. To save by entering the person information(UserIs) at the bottom after the selected answers. To do it all with a single submit button. models class IsSoru( models.Model ): soru= models.CharField(max_length=145) metin_tr = models.CharField(max_length=250) sira = models.IntegerField() isaltgrup = models.ForeignKey(IsAltGruplari, on_delete=models.CASCADE) class IsSecenek( models.Model ): secenek_tr = models.CharField(max_length=145) sira = models.IntegerField() issoru = models.ForeignKey(IsSoru, on_delete=models.CASCADE) class UserIs( models.Model): eposta = models.EmailField(max_length=145) telefon = models.CharField(max_length=145) adres = models.CharField(max_length=245) sehir = models.CharField(max_length=45) mesaj = models.TextField() tarih = models.DateTimeField(auto_now_add=True) isdurumu = models.CharField(max_length=45, default='Yeni' ) isaltgrup = models.ForeignKey(IsAltGruplari, on_delete=models.CASCADE) kullanici = models.CharField(max_length=150) class Cevap( models.Model ): soru = models.ForeignKey(IsSoru, on_delete=models.CASCADE) cevap = models.ForeignKey(IsSecenek, on_delete=models.CASCADE) useris = models.ForeignKey(UserIs, on_delete=models.CASCADE) forms class UserIsForm(forms.ModelForm): class Meta: model = UserIs fields = ("kullanici", "eposta", "telefon", "adres", "sehir", "mesaj", "isaltgrup") widgets = { 'kullanici': forms.TextInput(attrs={'id': 'name','placeholder': _('Name/Surname'),"required":""}), 'eposta': forms.EmailInput(attrs={'id': 'email','placeholder': _('E-mail'),"required":""}), 'telefon': forms.TextInput(attrs={'id': 'phone','placeholder': _('Phone'),"required":""}), 'adres': forms.TextInput(attrs={'id': 'address','placeholder': _('Address'),"required":""}), 'sehir': forms.Select(attrs={'id': 'privence','placeholder': _('Privence'),"required":""}), 'mesaj': forms.Textarea(attrs={'id':'message', 'placeholder': _('Your Message'),"required":""}), } labels = {'kullanici':'', "eposta":'', "telefon":'', "adres":'', "sehir":'', "mesaj":'', "isaltgrup":''} class UserCevapForm(forms.ModelForm): class Meta: model = Cevap fields = ("cevap", "soru") view class SecDetay_View(CreateView): model = UserIs … -
from .api.serializers import EmployeeSerializer ModuleNotFoundError: No module named 'Auth.api.api
I am getting the following error when I trying to include my app URLs in base URLs Auth.api.views urlpatterns = [ path('', views.employee_list), ] Base.urls from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('', include('Auth.urls')), path('api/', include('Auth.api.urls')), path('api-auth/', include('rest_framework.urls')), ] -
How to set custom primary keys of different models as foreign key and migrate to mysql properly in django?
I created this model for my django project and connected it with mysql. I created customerid as the primary key in the Customer model and used it as a foreign key in the cart to represent the owner. There should not be an id field since django does not create one when primary key is true. Whenever I try to migrate the model, it errors "Cannot drop 'id': needed in a foreign key constraint 'api_cart_owner_id_c65befd7_fk_api_customer_id' of table 'api_cart'"). I tried fake migration but that created an unwanted id field in the mysql schema. And if I leave it like that and make a post request with a customerid I get this error "Incorrect integer value: '' for column 'owner_id' at row 1". I suppose that owner_id is looking for id field from customer model instead of customerid. I believe I have not set the cart model correctly. How do I represent the customerid and itemid (custom primary keys of different model) as a foreign key for the cart model and migrate it properly? class Item(models.Model): itemid = models.TextField(primary_key=True) name = models.TextField() price = models.FloatField() quantity = models.IntegerField() ordered = models.IntegerField(default=0) def __str__(self): return self.name class Customer(models.Model): customerid = models.TextField(primary_key=True) name … -
how to make a field in Django only superuser editable and for other users it is read only?
my model class QuestionModel(models.Model): question = models.TextField() author = models.ForeignKey(User, on_delete=models.CASCADE) doubt_class_id = models.ForeignKey(DoubtClasses, on_delete=models.CASCADE, null=True, blank=True) conceptual_class_id = models.ForeignKey(LiveClass_details, on_delete=models.CASCADE, null=True, blank=True) mentor = models.ForeignKey(Mentor, on_delete=models.CASCADE, null=True, blank=True) answer = models.TextField(default='') This is a question model where a user is allowed to post new questions but i want that this answer field is only superuser editable and a normal user have only readonly access for that field, needs help i searched for possible answers but didn't get any -
Why is my dockerized Django app so slow and shows ([CRITICAL] WORKER TIMEOUT)?
I'm trying to deploy a Django app in a Docker container. It works well but the first time I open a page I receive these messages: [CRITICAL] WORKER TIMEOUT [INFO] Worker exiting [INFO] Booting worker with pid: 19 The next time I open the same page it's pretty fast. Here's my Dockerfile (generated by wagtail app starter) FROM python:3.8.6-slim-buster RUN useradd wagtail EXPOSE 8000 ENV PYTHONUNBUFFERED=1 \ PORT=8000 RUN apt-get update --yes --quiet && apt-get install --yes --quiet --no-install-recommends \ build-essential \ libpq-dev \ libmariadbclient-dev \ libjpeg62-turbo-dev \ zlib1g-dev \ libwebp-dev \ nano \ vim \ && rm -rf /var/lib/apt/lists/* RUN pip install "gunicorn==20.0.4" COPY requirements.txt / RUN pip install -r /requirements.txt WORKDIR /app RUN chown wagtail:wagtail /app COPY --chown=wagtail:wagtail . . USER wagtail RUN python manage.py collectstatic --noinput --clear CMD set -xe; python manage.py migrate --noinput; gunicorn mysite.wsgi:application How can I fix that? -
How to copy a Django SQlite database to a Docker container?
I'm new to Docker. I am trying to dockerize a Django app. My project contains a Wagtail app and I'm using the auto generated Dockerfile by Wagtail. FROM python:3.8.6-slim-buster RUN useradd wagtail EXPOSE 8000 ENV PYTHONUNBUFFERED=1 \ PORT=8000 RUN apt-get update --yes --quiet && apt-get install --yes --quiet --no-install-recommends \ build-essential \ libpq-dev \ libmariadbclient-dev \ libjpeg62-turbo-dev \ zlib1g-dev \ libwebp-dev \ nano \ vim \ && rm -rf /var/lib/apt/lists/* RUN pip install "gunicorn==20.0.4" COPY requirements.txt / RUN pip install -r /requirements.txt WORKDIR /app RUN chown wagtail:wagtail /app COPY --chown=wagtail:wagtail . . USER wagtail RUN python manage.py collectstatic --noinput --clear CMD set -xe; python manage.py migrate --noinput; gunicorn mysite.wsgi:application It's working well but my sqlite Database is empty and I'd like to run my container with the wagtail pages that I will create locally. How can I change the Dockerfile for that endeavor? -
Can't figure out why I'm getting `Reverse for 'app_list' with keyword arguments '{'app_label': ''}' not found` in a django project
The project has 2 apps - accounts (very basic custom users) and portal. myproject/myproject/urls.py: from django.contrib import admin from django import urls from portal import admin as user_admin from portal import views urlpatterns = [ urls.path(r'admin/', admin.site.urls), urls.path(r'portal/mymodel/', views.testview), urls.path('', user_admin.user_site.urls), ] myproject/portal/templates/portal/mymodel/testview.html: {% extends "admin/change_list.html" %} {% block after_field_sets %}{{ block.super }} <h2> hello world </h2> {% endblock %} myproject/portal/templates/portal/views.py: from django.shortcuts import render def testview(request): return render( request, 'portal/mymodel/testview.html', {'app_label': 'portal'} ) and the stacktrace: Traceback (most recent call last): File "/usr/local/Cellar/python@3.9/3.9.4/Frameworks/Python.framework/Versions/3.9/lib/python3.9/wsgiref/handlers.py", line 137, in run self.result = application(self.environ, self.start_response) File "/Users/Me:D/myproject/venv/lib/python3.9/site-packages/django/contrib/staticfiles/handlers.py", line 76, in __call__ return self.application(environ, start_response) File "/Users/Me:D/myproject/venv/lib/python3.9/site-packages/django/core/handlers/wsgi.py", line 133, in __call__ response = self.get_response(request) File "/Users/Me:D/myproject/venv/lib/python3.9/site-packages/django/core/handlers/base.py", line 130, in get_response response = self._middleware_chain(request) File "/Users/Me:D/myproject/venv/lib/python3.9/site-packages/django/core/handlers/exception.py", line 49, in inner response = response_for_exception(request, exc) File "/Users/Me:D/myproject/venv/lib/python3.9/site-packages/django/core/handlers/exception.py", line 114, in response_for_exception response = handle_uncaught_exception(request, get_resolver(get_urlconf()), sys.exc_info()) File "/Users/Me:D/myproject/venv/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/Users/Me:D/myproject/venv/lib/python3.9/site-packages/django/utils/deprecation.py", line 117, in __call__ response = response or self.get_response(request) File "/Users/Me:D/myproject/venv/lib/python3.9/site-packages/django/core/handlers/exception.py", line 49, in inner response = response_for_exception(request, exc) File "/Users/Me:D/myproject/venv/lib/python3.9/site-packages/django/core/handlers/exception.py", line 114, in response_for_exception response = handle_uncaught_exception(request, get_resolver(get_urlconf()), sys.exc_info()) File "/Users/Me:D/myproject/venv/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/Users/Me:D/myproject/venv/lib/python3.9/site-packages/django/utils/deprecation.py", line 117, in __call__ response = response or … -
Source specified in Javascript not showing up in Django template
Maybe this is a really dumb question, but I'm learning Javascript and Django and can't figure it out. I've spent a few hours on this and maybe it's a syntax error or something else. I want to specify the source of an image in javascript and then display the image in Django HTML template. It's not working, even with simple images Here is my javascript: $(document).ready(function() { var image = document.getElementById("image").src('https://res.cloudinary.com/.../{{ object.id}}'); } Here is my image info: <img src="#" id="image" class="mx-auto" width="250px" onerror='this.onerror = null; this.src="https://res.cloudinary.com/.../image.jpg"'/> What am I doing wrong? It's definitely not working - the image is not showing up even when it exists. I either get the default image or no image.