Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Gunicorn can't start wsgi for my django application
everyone! I want to deploy my Django app on ubuntu 20 The scheme, as I understand it, is like this: Nginx -> Gunicorn -> WSGI -> Django pip list Package Version \------------------ ------- asgiref 3.6.0 backports.zoneinfo 0.2.1 bcrypt 4.0.1 cffi 1.15.1 cryptography 39.0.1 Django 4.1.7 future 0.18.3 gunicorn 20.1.0 paramiko 3.0.0 pip 20.0.2 pkg-resources 0.0.0 psycopg2-binary 2.9.5 pycparser 2.21 PyNaCl 1.5.0 setuptools 44.0.0 six 1.16.0 sqlparse 0.4.3 textfsm 1.1.3 wheel 0.38.4 I have installed the necessary packages for Nginx, Gunicorn and my project is located at: /opt/Iron Here is the Gunicorn setup file: sudo nano /etc/systemd/system/gunicorn.service \[Unit\] Description=gunicorn daemon After=network.target \[Service\] User=n.fomichev Group=www-data WorkingDirectory=/opt/Iron ExecStart=/opt/Iron/venv/bin/gunicorn --workers 3 --bind unix:/opt/Iron/Iron.sock Iron.wsgi:application \[Install\] WantedBy=multi-user.target Next I run Gunicorn under a virtual environment: systemctl daemon-reload systemctl start gunicorn systemctl enable gunicorn And I look at the status of the service: (venv) root@iron:/opt/Iron# sudo systemctl status gunicorn * gunicorn.service - gunicorn daemon Loaded: loaded (/etc/systemd/system/gunicorn.service; enabled; vendor preset: enabled) Active: failed (Result: exit-code) since Mon 2023-02-20 11:21:48 UTC; 26s ago Main PID: 20257 (code=exited, status=3) Feb 20 11:21:48 iron gunicorn[20260]: File "<frozen importlib._bootstrap>", line 1014, in _gcd_import Feb 20 11:21:48 iron gunicorn[20260]: File "<frozen importlib._bootstrap>", line 991, in _find_and_load Feb 20 11:21:48 iron gunicorn[20260]: … -
Django rest framework TypeError: 'NoneType' object is not callable
/models.py class Like(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='likes', on_delete=models.CASCADE) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') class Content(models.Model): """Контент (фильмы, сериалы, и т.д.)""" title_ru = models.CharField('Название', max_length=200, blank=True) title_en = models.CharField('Название на английском', max_length=200, blank=True) rating = models.FloatField('Оценка', validators=[ MaxValueValidator(10.0), MinValueValidator(0.0), ], default=0.0) year = models.PositiveSmallIntegerField('Дата выхода', default=date.today().year, null=True) kinopoisk_id = models.IntegerField('Кинопоиск id') is_banned = models.BooleanField('Бан', default=False) def __str__(self): return f'{self.title_ru} / {self.title_en}' class Meta: ordering = ['-year'] verbose_name = 'Контент' verbose_name_plural = 'Контент' /services.py from django.contrib.auth import get_user_model from django.contrib.contenttypes.models import ContentType User = get_user_model() def add_like(obj, user): """Лайк пользователя""" obj_type = ContentType.objects.get_for_model(obj) like, is_created = Like.objects.get_or_create( content_type=obj_type, object_id=obj.id, user=user) return like def remove_like(obj, user): """Лайкает `obj`.""" obj_type = ContentType.objects.get_for_model(obj) Like.objects.filter( content_type=obj_type, object_id=obj.id, user=user ).delete() def is_fan(obj, user) -> bool: """Удаляет лайк с `obj`.""" if not user.is_authenticated: return False obj_type = ContentType.objects.get_for_model(obj) likes = Like.objects.filter( content_type=obj_type, object_id=obj.id, user=user) return likes.exists() def get_fans(obj): """Получает всех пользователей, которые лайкнули `obj`.""" obj_type = ContentType.objects.get_for_model(obj) return User.objects.filter( likes__content_type=obj_type, likes__object_id=obj.id) /serializers.py from django.contrib.auth import get_user_model from rest_framework import serializers from .services import is_fan User = get_user_model() class FanSerializer(serializers.ModelSerializer): class Meta: model = User fields = ( 'username', ) class ContentListSerializer(serializers.ModelSerializer): """Список контента""" class Meta: model = Content fields = ('title_ru', 'title_en', … -
Return Custom Response on Django Rest Framework Generics Retrieve API View
Excuse me devs, i want to ask about how to return custom response on Class Based Views for django rest framework generics retrieveapiview. I have tried to make class based views and function for return custom response but error "Object of Type is not JSON serializable" I just want to return custom response like {"msg": "success", "data": queryset data} # My Views class GetClientDetails(generics.RetrieveAPIView): queryset = TablePVUser.objects.all() serializer_class = GetClientDetails lookup_field = 'pv_owner' def get(self, request, pv_owner): queryset = self.get_queryset().filter(pv_owner=pv_owner, user__is_active=True) return Response({'Message': 'Users active loaded successfully', 'data': queryset}, status=status.HTTP_201_CREATED) -
how to save edits of object and view it as pdf file with django
hello everyone I'm new in django, I finished my app but I want to add some features, in my medical city I need to save all edits that done, like if the filling done on tooth 11 on 20/10/2022, but in 20/12/2022 we extract the same tooth, I want to save the filling and extraction in the details with date of patient like this "20-10-2022" "20-12-2022" click it and go to the form and see what we have done at that date, in my app now I just edit the fields like the tooth number and I can't see the old tooth numer, the second feature is print the fields in pdf form that we used in the medical city that contains patient details and graph of teeth and small box to describe the tooth, like Decay, Filling and Missing, like this "11 M (for missing)" like this picture, is it posiable? -
Populating an HTML table from Django views.py
I have an HTML table that I want to be populated from views.py. Here is my code: index.html {% for pizza in pizza %} <tr id="{{pizza.name}}"> {% for item in pizza.pizza.all %} <td>{{item.status}}</td> <td>{{item.name}}</td> {% endfor %} </tr> {% endfor %} views.py def barangay_canvass_report(request): pizza_data = [{'name': 'Pepperoni Pizza', 'status': 'Ready'}] return render(request, "index.html", {'pizza': pizza_data}) The table doesn't get populated and I don't see any error code. Is it the format in pizza_data? The reason why pizza_data is hardcoded is because that is a JSON file that I need to figure out how to insert but for now I want to see if the {% for %} loop can populate but it is not. -
Implement email verification during sign-up process
I need to validate user's email before allowing them to proceed with account creation. What will be the best way of doing so in Django ? I was thinking of sending cookies with UUID which will be used during registration. email_validation_DB: UUID | Email | Confirmation Code | is_verified Then, when user will click on register. UUID will be used to get the verified email address from email_validation_DB and proceed with account creation. -
get (1045, "Access denied for user 'tony'@'localhost' when use environment variables
i'm in ubuntu 22.04 i connect my project to mysql whit environment variables: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': env('NAME'), 'USER': env("USER"), 'PASSWORD': env("PASSWORD"), 'HOST': env("HOST"), 'PORT': '', } } and my .env file: NAME=mysql USER=root PASSWORD=411481:011 HOST=localhost return this error: (1045, "Access denied for user 'tony'@'localhost' but when didn't use environment variables that work DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'mysql', 'USER': 'root', 'PASSWORD': '411481:011', 'HOST': 'localhost', 'PORT': '', } } -
Upon Table row click, go to a new html page! How does that work for element-ui?
Currently working on a website using Django and I encountered a problem. Upon row-clicking on the table row, I want it to open a new page called "doctor_qr.html" for that particular row. Does anyone know how does that work? Also, upon doing row-click, the records for the corresponding row should be POSTED to the function "medicineRequestSelect" in view_doctor.py. However, it is unable to extract that row of values and only returns me None values shown in Image 1. I would greatly appreciate any help or advice. Thank you! <doctor_emr.html> {% verbatim %} <div id="app2" class="container"> <div class="emr-table"> <el-table ref="multipleTable" :data="list" stripe style="width: 50%" @row-click="handle" @selection-change="handleSelectionChange"> <el-table-column prop="id" label="Index"> </el-table-column> <el-table-column prop="order_id" label="Order ID"> </el-table-column> <el-table-column prop="ward_number" label="Ward No."> </el-table-column> <el-table-column prop="prop" label="Scan QR" width="width"> </el-table-column> </el-table> </div> </div> {% endverbatim %} <script> new Vue({ el: '#app2', data() { return { list: [] } }, mounted() { this.getemrList() }, methods: { getemrList() { // Obtain EMR list axios.post(ToDJ('emrList'), new URLSearchParams()).then(res => { if (res.data.code === 0) { console.log(res.data.data) this.list = res.data.data } else { this.NotifyFail(res.data.data) } }) }, // Purpose: For the row click handle(row, event, column) { console.log(row, event, column) axios.post(ToDJ('medicineRequestSelect'), new URLSearchParams()).then(res => { if (res.data.code === 0) { … -
Multiple django apps vs multiple projects
So I have an architectural question for setting up a new application. Currently, I have a Django application (App 1) that receives data from a mobile phone (through api endpoints) and stores it in db. Then a separate celery application (App 2) runs some computation over this data and sends the results to a third Django application (App 3). This third app basically supports a reactjs site that I have for viewing the computed data. I want a new application that will serve as a 'public' API. So, instead of having App 1 as internal endpoints that only my mobile application has access to, I want to make it available to other developers to integrate themselves. So they can now interact with these endpoints to send me data from a phone, and then run some computation over it and view the raw and computed data afterwards (not on a frontend, just a csv endpoint from App 1 will be fine, no need for another app to store this data, like I have in my original setup). The question that I have is: is it better to setup a brand new Django project for this? Or, can I just create a … -
No data posts by my Kotlin appliaction to Django Rest Framework
I made a Authorizing system with SMS which gets number of an application then makes account and with verify code it let user to login. the problem is that when I send data by Retrofit in Kotlin as POST ,it sends no data (None) to server and Django logs show that no data sent for it. I know my Django API is working truly because of that POSTMAN works with it but my Kotlin application doesn't. Here I used APIService "Kotlin Intrface" class like this you see as below: @FormUrlEncoded @POST("v1/register/") suspend fun RegisterRequest( @Field("mobile") mobile: String ):Response<Reply> I expected to see in logs that data sends for server but it doesnt work. Also maybe you say that it needs Header but no ,cuz of I tried to set header for it also its Register and doesn't need token or anything like this and there's no persmission for it in server side. -
Django 'exclude' query did not return expected results
I am relatively new to Django and this is my first post in the forum. Below are the models(simplified) that are used in the app. The app is about reserving a set of resources for a given period. from django.db import models class Resource(models.Model): id = models.AutoField(primary_key=True) serialno = models.CharField(max_length=30, null=False, unique=True) name = models.CharField(max_length=40, null=False) def __str__(self): return f"{self.name}/{self.serialno}" class Reservations(models.Model): id = models.AutoField(primary_key=True) active = models.BooleanField(default=True) name = models.CharField(max_length=30, null=False) startdate = models.DateField(null=False) enddate = models.DateField(null=False) resource = models.ManyToManyField("myapp.Resource", db_table="myapp_resource_reservations", related_name="reservations") def __str__(self): return f"{self.name}/{self.startdate}/{self.enddate}" For example, below are the data present in the models Resource(format: name/serialno) >>> Resource.objects.all() <QuerySet [<Resource: Resource1/RES1>, <Resource: Resource2/RES2>, <Resource: Resource3/RES3>, <Resource: Resource4/RES4>]> >>> Reservations(format: name/startdate/enddate/active) All reservations are made for Resource1 >>> Reservations.objects.all() <QuerySet [<Reservations: Booking1/2023-03-01/2023-03-07/True>, <Reservations: Booking2/2023-03-15/2023-03-22/True>, <Reservations: BookingX/2023-03-08/2023-03-14/False>]> >>> I am trying to retrieve all resources that do not have an 'active' reservation for a given date period using below query. >>> Resource.objects.exclude((Q(reservations__startdate__range=('2023-03-08','2023-03-14')) | Q(reservations__enddate__range=('2023-03-08','2023-03-14'))) & Q(reservations__active=True)) <QuerySet [<Resource: Resource2/RES2>, <Resource: Resource3/RES3>, <Resource: Resource4/RES4>]> >>> Resource1 does have a reservation: BookingX for period 2023-03-08 to 14 but it is active=False. I expected 'Resource1' to show up in above exclude query but it didn't(intended logic: 'exclude all resources that fall in … -
Update only 2 field in DRF
i have a model and with DRF i want pdate only 2 field in model but when i update , 2 field are update but the other fields are empty . #View `@api_view(['GET', 'PUT', 'DELETE']) def snippet_detail(request, format=None): try: requestd = request.POST['card_number'] requestd2 = card.models.Card(card_number=requestd) #snippet = Card.objects.get() print(requestd2) credit = Card.objects.filter(card_number=requestd).values('initial_credit') credit2 = int(credit[0]['initial_credit']) requestcredit = int(request.POST['initial_credit']) #print(snippet) print(credit) print(credit2) except Card.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) if request.method == 'PUT': serializer = CardModelSerializer(requestd2, data=request.data, partial=True) #insted of requestd 2 was snippet if serializer.is_valid(): #print(request.data) new_credit= credit2 - requestcredit comment = 'Not ٍ Enough' comment2 = 'Not Valid' if new_credit >= 0: if requestcredit >0: serializer.save() return Response(serializer.data,status=status.HTTP_200_OK) else: return Response (comment2, status=status.HTTP_400_BAD_REQUEST) else: return Response(comment, status=status.HTTP_451_UNAVAILABLE_FOR_LEGAL_REASONS) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) #serializers class CardModelSerializer(serializers.ModelSerializer): class Meta: model = Card fields = ['card_number', 'initial_credit'] #'all' #Model class Card(models.Model): card_number = models.CharField(max_length=100, unique=True ,primary_key=True, verbose_name='شماره کارت') first_name_and_last_name = models.CharField(max_length=100) company_name = models.CharField(max_length=100) national_number = models.CharField(max_length=100, unique=True) initial_credit = models.IntegerField(default=0) password = models.CharField(max_length=100) phone_number = models.CharField(max_length=100) personnel_code = models.CharField(max_length=100) #unique=False card_status = models.CharField(max_length=10, choices=(('فعال', 'فعال',), ('غیر فعال', 'غیر فعال',))) created_at = j_models.jDateTimeField( null=True ,blank=True ,default=datetime.now ) #auto_now_add=True, updated_at = j_models.jDateTimeField(auto_now=True) class Meta: verbose_name = 'Card' verbose_name_plural = 'Cards' def __str__(self): return self.card_number` -
Poetry install error while running it on github workflow
Encountering an error message while installing dependencies using Poetry with GitHub Actions. It works fine when I install it locally. However, it gives out the runtime error of ['Key "files" does not exist.'] missing when Action runs on GitHub for the line [Install dependencies]. Error Message 'Key "files" does not exist.' Error: Process completed with exit code 1. Github Workflow name: Linting on: pull_request: branches: [ master ] types: [opened, synchronize] jobs: linting: runs-on: ${{ matrix.os }} strategy: matrix: python-version: [3.9] os: [ubuntu-latest] steps: - name: Checkout uses: actions/checkout@v2 - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v2 with: python-version: ${{ matrix.python-version }} - name: Set up Poetry uses: abatilo/actions-poetry@v2.0.0 - name: Install dependencies run: poetry install - name: Run code quality check run: poetry run pre-commit run -a Toml File [tool.poetry] name = "ailyssa_backend" version = "4.0.9" description = "The RESTful API for Ailytics using the Django Rest Framework" authors = ["Shan Tharanga <63629580+ShanWeera@users.noreply.github.com>"] [tool.poetry.dependencies] python = "^3.9" Django = "4.1.3" djangorestframework = "^3.13.1" django-environ = "^0.8.1" djangorestframework-simplejwt = "^5.0.0" drf-spectacular = {version = "0.25.1", extras = ["sidecar"]} django-cors-headers = "^3.10.0" uvicorn = "^0.16.0" django-filter = "^21.1" psycopg2 = "^2.9.3" django-auditlog = "2.2.1" boto3 = "^1.22.4" django-allow-cidr = … -
Change form input from text value to model instance in django
I want to create Aviz entry using AJAX form. In the form the input material has a jquery ui function autocomplete, that gets all the material names from the Material Model. When I submit the form I get this error in the console : ValueError: Cannot assign "'ADEZIV LIPIRE VATA MINERALA, CT 180, 25 KG CERESIT'": "Aviz.material" must be a "Material" instance. I know that I need to get the input from the form, and turn it in a Material instance...but do not know how/did not find any info about this. models.py: class Material(models.Model): name = models.CharField(max_length=255,default=None,verbose_name='Nume material') class Aviz(models.Model): material = models.ForeignKey(Material, on_delete=models.CASCADE,related_name="aviz") quantity = models.FloatField(default=0,verbose_name="Cantitate") views.py: class AvizCreate(LoginRequiredMixin, AjaxCreateView): model = Aviz form_class = AvizForm def get_form_kwargs(self): kwargs = super().get_form_kwargs() kwargs['pk'] = self.kwargs.get('centrudecost') return kwargs @login_required def autocomplete(request): if 'term' in request.GET: qs = Material.objects.filter(name__icontains=request.GET.get('term')) name = list() id = list() cod_nexus = list() name = [prod.name for prod in qs] id = [prod.pk for prod in qs] cod_nexus = [prod.cod_nexus for prod in qs] return JsonResponse({"name": name, "id":id, "cod_nexus":cod_nexus}, safe=False) templates.html $('#id_material').autocomplete({ source: function(request, response) { $.ajax({ url: "{% url 'materiale:autocomplete' %}", dataType: "json", data: { term: request.term }, success: function(data) { response($.map(data.name, function(value, key) { return … -
i working on django application to charge a user before posting his products. i want to offer a free option, how to archive this and save add with sti
i am working on django application where admin can set pricing,and give coupon, my proble is how to offer a free option or free listing whe you are using stripe. this is a function on my views.py your text@login_required(login_url='/users/login') def create_ad_func(request): user = request.user if request.method == "POST": data = dict(request.POST) data = clean(data) ad = AdList.objects.create_ad(**data) img_counter = 0 img_files = request.FILES if len(request.FILES) > 0: for ad_img in request.FILES: print(img_files[ad_img]) upload_img(ad_img, img_files, ad) else: url = upload_image(request.FILES[ad_img], ad.id, img_counter) img_counter = img_counter + 1 data[ad_img] = url date_time = arrow.utcnow().format('YYYY-MM-DD HH:mm:ss') data['post_date'] = date_time pprint(data) AdList.objects.filter(pk=ad.id).update(**data) objectss = AdList.objects.filter(pk=ad.id) subscription_list = ['urgent_ad', 'regular_ad', 'featured_ad'] for key in data.keys(): if key in subscription_list: ad_subscription = AdSubscription.objects.values()[0] price = ad_subscription[key] charge = ad_subscription[key] * 100 print(price, charge) key = settings.STRIPE_PUBLISHABLE_KEY return render(request, 'checkout.html', {"user": request.user, 'ad': ad, 'price':price, 'key':key, 'charge':charge}) else: ad_subscription = AdSubscription.objects.values()[0] return render(request, 'ad-list-cat.html', {"user": request.user, "subscription": ad_subscription}) and this is my manage.py `class AdListManager(BaseUserManager): """ Custom user model manager where email is the unique identifiers for authentication instead of usernames. """ def create_ad(self, **data): """ Create and save a User with the given email and password. """ email = data["email"] email = self.normalize_email(email) ad = self.model(**data) … -
Django+Heroku+MySQL - R10 - Error R10 (Boot timeout) -> Web process failed to bin d to $PORT within 60 seconds of launch
I am running: git push heroku master heroku open My Procfile: release: python manage.py migrate web: waitress-serve --listen=localhost:8000 storefront.wsgi:application My Log: 2023-02-20T05:47:22.531135+00:00 heroku[web.1]: State changed from crashed to starting 2023-02-20T05:47:41.700316+00:00 heroku[web.1]: Starting process with command `waitress-serve --liste n=localhost:8000 storefront.wsgi:application` 2023-02-20T05:47:44.005026+00:00 app[web.1]: Serving on http://127.0.0.1:8000 2023-02-20T05:48:05.000000+00:00 app[heroku-redis]: source=REDIS addon=redis-acute-18444 sample#activ e-connections=1 sample#load-avg-1m=0.195 sample#load-avg-5m=0.355 sample#load-avg-15m=0.4 sample#read -iops=0 sample#write-iops=0 sample#memory-total=16084924kB sample#memory-free=9997524kB sample#memory -cached=3236532kB sample#memory-redis=335784bytes sample#hit-rate=1 sample#evicted-keys=0 2023-02-20T05:48:42.244149+00:00 heroku[web.1]: Error R10 (Boot timeout) -> Web process failed to bin d to $PORT within 60 seconds of launch 2023-02-20T05:48:42.327725+00:00 heroku[web.1]: Stopping process with SIGKILL 2023-02-20T05:48:42.567303+00:00 heroku[web.1]: Process exited with status 137 2023-02-20T05:48:42.623286+00:00 heroku[web.1]: State changed from starting to crashed 2023-02-20T05:48:57.777654+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path ="/" host=vin-prod.herokuapp.com request_id=d46cea93-368f-4c0a-855f-7e482bc4e826 fwd="174.82.25.34" d yno= connect= service= status=503 bytes= protocol=https 2023-02-20T05:48:58.128022+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path ="/favicon.ico" host=vin-prod.herokuapp.com request_id=8cbbf38a-b258-4ae0-8aef-9d451c099b33 fwd="174. 82.25.34" dyno= connect= service= status=503 bytes= protocol=https I am running my code on windows(VS code). I tried running heroku ps:scale web=1. It works fine : Scaling dynos... done, now running web at 1:Basic In my heroku dynos are set to my waitress-serve. [enter image description here](https://i.stack.imgur.com/eaIyM.png) Please help me out -
I want to display this python dataframe values as a table so in html how can I do that?
performersInfo = MyUser.objects.prefetch_related('newreport_set').filter( Q(is_active=True) & Q(groups__name = 'ITOfficer')).exclude(is_superuser=True).values('id', 'name').annotate(onGoingCount=Case (When (newreport__performer_completion_date__isnull = True, then=(Count('newreport__id'))), default=0)) # .aggregate(totalTask = sum('onGoingCount')) print(performersInfo) performersInfo2 = pd.DataFrame(performersInfo) print(performersInfo2) performersInfo2.columns = performersInfo2.columns.get_level_values(0) aggregateOngoing = performersInfo2.groupby(['id', 'name']).sum() print(aggregateOngoing) the last print results onGoingCount id name 26 Dagim 0 27 Michael M 0 28 Nahom T 2 29 Dawit B 0 30 Kalkidan L 1 31 Kalkidan T 0 32 Melesew 0 33 Michael B 1 {% for key in aggregateOngoing.items %} <p>{{key.1}} {{key.0}}- ({{value.0}})</p> {% endfor %} The format that I want to display in loop is like this 26 Dagim 0 27 Michael M 0 28 Nahom T 2 29 Dawit B 0 30 Kalkidan L 1 31 Kalkidan T 0 32 Melesew 0 33 Michael B 1 -
Can't install mysqlclient
pip install mysqlclient Collecting mysqlclient Using cached mysqlclient-2.1.1.tar.gz (88 kB) Preparing metadata (setup.py) .. done Building wheels for collected packages: mysqlclient Building wheel for mysqlclient (setup.py) .. error ERROR: Command errored out with exit status 1: command: 'c:\users\hp\appdata\local\programs\python\python36\python.exe' -u -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\HP\\AppD ata\\Local\\Temp\\pip-install-mmb7531p\\mysqlclient_a141c7c0a933439fbe19807e877c7cc2\\setup.py'"'"'; __file__='"'"'C:\\Users\\HP\\AppData\\Local\\Temp\\pip-install -mmb7531p\\mysqlclient_a141c7c0a933439fbe19807e877c7cc2\\setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(__file__) if os.path.exists(__file__) else io.St ringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"' ))' bdist_wheel -d 'C:\Users\HP\AppData\Local\Temp\pip-wheel-44gqcvbi' cwd: C:\Users\HP\AppData\Local\Temp\pip-install-mmb7531p\mysqlclient_a141c7c0a933439fbe19807e877c7cc2\ Complete output (25 lines): c:\users\hp\appdata\local\programs\python\python36\lib\distutils\dist.py:261: UserWarning: Unknown distribution option: 'long_description_content_type' warnings.warn(msg) running bdist_wheel running build running build_py creating build creating build\lib.win-amd64-3.6 creating build\lib.win-amd64-3.6\MySQLdb copying MySQLdb\__init__.py -> build\lib.win-amd64-3.6\MySQLdb copying MySQLdb\_exceptions.py -> build\lib.win-amd64-3.6\MySQLdb copying MySQLdb\connections.py -> build\lib.win-amd64-3.6\MySQLdb copying MySQLdb\converters.py -> build\lib.win-amd64-3.6\MySQLdb copying MySQLdb\cursors.py -> build\lib.win-amd64-3.6\MySQLdb copying MySQLdb\release.py -> build\lib.win-amd64-3.6\MySQLdb copying MySQLdb\times.py -> build\lib.win-amd64-3.6\MySQLdb creating build\lib.win-amd64-3.6\MySQLdb\constants copying MySQLdb\constants\__init__.py -> build\lib.win-amd64-3.6\MySQLdb\constants copying MySQLdb\constants\CLIENT.py -> build\lib.win-amd64-3.6\MySQLdb\constants copying MySQLdb\constants\CR.py -> build\lib.win-amd64-3.6\MySQLdb\constants copying MySQLdb\constants\ER.py -> build\lib.win-amd64-3.6\MySQLdb\constants copying MySQLdb\constants\FIELD_TYPE.py -> build\lib.win-amd64-3.6\MySQLdb\constants copying MySQLdb\constants\FLAG.py -> build\lib.win-amd64-3.6\MySQLdb\constants running build_ext building 'MySQLdb._mysql' extension error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools": http://landinghub.visualstudio.com/visual-cpp-build-tools ---------------------------------------- ERROR: Failed building wheel for mysqlclient Running setup.py clean for mysqlclient Failed to build mysqlclient Installing collected packages: mysqlclient Running setup.py install for mysqlclient ... … -
Form Django can't update data
here's my code i can't update my data if i used type "file" My form can't be updated, I try print(form.error) but "this field requirement" appears, even though the form is filled out views.py : @login_required def data_karyawan_edit(request, id): karyawan = Karyawan.objects.get(id=id) ar_divisi = Divisi.objects.all() if request.method == 'POST': form = KaryawanForm(request.POST, request.FILES, instance=karyawan) print(form.errors) if form.is_valid(): form.save() messages.success(request, "Berhasil disimpan") return redirect('data_karyawan') else: form = KaryawanForm() return render(request, "data_karyawan/edit.html", {'karyawan': karyawan, 'ar_divisi': ar_divisi}) -
django-tailwind not loading page if django_browser_reload enabled
I use Cookiecutter Django templpate to generate my project using docker. then I want to integrate it using django-tailwind. django-tailwind work properly when django_browser_reload removed from INSTALLED_APPS, urls.py, and the middleware. Post CSS is generated and loaded successfully when django_browser_reload disabled. But when I enabled it, it just stuck and wont load the page. How can I make django_browser_reload work properly? -
How to create a base serializer to custom generate file field urls
I'm using Django's django-private-storage When an api is created using drf, in the case of a general file field, the url starts with http:// in local and https:// in dev and prod. But for privateFileField it starts with http:// everywhere. Therefore, I want to create a BaseSerializer and create a custom url when the field is a privateFileField. And I want the model serializer with privateFileField to inherit from that serializer. What should I do? I could use get_value() function, but I don't want to implement that function in every model serializer with privateFileField. I want to reduce repetition. Also, the settings that change http:// to https:// are already applied. Only privateFileField is a problem. -
Django partial index on date
Django has allowed partial indices for a while now. I’ve seen examples where it’s set on boolean and strings, but what if I want to set it on a date, for example > 01-01-2023? Engine is PostgreSQL. -
why block tag in django framework is working properly?
i'am new to django , i have been trying to replace small contant of the "base.html" with the contant of "contact.html" but nothing happends base.html <!DOCTYPE html> <html> <head> <title>this is base</title> </head> <body> {% block content %} replace me {% endblock %} </body> </html> contact.html {% extends "base.html" %} {% block content %} <h1>this is contact,contact is working congrats</h1> {% endblock %} result setting.py -
Author page in django migrations and questions
I want to make a website for eBooks with a page that has all the books published by one of the authors. The problem is that I have no idea how to do that. I will mention that I am a beginner. I tried this int the model file class Author(models.Model): author = models.TextField() class Product(models.Model): … author=models.ForeignKey(Author,on_delete=models.CASCADE) The result in the terminal was: File "/home/user/petnet/petnet-env/lib/python3.10/site-packages/django/db/backends/sqlite3/base.py", line 264, in check_constraints raise IntegrityError( django.db.utils.IntegrityError: The row in table 'store_product' with primary key '2' has an invalid foreign key: store_product.author_id contains a value 'anonim' that does not have a corresponding value in store_author.id. I think this is caused by the act that I made the author field later and there were already authors fields from before, but then, when I tried to revert back to what I had before doing this, I got some errors regarding migrations. Also the views were: def author_detail(request, slug): author = get_object_or_404(Author, slug=slug) products = author.products.filter(status=Product.ACTIVE) return render(request, 'store/author_detail.html', { 'author':author, 'products':products }) But I am also curious if there is a chance I could use only this for models so I could use the form for adding a product in a much easier way. class Product(models.Model): … -
Django: Problems passing a list and the results of the list treated by a function as two separate variables to the template
I'm trying to make CV website which has a sudoku generator and solver. The generator and solver are two separate functions in the functions.py file imported into the views.py file. My sudokus are stored in a list of 9 lists of 9 ints. from views.py: from functions import * def sudoku(request): grid = make_sudoku() # generates unsolved sudoku list solved = solve(grid) # generates solved list of unsolved list fed in. count = [i for i in range(9)] context = { 'grid': grid, 'solved': solved, 'count': count } return render(request, 'main/sudoku.html', context) if I print grid, I get an unsolved sudoku list. If I print solved, I get a the same list which has been solved. Everything works dandy up until that point, but if I go to sudoku.html and type {{ grid }}, I get a solved sudoku list. As the tree said to the lumberjack, I'm STUMPED! I'm completely baffled as to why this might happen because at no point in sudoku.html do I refer to grid or solved outside of passing them on to sudoku.js which actually makes the puzzle.