Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Using python script to upload a file to django server localhost
I build an django rest framework that can help me to upload a file in view.py class FileResultViewSet(viewsets.ModelViewSet): queryset = FileResult.objects.order_by('-timestamp') serializer_class = FileResultSerializer parser_classes = (MultiPartParser, FormParser) def perform_create(self, serializer): serializer.save() The script work well without any error, and the file is stored in media folder Then, I use an python script that can help me to upload file to django import requests import openpyxl url = "http://localhost:8000/upload/" headers = {'Content-Type': 'multipart/form-data'} file_path = "H:/MEGA_H/Data/uploaded/Book1.xlsx" ''' with open(file_path, 'rb') as f: file = {'file': f} response = requests.get(url, headers=headers, files=file) ''' filename = "Book1.xlsx" # Open the file and read its contents with open(file_path, 'rb') as f: file_contents = f.read() # Create a dictionary to store the file information #file_data = {'file': (filename, file_contents,result_file)} file_data = { "result_file": file_contents } # Make a POST request to the URL with the file information response = requests.post(url, files=file_data) # Check if the request was successful if response.status_code == 201: print("File successfully uploaded") else: print("Failed to upload file") The code still works with an issue, after upload the file to media folder, the file doesnt include the file type, so it can not read. I have to change the name of the … -
DJango how to create path to custom method in view?
I've been learning django for a few days and I started creating a simple project. However I have small problem with urls. In my project I created view: views/cars/scrapped_view.py from app.models import ScrappedCar from django.views.decorators.csrf import csrf_exempt from django.utils.decorators import method_decorator from rest_framework import status from rest_framework.views import APIView from rest_framework.response import Response from rest_framework.request import Request @method_decorator(csrf_exempt, name='dispatch') class ScrappedView(APIView): def get(self, request: Request) -> Response: # /cars/scrapped scrapped_cars = ScrappedCar.objects.all() return Response(scrapped_cars, status=status.HTTP_200_OK) def related(self, request: Request, id=None) -> Response: # /cars/scrapped/<int:id>/related scrapped_car = ScrappedCar.objects.get(id=id) related_scrapped_cars = ScrappedCar.objects.filter(user_id=scrapped_car.user_id, paid=True) return Response(related_scrapped_cars, status=status.HTTP_200_OK) The problem is that I don't know how to create a path to the method related. I was trying many different things but nothing works. Here you can see few of them: urls.py from django.urls import path from .views.cars.scraped_view import ScrapedView urlpatterns = [ path(route=‘cars/scrapped’, view= ScrapedView.as_view()), # works # path(route='cars/scrapped/<int:id>/related', view=NegativeKeywordView.as_view()) not working # path(route='cars/scrapped/<int:id>/related', view=NegativeKeywordView.as_view({‘get’ : ‘related})) not working # path(route='cars/scrapped/<int:id>/related', view=NegativeKeywordView.related) not working ] Do you know what I am doing wrong? How I can create path /cars/scrapped/<id>/related to the method related? -
Django - Find sum and count of values in child table using serializers
I have two tables: Event and EventTicket. I have to return total transactions and total tickets sold of each event. I am trying to achieve this using Django serializers. Using only serializers, I need to find the following: 1. total tickets sold: count of items in EventTicket table for each event 2. total transactions: sum of total_amount of items in EventTicket table for each event where payment_status: 1 I read about SerializerMethodField but couldn't find a solution specific to this scenario. class Event(models.Model): name = models.CharField(max_length=100, null=False, blank=False) description = models.TextField(null=False, blank=False) date_time = models.DateTimeField() class EventTicket(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) event = models.ForeignKey(Event,on_delete=models.CASCADE) payment_status = models.SmallIntegerField(default=0, null=False, blank=False) ## payment_success: 1, payment_failed: 0 total_amount = models.FloatField() date_time = models.DateTimeField() My desired output is: "ticket_details": [ { "event_id": 1, "event_name": Event-1, "total_transactions": 10000, ## Sum of all ticket amounts of event_id: 1, where payment_status: 1 "total_tickets": 24, ## Count of all tickets that belong to event_id: 1 }, { "event_id": 2, "event_name": Event-2, "total_transactions": 10000, ## Sum of all ticket amounts of event_id: 2, where payment_status: 1 "total_tickets": 24, ## Count of all tickets that belong to event_id: 2 }] -
Partial change in the model of one field for individual users - DRF
I have a model: class Task(models.Model): title = models.CharField(max_length=255) description = models.TextField() status = models.ForeignKey(Status, on_delete=models.PROTECT, related_name='todo_status') author = models.ForeignKey(User, on_delete=models.PROTECT, related_name='todo_author') assignet_to = models.ManyToManyField(User, blank=True, related_name='todo_assigned_to') I want the user/users who will in field assigned_to the Task to only be able to edit the field Status. How I see it: url - for view Check_status And view Check_status class CheckStatusView(generics.RetrieveUpdateAPIView): queryset = Task.objects.all() serializer_class = TaskDetailSerializer permission_classes = [permissions.IsAuthenticated] and then I think I need redefine this def put(self, request, *args, **kwargs): return self.update(request, *args, **kwargs) or def patch(self, request, *args, **kwargs): return self.partial_update(request, *args, **kwargs) or maybe: def partial_update(self, request, *args, **kwargs): kwargs['partial'] = True return self.update(request, *args, **kwargs) I want the user/users who will in field assigned_to the Task to only be able to edit the field Status. -
What static code analyzer should be choosen for backend and frontend?
I need to choose great static code analyzer for a product where backend is on django and frontend is on angular. Which one is best? What options are great? To get list of static code analysers -
error al ejecutar npm run serve dentro de la carpeta frontend
estaria necesitando ayuda ya que al intentar ejecutar npm run serve dentro de mi carpeta front en mi proyecto django saltan los siguientes errores ERROR Failed to compile with 1 error 13:19:35 [eslint] Failed to load plugin '@typescript-eslint' declared in '.eslintrc.json': Cannot find module 'typescript' Require stack: /home/juan/Escritorio/proyectopersonal/app_front/node_modules/@typescript-eslint/eslint-plugin/dist/util/astUtils.js /home/juan/Escritorio/proyectopersonal/app_front/node_modules/@typescript-eslint/eslint-plugin/dist/util/index.js /home/juan/Escritorio/proyectopersonal/app_front/node_modules/@typescript-eslint/eslint-plugin/dist/rules/adjacent-overload-signatures.js /home/juan/Escritorio/proyectopersonal/app_front/node_modules/@typescript-eslint/eslint-plugin/dist/rules/index.js /home/juan/Escritorio/proyectopersonal/app_front/node_modules/@typescript-eslint/eslint-plugin/dist/index.js /home/juan/Escritorio/proyectopersonal/app_front/node_modules/@eslint/eslintrc/lib/config-array-factory.js /home/juan/Escritorio/proyectopersonal/app_front/node_modules/@eslint/eslintrc/lib/index.js /home/juan/Escritorio/proyectopersonal/app_front/node_modules/eslint/lib/cli-engine/cli-engine.js /home/juan/Escritorio/proyectopersonal/app_front/node_modules/eslint/lib/cli-engine/index.js /home/juan/Escritorio/proyectopersonal/app_front/node_modules/eslint/lib/api.js /home/juan/Escritorio/proyectopersonal/app_front/node_modules/eslint-webpack-plugin/dist/getESLint.js /home/juan/Escritorio/proyectopersonal/app_front/node_modules/eslint-webpack-plugin/dist/linter.js /home/juan/Escritorio/proyectopersonal/app_front/node_modules/eslint-webpack-plugin/dist/index.js /home/juan/Escritorio/proyectopersonal/app_front/node_modules/@vue/cli-plugin-eslint/index.js /home/juan/Escritorio/proyectopersonal/app_front/node_modules/@vue/cli-service/lib/Service.js /home/juan/Escritorio/proyectopersonal/app_front/node_modules/@vue/cli-service/bin/vue-cli-service.js Referenced from: /home/juan/Escritorio/proyectopersonal/app_front/.eslintrc.json You may use special comments to disable some warnings. Use // eslint-disable-next-line to ignore the next line. Use /* eslint-disable */ to ignore all warnings in a file. ERROR in [eslint] Failed to load plugin '@typescript-eslint' declared in '.eslintrc.json': Cannot find module 'typescript' Require stack: /home/juan/Escritorio/proyectopersonal/app_front/node_modules/@typescript-eslint/eslint-plugin/dist/util/astUtils.js /home/juan/Escritorio/proyectopersonal/app_front/node_modules/@typescript-eslint/eslint-plugin/dist/util/index.js /home/juan/Escritorio/proyectopersonal/app_front/node_modules/@typescript-eslint/eslint-plugin/dist/rules/adjacent-overload-signatures.js /home/juan/Escritorio/proyectopersonal/app_front/node_modules/@typescript-eslint/eslint-plugin/dist/rules/index.js /home/juan/Escritorio/proyectopersonal/app_front/node_modules/@typescript-eslint/eslint-plugin/dist/index.js /home/juan/Escritorio/proyectopersonal/app_front/node_modules/@eslint/eslintrc/lib/config-array-factory.js /home/juan/Escritorio/proyectopersonal/app_front/node_modules/@eslint/eslintrc/lib/index.js /home/juan/Escritorio/proyectopersonal/app_front/node_modules/eslint/lib/cli-engine/cli-engine.js /home/juan/Escritorio/proyectopersonal/app_front/node_modules/eslint/lib/cli-engine/index.js /home/juan/Escritorio/proyectopersonal/app_front/node_modules/eslint/lib/api.js /home/juan/Escritorio/proyectopersonal/app_front/node_modules/eslint-webpack-plugin/dist/getESLint.js /home/juan/Escritorio/proyectopersonal/app_front/node_modules/eslint-webpack-plugin/dist/linter.js /home/juan/Escritorio/proyectopersonal/app_front/node_modules/eslint-webpack-plugin/dist/index.js /home/juan/Escritorio/proyectopersonal/app_front/node_modules/@vue/cli-plugin-eslint/index.js /home/juan/Escritorio/proyectopersonal/app_front/node_modules/@vue/cli-service/lib/Service.js /home/juan/Escritorio/proyectopersonal/app_front/node_modules/@vue/cli-service/bin/vue-cli-service.js Referenced from: /home/juan/Escritorio/proyectopersonal/app_front/.eslintrc.json webpack compiled with 1 error probe borrar y reinstalar la carpeta node modules pero no hay solución por mas que la reinstalo sigue saltando el mismo error -
How do I display my list view in recommended_items?
I'd like to show the list's introduction to users, and I've used the Association rule in Django for this project. views.py def user_detail(req, id): AllParcel = Add_Parcel.objects.filter(id=id).first() df = pd.read_csv('myapp/recommend.csv') df = df.drop_duplicates().reset_index(drop=True) df = df.pivot(index='item_id', columns='user_id', values='user_id') df = df.notnull().astype(int) frequent_itemsets = apriori(df, min_support=0.5, use_colnames=True) rules = association_rules(frequent_itemsets, metric="confidence", min_threshold=0.5) user_loans = LoanParcel.objects.filter(user=req.user) user_borrowed = [loan.parcel_item.name for loan in user_loans] recommended_items = [] for item in rules['antecedents']: if set(item).issubset(set(user_borrowed)): recommended_items.extend(list(Add_Parcel.objects.filter(name__in=rules[rules['antecedents'] == item]['consequents'].tolist()[0]))) context = { "AllParcel": AllParcel, "recommended_items" : recommended_items, } return render(req,'pages/user_detail.html',context) I wanted to render recommended_items to display similar to Add_Parcel using data from Add_Parcel's database to display, but when I put the display command in HTML, it returned as a blank value. How should I fix it? user_detail.html <h2>Recommended Items</h2> <ul> {% for parcel in recommended_items %} <li>{{ parcel.name }} ({{ parcel.nametype }}) - {{ parcel.description }}</li> {% endfor %} </ul> recommend.csv item_id,user_id 1,1 1,2 1,3 1,4 1,5 1,6 1,7 3,8 3,9 3,10 3,11 1,12 1,11 1,10 2,9 2,8 2,7 -
How can I customize text wrapping and text style in Bokeh table?
I have a base Bokeh table in Django Python. I have it displayed in its basic form - as by default without any style editing. At me all words are superimposed on other columns of the data. What's in the header of the table - what's in the body of the table. I can not change the font of the table - the title and body of the table. How can I set up a data-wrapped display of table text on another line? And how can I change the font of the text inside the table - the table header and table body? My table does not expand to the entire DIV container in which it is located. Sometimes layering on other template objects. How can this be set up? def table_htmx(request): context = {} qs_select_tabl = Table_model.objects.filter(name_1=select_1).order_by('name_name') qs = qs_select_tabl.values() df = pd.DataFrame.from_records(qs) header = [field.verbose_name for field in Table_model._meta.get_fields()] df.columns = header template = """ <div style="font-size: 100%"> <%= value %> </div> """ template_html = HTMLTemplateFormatter(template=template) columns = [TableColumn(field=col, title=col, formatter=template_html) for col in header] source = ColumnDataSource(df) data_table = DataTable(source=source, columns=columns, width=800) script, div = components(data_table) context['script'] = script context['div'] = div return render(request, "table_htmx.html", context) -
Display a list of related fields in the admin panel
I have two related models. class Refbook(models.Model): code = models.CharField(max_length=100, unique=True) name = models.CharField(max_length=300) description = models.TextField() class VersionRefbook(models.Model): refbook_id = models.ForeignKey('Refbook', on_delete=models.CASCADE, related_name='versions') version = models.CharField(max_length=50) date = models.DateField() When I edit a Refbook instance in the admin panel, I want the read-only list of available versions of this Refbook instance to be displayed on the same page. I know that it is possible to output them through TabularInline . And it seems that there is a read-only property here. Maybe there is a way to display just a list in a column or row separated by commas? Now, I have this code in admin.py: @admin.register(Refbook) class RefbookAdmin(admin.ModelAdmin): list_display = ['id', 'code', 'name'] I tried to create a "get_versions(self)" method in models.py in Refbook class, in which I received a queryset using related_name. But I can't display it in the admin panel. Or is it still correct to do this using the model.ModelAdmin parameters? -
How to ensure consistency between Django models and underlying databases
On our staging server we observed a runtime error stating a field is missing from a database, column our_table.our_field does not exist LINE 1: ...d"."type", "our_table"... The field was added in a latest update during some complex migration squashing process, through which we should have made some mistakes. Since manage.py showmigration did show the migration has been applied and we do not run our tests on staging/production servers, we are wondering what is the best way to detect such an error. To rephrase the question using a simpler example, how to detect inconsistency between database structure and Django models after an incorrect migration introduced by something like the following? python manage.py migrate our_app --fake I suppose I am looking for something like python manage.py check_database -
django get to every user if its latest record match given value in table
I want to filter students if his last record transaction_type match with given value. For example Student Ali has 3 record in transaction table. And if the latest records transaction_type == 'busy' I want to get this transaction otherwise I want to pass this transaction My Models like that class Type(models.Model): type = models.CharField(max_length=50) def __str__(self): return self.durum class Student(models.Model): ogr_no = models.CharField(max_length=10, primary_key=True) ad = models.CharField(max_length=50) soyad = models.CharField(max_length=50) bolum = models.CharField(max_length=100,blank=True) dogum_yeri = models.CharField(max_length=30) sehir = models.CharField(max_length=30) ilce = models.CharField(max_length=30) telefon = models.CharField(max_length=20,blank=True, null=True) nufus_sehir = models.CharField(max_length=30,blank=True, null=True) nufus_ilce = models.CharField(max_length=30,blank=True, null=True) def __str__(self): return self.ogr_no + " " + self.ad + " " + self.soyad class Transaction(models.Model): student = models.ForeignKey(Student, on_delete=models.CASCADE, related_name='islemogrenci') transaction_type = models.ForeignKey(Type, on_delete=models.CASCADE) yardim = models.ForeignKey(Yardim, on_delete=models.CASCADE, blank=True, null=True) aciklama = models.CharField(max_length=300,blank=True, null=True) transaction_date = models.DateTimeField(blank=True,null=True) transaction_user = models.ForeignKey(User, on_delete=models.CASCADE,null=True,blank=True) def __str__(self): return self.student.ad + " " + self.transaction_type.durum Note: I use Postgres as Database Engine -
Django one column values to one column concat value using annotate Subquery returns more than 1 row
hellow my models see the blow class IP(models.Model): subnet = models.ForeignKey(Subnet,verbose_name="SUBNET",on_delete=models.CASCADE,related_name="ip_set") ip = models.GenericIPAddressField(verbose_name="IP",protocol="both",unpack_ipv4=True,unique=True) asset = models.ManyToManyField(Asset,verbose_name="HOSTNAME",through="AssetIP",related_name="ip_set",blank=True,) description = models.CharField(verbose_name="DESCRIPTION",max_length=50,default="",null=True,blank=True) class AssetIP(models.Model): TYPE_CHOICES = [ ("GATEWAY-IP", "GATEWAY-IP"), ("MGT-IP", "MGT-IP"), ("PRIMARY-IP", "PRIMARY-IP"), ("OTHER-IP", "OTHER-IP"), ] ip_type = models.CharField(verbose_name="IP TYPE",max_length=30,choices=TYPE_CHOICES) ip = models.ForeignKey(IP,verbose_name="IP",on_delete=models.CASCADE,related_name="asset_ip_set") asset = models.ForeignKey(Asset,verbose_name="HOSTNAME",on_delete=models.CASCADE,related_name="asset_ip_set") class Asset(models.Model): barcode = models.CharField(verbose_name="Barcode",max_length=60,blank=True,null=True,unique=True) hostname= models.CharField(verbose_name="Hostname",max_length=30) so in this model data is blow IP Model | IP | Asset | Description | |:---- |:------:| -----:| | 10.10.10.2 | A_HOST,B_HOST,C_HOST | - | | 10.10.10.3 | A_HOST,B_HOST | - | | 10.10.10.4 | A_HOST | - | | 10.10.10.5 | A_HOST | - | AssetIP through Model | IP | Asset | IP_TYPE | |:---- |:------:| -----:| | 10.10.10.2 | A_HOST | OTHER-IP | | 10.10.10.2 | B_HOST | OTHER-IP | | 10.10.10.2 | C_HOST | OTHER-IP | | 10.10.10.3 | A_HOST | OTHER-IP | | 10.10.10.4 | A_HOST | OTHER-IP | | 10.10.10.5 | A_HOST | PRIMARY-IP | So Asset Query Result in this Result = Asset.objects.all() in this result Field Asset = { barcode: "ddd", hostname: "A_HOST", } I Want Field and Result Asset = { barcode: "ddd", hostname: "A_HOST", primary_ip : "10.10.10.5", other_ip : "10.10.10.2, 10.10.10.3, 10.10.10.4" } I Try the this query … -
"<VariationPrice>" needs to have a value for field "id" before this many-to-many relationship can be used
I have this model in my django code. I want to check whether VariationPrice for a product with the variations exist. If it exists, make changes to the already existing VariationPrice else save the new VariationPrice. The error I'm getting with the existing code is "<VariationPrice: >" needs to have a value for field "id" before this many-to-many relationship can be used. class Product(models.Model): .... product_name = models.CharField(max_length=200, unique=True) class Variation(models.Model): .... variation_value = models.CharField(max_length=100) class VariationPrice(models.Model): price = models.IntegerField() product = models.ForeignKey(Product, on_delete=models.CASCADE) variations = models.ManyToManyField(Variation, blank=True) def __str__(self): if self.pk is not None: return ", ".join(str(var) for var in self.variations.all()) else: return '' def save(self, *args, **kwargs): if self.pk is None: var_list = [i['variation_value'] for i in self.variations.values()] vprice = VariationPrice.objects.filter(product=product,variations__variation_value__in=var_list).annotate(num_attr=Count('variations__variation_value')).filter(num_attr=len(var_list)) if vprice.exists(): self.pk = vprice.first().pk super(VariationPrice, self).save(*args, **kwargs) -
How to print elements of list of an unknown number of zipped lists in Djanto templates
a = [1,2,3,4,5] b = [[3,4],[4,5],[6,7]] out = [[x if x in l else 'X' for x in a] for l in map(set, b)] z = zip(a,*out) In above code the list a will have fix number of elements but list b will be varying, hence elements in z will vary as well. Now in Django template I would Like to print the elements of z. What I tried for above scenario is {% for d,s1,s2,s3 in z %} <tr> <td> {{d}} </td> <td> {{s1}} </td> <td> {{s2}} </td> <td> {{s3}} </td> </tr> {% endfor %} Which works fine if I know the number of elements present in the z; but unfortunately it's varying. Sometimes it could have 10 lists , sometimes nothing. Sometimes the scenario will be like below: {% for d,s1 in z %} <tr> <td> {{d}} </td> <td> {{s1}} </td> </tr> {% endfor %} So How can I correct above template code to print variable number of list elements in the table? Thanks. -
Django tutorial throws ImportError if importing the model from commandline python
Given the exact code from the tutorial part Creating models polls/models.py from django.db import models class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) Why can't I from .models import Question? [polls]$ python Python 3.8.12 (default, Dec 4 2021, 10:54:00) [GCC 11.1.0] on linux Type "help", "copyright", "credits" or "license" for more information. >>> from .models import Question Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: attempted relative import with no known parent package Otherweise the tutorial works fine so yes _init_.py exists in the polls directory (created by the django tutorial). None of the many related questions have helped me, thus please don't close as duplicate. -
Django: Object of type Profile is not JSON serializable
I have a model called Order, Profile and Users. In my Order model, i want to access the Profile of the buyer and seller, so i wrote a function in the Order model to get the profile of the buyer and the seller. class Orders(models.Model): service = models.ForeignKey(Service, on_delete=models.SET_NULL, null=True, related_name="service_orders") seller = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, related_name="seller") buyer = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, related_name="buyer") ... def seller_profile(self): seller_profile = Profile.objects.get(user=self.seller) return seller_profile def buyer_profile(self): buyer_profile = Profile.objects.get(user=self.buyer) return buyer_profile Now when i add the seller_profile and buyer_profile in my OrderSerializer in serializer.py, and try accessing the api endpoint in the browser, it shows the error Object of type Profile is not JSON serializable, Do i need to serialize my Profile Model or something like that? class OrderSerializer(serializers.ModelSerializer): class Meta: model = Orders fields = ['id','seller', 'buyer', 'buyer_profile', 'seller_profile', ...] def __init__(self, *args, **kwargs): super(OrderSerializer, self).__init__(*args, **kwargs) request = self.context.get('request') if request and request.method=='POST': self.Meta.depth = 0 else: self.Meta.depth = 2 I dont have any ProfileSeriallizer, do i need it? -
Django DSL custom analyzer
i made my own custom analyzer, I am using elasticsearch:7.5.2 when i run python manage.py search_index --rebuild the error is raise RedeclaredFieldError( django_elasticsearch_dsl.exceptions.RedeclaredFieldError: You cannot redeclare the field named 'name' on CarDocument class CarDocument(Document): name = fields.TextField(analyzer=ngram_analyzer) class Index: name = 'cars' settings = { 'number_of_shards': 1, 'number_of_replicas': 0, } class Django: model = Car fields = [ 'name' ]``` -
How can two HTML template elements be updated using (HTMX)?
I have a form in which there are three fields, basically these fields contain drop-down lists - selections. These select lists are based on a data model that has fields associated with ForeynKey . After completing this form. I update information, code and do calculations in code. Further after the calculations. I am updating two elements on the template - a table and a graph. I have these two elements in separate parts of the template. Like two different pieces of HTML . With (HTMX) I can only update one element on the table - this element is a chunk of the HTML template - which is updated by rendering that chunk of that template. How can I update another piece of the template? How can two HTML template elements be updated using (HTMX) ? I would be very grateful for any help. -- <div class="row"> <div class="col-6"> <form method="POST" class="post-form"> {% csrf_token %} {{form_1.as_p}} <button type="submit" class="save btn btn-light">Form</button> </form> </div> </div> <div class="row"> <div class="col"> {{ div_1|safe }} {{ script_1|safe }} </div> </div> <div class="row"> <div class="col"> {{ div_2|safe }} {{ script_2|safe }} </div> </div> -- class Form_1(forms.ModelForm): class Meta: model = Model_1 fields = "__all__" -- class … -
Add CSS File to Django Project - Nothing seems to work
I feel kinda tired of this problem right now, and am desperately looking for help. I try to add a main.css file to my django project so I can do the CSS myself. Watched like 8 full tutorials already and 6 of them crashed my project while the other 2 did not work. So please is there anyone who really knows how to do this? This must be a really simple thing i guess? Im stuck on my project for 3 days now, so frustrating. I hope to find a decent explanation of someone who really knows how this works. -
Using stripe.js with dj-stripe
I'm using django and I want to integrate stripe using the abstraction layer dj-stripe. From what I understand from the documentation, ElementJs with Payment Intent is the preferred way to allow users to enter their payment details. see https://dj-stripe.dev/stripe_elements_js/ However, there is no documentation on how to connect dj-stripe with stripe.js. The first step of the usage documentation in dj-stripe already assumes payment methods have been connected (https://dj-stripe.dev/usage/subscribing_customers/). I looked through the code of dj-stripe and it seems to have Payment Intent classes, but I can't figure out how to use them. How can I generate a client secret for customers created in dj-stripe that can then be used in stripe.js? (Or if I'm not on the right path, what should I do instead to allow adding payment details to be used in dj-stripe) -
Possibility to return json or xml In one django function
There is a task in which you need to implement the ability, depending on the url, to transfer data to the user in json or xml format. format is passed to str:typeof path('<str:typeof>/site/<str:domain_name>', ApiInterfaceViewSet.as_view({"post":"site_info"})), The main logic is implemented in the ViewSet class class ApiInterfaceViewSet(ViewSet): read_only = True renderer_classes = (XMLRenderer, JSONRenderer) def site_info(self, request: HttpRequest, typeof: str, domain_name: str, *args, **kwargs): responce = None records = Site.objects.raw("""select * from urlopen_app_site uas where uas.domain_name = %s""", [domain_name]) serializer = SiteSerializer(records[0]) if typeof == 'json': responce = Response(serializer.data, content_type='application/json; charset=utf-8') return responce elif typeof == 'xml': xml_data = XmlRendererSite(records) xml_data = xml_data.formation_xml_site() responce = Response(xml_data.getvalue().decode(encoding="utf-8"), content_type='application/xml; charset=utf-8') return responce an xml transformation factory implemented in the XmlRendererSite class. Manually It would be possible to separate the logic into different classes. in one class return xml, and in another json but it needs to be implemented in one function The problem I am facing is how to implement this idea. Explicitly specifying the content type does not help. The XML is returned as a string. response.media_type = "application/xml" doesn't help. I broke my head. I miss something important or get confused in simple things separating logic into different classes works correctly, but … -
How to solve SMTP Recipient Refused error
I had set app password in EMAIL_PASSWORD but i am getting this error smtp RecipientsRefused.The entered gmail ids are correct. I have followed all mentioned procedures in app password generation i don't know what is the cause of the error -
I can't use try-except in django
I have problem in try-except The file is views.py function 'noun_check' return nouns of the sentence that I received from contenct.para(=input) If there is no noun in the sentence than function 'noun_check' return error If the error occur, go to except and return(request, 'main/desktop.html'), and receive another sentence. And If I got nouns, I return render(request, 'main/introduction.html', context). This is the way I thought. But error occured in function 'noun_check', logic doesnt' go to except, and return render(request, 'main/introduction.html', context) Could you explain why try-except doesn't work? def submit(request): if request.method == 'POST' and request.POST['input'] != '': try: content = Diary_content() content.para = request.POST['diary_input'] tokenized_nouns = noun_check(content.para) context = {'para' : content.para, 'emotions':tokenized_nouns} return render(request, 'main/introduction.html', context) except: return render(request, 'main/desktop.html') I seperate the function, and made function if error occur return False And use temp = function(sentence) \n if temp == 0: ... Althogh 'temp == 0' is True, logic doesn't go under 'if function' -
Django admin prefetch_related
I have django models organized like this: class Filmwork(UUIDMixin, TimeStampedMixin): ... class Genre(UUIDMixin, TimeStampedMixin): ... class GenreFilmwork(UUIDMixin): film_work = models.ForeignKey(Filmwork, on_delete=models.CASCADE) genre = models.ForeignKey(Genre, on_delete=models.CASCADE) How can i get prefetch all genres of filmwork in django admin using prefetch_related? I'm trying like this: @admin.register(Filmwork) class FilmworkAdmin(admin.ModelAdmin): list_display = ('title', 'type', 'get_genres', 'creation_date', 'rating', 'created', 'modified') list_prefetch_related = ( ??????? ) def get_queryset(self, request): queryset = ( super() .get_queryset(request) .prefetch_related(*self.list_prefetch_related) ) return queryset def get_genres(self, obj): return ','.join([genre.name for genre in obj.genres.all()]) -
why docxtpl jinja annotate doesnt work with postgrsql?
i ve created a view to generate a doc with docxtpl, for this i use this view bellow but the annotate with FLoatfield doesnt work, can you help me please ? def postACD(request, id): Raison_sociale = Client.objects.filter(id=id).values_list('Raison_sociale',flat=True).annotate(Raison_sociale_as_float=Cast('Raison_sociale', output_field=FloatField())).get() byte_io = BytesIO() tpl = DocxTemplate(os.path.join(settings.MEDIA_ROOT, 'ACD.docx')) context = {} context['Raison_sociale'] = Raison_sociale tpl.render(context) tpl.save(byte_io) byte_io.seek(0) return FileResponse(byte_io, as_attachment=True, filename=f'ACD{id}.docx') you can see the message error : enter image description here i try many solutions but nothing