Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Show a field data into header section of a pdf file
I am quite new to using this library call Django Reportlab where I'd like to show "supplier" details into the header section of the pdf file. Here is the code def generate_pdf(request): pdf_buffer = BytesIO() doc = SimpleDocTemplate(pdf_buffer, pagesize=landscape(letter)) styles = getSampleStyleSheet() elements = [] paragraph_text = 'Victorious Step Sdn.Bhd. (667833-T)' columns = [ {'title': 'Date', 'field': 'created_date'}, {'title': 'Part No', 'field': 'partno'}, {'title': 'Supplier Name', 'field': 'supplier'}, {'title': 'Status', 'field': 'limit'}, ] table_data = [[col['title'] for col in columns]] orders = Order.objects.all() for tr in orders: table_row = [str(tr.created_date.strftime("%d-%m-%Y")), tr.part.partno, tr.supplier] table_data.append(table_row) table = Table(table_data, repeatRows=1, colWidths=[doc.width / 7.0] * 7) table.setStyle(TableStyle([ ('BOX', (0, 0), (-1, -1), 0.20, colors.dimgrey), ('FONT', (0, 0), (-1, 0), 'Helvetica-Bold'), ('INNERGRID', (0, 0), (-1, -1), 0.1, colors.black), ('ALIGN', (0, 0), (-1, -1), 'CENTER'), ('FONTSIZE', (0, 0), (-1, -1), 10), ])) elements.append(table) elements.append(Spacer(1, 50)) doc.build(elements) pdf = pdf_buffer.getvalue() pdf_buffer.close() response.write(pdf) return response I am trying to show the supplier data after the paragraph_text = 'Victorious Step Sdn.Bhd. (667833-T)' . Can anyone assist me with how to do that? Thanks in advance. -
Record user's voice and save it to db in Django
I want to build a Django app in which a user can record his/her voice. I have used the following link: https://github.com/Stephino/stephino.github.io/blob/master/tutorials/B3wWIsNHPk4/index.html in order to capture user's voice and it works perfectly for me, but I do not know exactly how to save it to database. I do not know how to build my Model and also a form to do this. Does anybody have any idea? (The obligatory framework is Django and in terms of db my preference is Postgresql) -
Django model abstract model with constrains not being inherited: 'constraints' refers to field 'xxx' which is not local to model 'Foo'
I am using Django 3.2 I have come across a strange behaviour which appears to be a bug; Fields used in constraints defined in a ABC are not inherited by child classes. myapp/models.py class BaseFoo(models.Model): content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE,related_name='%(class)s_content_type') object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') user = models.ForeignKey(User, blank=False, null=False, on_delete=models.CASCADE,related_name='%(class)s') created = models.DateTimeField(auto_now_add=True) class Meta: abstract = True constraints = [ models.UniqueConstraint(fields=['content_object', 'user'], name="'%(class)s_unique"), ] class Foo(BaseFoo): class Meta(BaseFoo.Meta): abstract = False No problem when I makemigrations, but, When I attempt to migrate the schema (`python manage.py migrate), I get the following error: myapp.Foo: (models.E016) 'constraints' refers to field 'content_object' which is not local to model 'Foo'. HINT: This issue may be caused by multi-table inheritance. Why is Foo not inheriting the fields clearly defined in the parent ABC? - and how do I fix this (assuming it's not a bug)? -
Django - how to change view based on option chosen in select dropdown from template
I am attempting to display a graph that is responsive to an option chosen by the user from a select form. However, I'm finding that the graph isn't acting responsive when I choose other options besides 'BTC'. relevant main.HTML: <div class = "container"> <form method = "POST" action = ""> <select name = "coin-select"> {% for coin in coin_lst %} <option value="{{ coin }}">{{ coin }}</option> {% endfor %} </select> </form> </div> <div class = "container"> {% autoescape off %} {{ graph }} {% endautoescape %} </div> relevent view.py: def initial_data(request): coin_lst = [] for x in focused_df.coin: if x not in coin_lst: coin_lst.append(x) def close_vs_redditComments(): if request.method == 'POST': coin = str(request.POST.get("coin-select")) else: coin = 'BTC' closeVSredditComment = make_subplots(specs=[[{"secondary_y": True}]]) closeVSredditComment.add_trace(go.Scatter(x = df[df.coin == coin]['time'], y = df[df.coin == coin]['close'], name = "closing price"), secondary_y = False) closeVSredditComment.add_trace(go.Scatter(x = df[df.coin == coin]['time'], y = df[df.coin == coin]['reddit_comments'], name = "reddit comment volume"), secondary_y = True) return(plot(closeVSredditComment, output_type = 'div')) context = { 'coin_lst': coin_lst, 'graph': close_vs_redditComments() } return render(request, 'main.html', context) What am I missing here? -
Possibility to display current partner.id in odoo view
I want to get the current partner's id in my stock.picking view. I foud something like this <field name="myId" domain="[('partner_id','=',id)]" /> but it's wrong.Is it even possible to have the current partner's id? -
Django access html info from form post method
this is my first Django Project so I just wanted to know if what I want to do is viable. I have an html with two fors right now and other additional info In Form1, it calls ajax method to populate the list of products that is included in Form2. What I want to do is in Form2 (this form contains the product list, the Unidades input and the button) post method, get the fields that are in red (they are not inside Form2) Is there a way to achieve this? Or the only way is to put this fields inside Form2. I also attach mi post method, keyinvoice number is the first field in red section im trying to get but obviously brings a None class CurrentSaleAddProduct(LoginRequiredMixin, View): login_url = reverse_lazy('users_app:user-login') def post(self, request, *args, **kwargs): productselect = self.request.POST.getlist('productselect') keyunits = self.request.POST.get("keyunits", None) keyinvoicenumber = self.request.POST.get("invoice_number", None) print(keyinvoicenumber) for p in productselect: product_selected = Product.objects.search_id(p) stock_product_selected = Stock.objects.search_id(p) obj, created = CurrentSaleItems.objects.get_or_create( product=product_selected, defaults={ 'count': Decimal(keyunits), 'total': Decimal(keyunits)*stock_product_selected.price_sale }) if not created: obj.count = obj.count + Decimal(keyunits) obj.total = obj.total + \ Decimal(keyunits)*stock_product_selected.price_sale obj.save() """ car = CarShop.objects.get(id=self.kwargs['pk']) if car.count > 1: car.count = car.count - 1 car.save() # … -
Loading Django static files from React component
I am fairly new to React/Django/web development in general. I know there are a lot of questions on SO about how to load static files in Django templates, but I couldn't find anything helpful on how to do this in React components. Scenario: I am building a React-Django app, and one of the features is to render a PDF document based on some user input. I am able to render the pdf successfully with react-pdf if the file is stored somewhere in the react app's source tree. However, I want to serve these pdf files from the backend. Currently, I have a Django model with a FilePathField that points to where these pdfs are on my filesystem. What is the best practice for using this file path to render the pdf in React? Also, is this approach even correct? -
Django : donwloading server files on client side
I am running a Django project on a company server also that stores some .pdf and .docx files. Only workers have acces to this Django app throught their local machines and they need to download files from the server to their machines. I used webbrowser open, but files were opened on server machine in stead of clients one. Can you please help me with this issue? Thanks! -
How can i make 2 attributes unique in a table (Django)
It is possible to have a unique row, and make create_or_update on it? image: I want to have unique attributes for idTest + EmailStudent -
Reverse for 'order_successful' with no arguments not found despite sending an argument. DJANGO
I am new to django. I am making a website for a customer. I am integrating a paypal client side module and followed a video from youtube for the purpose. On order completion, I am trying to go to a page and I am passing it product id so it can retrieve it from the database and display a nice thank you page. But I am getting the following error: NoReverseMatch at /product-details/payment Reverse for 'order_successful' with no arguments not found. 1 pattern(s) tried: ['order_success/(?P[^/]+)$'] Following is my page checkout.html from where I am calling the function: <script> function getCookie(name) { let cookieValue = null; if (document.cookie && document.cookie !== '') { const cookies = document.cookie.split(';'); for (let i = 0; i < cookies.length; i++) { const cookie = cookies[i].trim(); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } const csrftoken = getCookie('csrftoken'); var total = '{{price}}' var quantityBought = '{{quant}}' var prodId = '{{prod.id}}' var fName = '{{firstName}}' var lName = '{{lastName}}' var apt = '{{apt}}' var street = '{{street}}' var city = '{{city}}' var … -
Can't properly runserver/ project structure incorrect?
I'm attempting to build a small project for myself. It's a trip planner. I'm working primarily with django/python combination and can't seem to find the issue. In particular I'm getting this error when I'm going to run server in powershell; django.core.exceptions.ImproperlyConfigured: Cannot import 'logReg'. Check that 'apps.logReg.apps.LogregConfig.name' is correct. I've checked within VS code and it's not linking my logReg app. See here: class LogregConfig(AppConfig): name = 'logReg' Once I delete it, it just says it can't find the second app 'trips' Am I missing something where's it's just not recognizing all my imports? -
Need help in reducing the complexity or duplication in the function mentioned
Hi can someone please help me in reducing the complexity of the below mentioned code as I am new to this I need it to reduce the amount of code and improve the code and to improve simplicity and reduce duplications in the overall coding any any help in this regard can be of great help and thanks in advance for your time and consideration in helping me in this regard. ''' class SynonymSerializer(serializers.ModelSerializer): class Meta: model = synonym fields = 'all' def update(self, instance, validated_data): instance.insured_synonym = validated_data.get('insured_synonym', instance.insured_synonym) instance.obligor_borrower_counterparty_synonym = validated_data.get('obligor_borrower_counterparty_synonym', instance.obligor_borrower_counterparty_synonym) instance.guarantor_synonym = validated_data.get('guarantor_synonym', instance.guarantor_synonym) instance.credit_rating_synonym = validated_data.get('credit_rating_synonym', instance.credit_rating_synonym) instance.country_of_risk_synonym = validated_data.get('country_of_risk_synonym', instance.country_of_risk_synonym) instance.tenor_synonym = validated_data.get('tenor_synonym', instance.tenor_synonym) instance.coverage_synonym = validated_data.get('coverage_synonym', instance.coverage_synonym) instance.insured_transaction_synonym = validated_data.get('insured_transaction_synonym', instance.insured_transaction_synonym) instance.any_third_parties_synonym = validated_data.get('any_third_parties_synonym', instance.any_third_parties_synonym) instance.premium_rate_synonym = validated_data.get('premium_rate_synonym', instance.premium_rate_synonym) instance.margin_synonym = validated_data.get('margin_synonym', instance.margin_synonym) instance.utilization_expected_utilization_synonym = validated_data.get( 'utilization_expected_utilization_synonym', instance.utilization_expected_utilization_synonym) instance.purpose_synonym = validated_data.get('purpose_synonym', instance.purpose_synonym) instance.retained_amount_synonym = validated_data.get('retained_amount_synonym', instance.retained_amount_synonym) instance.insured_percentage_synonym = validated_data.get('insured_percentage_synonym', instance.insured_percentage_synonym) instance.payment_terms_synonym = validated_data.get('payment_terms_synonym', instance.payment_terms_synonym) instance.secured_security_synonym = validated_data.get('secured_security_synonym', instance.secured_security_synonym) instance.waiting_period_synonym = validated_data.get('waiting_period_synonym', instance.waiting_period_synonym) instance.brokerage_synonym = validated_data.get('brokerage_synonym', instance.brokerage_synonym) instance.broker_synonym = validated_data.get('broker_synonym', instance.broker_synonym) instance.ipt_synonym = validated_data.get('ipt_synonym', instance.ipt_synonym) instance.enquiry_code_synonym = validated_data.get('enquiry_code_synonym', instance.enquiry_code_synonym) instance.law_synonym = validated_data.get('law_synonym', instance.law_synonym) instance.terms_of_repayment_synonym = validated_data.get('terms_of_repayment_synonym', instance.terms_of_repayment_synonym) instance.financials_limit_synonym = validated_data.get('financials_limit_synonym', instance.financials_limit_synonym) fields_25_synonym_key = [ 'insured_synonym', 'obligor_borrower_counterparty_synonym', 'guarantor_synonym', 'credit_rating_synonym', 'country_of_risk_synonym', 'tenor_synonym', 'coverage_synonym', 'insured_transaction_synonym', 'any_third_parties_synonym', 'premium_rate_synonym', … -
Django: Trying to access the limited no of random question(tell by user) of specific types from the database table
In my Django Project i have a Topic table , Subtopic Table, Question table ,Opions table and Answer table. Here Iam trying to access the limited number of random questions of specific subtopics [both the no of questions(limited number of questions) and subtopics are chosen by user]. like below one here is my models.py class Add_Topics(models.Model): grade = models.ForeignKey(Add_Grade,on_delete=models.CASCADE, default = 1) topic = models.CharField(max_length=40) def __int__(self): return id class Meta: db_table = 'Add_Topics' class Sub_Topics(models.Model): grade = models.ForeignKey(Add_Grade,on_delete=models.CASCADE, default = 1) topic = models.ForeignKey(Add_Topics,on_delete=models.CASCADE, default = 1) videofile = models.FileField(upload_to='videos/', null=True, verbose_name="") subtopic = models.CharField(max_length=40, default = 1) def __str__(self): return self.subtopic class Meta: db_table = 'Sub_Topics' class Questions(models.Model): grade = models.ForeignKey(Add_Grade,on_delete=models.CASCADE, default = 1) topic = models.ForeignKey(Add_Topics, on_delete= models.CASCADE , default = 1) sub_topic = models.ForeignKey(Sub_Topics, on_delete= models.CASCADE, default = 1) question = models.CharField(max_length=100) image= models.URLField(null=True) difficulty=models.CharField(max_length=100, default='') class Meta: db_table = 'questions' class Options(models.Model): grade = models.ForeignKey(Add_Grade,on_delete=models.CASCADE, default = 1) topic = models.ForeignKey(Add_Topics, on_delete= models.CASCADE, default = 1) sub_topic = models.ForeignKey(Sub_Topics, on_delete= models.CASCADE, default = 1) question = models.ForeignKey(Questions, on_delete= models.CASCADE, default = 1) option1 = models.CharField(max_length=20) option2 = models.CharField(max_length=20) option3 = models.CharField(max_length=20) option4 = models.CharField(max_length=20) class Meta: db_table = 'Options' class Answers(models.Model): grade = models.ForeignKey(Add_Grade,on_delete=models.CASCADE, default … -
Sub domain does not show cookie sent by server in response header
App description - Frontend - React hosted on a.example.com Backend - Django hosted on b.example.com Django sends a cookie in get request like below - set-cookie: sessionid=iqyb5hgi6m3qmeojyb07a794z3x2wtz0; Domain=a.example.com; expires=Wed, 09 Jun 2021 18:25:19 GMT; HttpOnly; Max-Age=1209600; Path=/; SameSite=None; Secure In Django settings, I tried giving the most possible access to test if things works, of course not for production, like below - CORS_ORIGIN_ALLOW_ALL = True SESSION_COOKIE_DOMAIN = 'a.example.com' CSRF_COOKIE_SECURE = True SESSION_COOKIE_SECURE = True CSRF_COOKIE_SAMESITE = 'None' SESSION_COOKIE_SAMESITE = 'None' ALLOWED_HOSTS = ['.example.com'] CSRF_TRUSTED_ORIGINS = ['a.example.com'] CSRF_ALLOWED_ORIGINS = ['a.example.com'] CORS_ALLOW_ALL_ORIGINS = True CORS_ALLOW_CREDENTIALS = True But does not show up in cookies in the browser. What am I doing wrong? Any help appreciated! Thanks -
How to make Heroku to store my updates to the website?
I have deployed a new Django project to Heroku and any changes to the database via the project are getting lost or reset after a dyno restart. I don't want this to happen. What are the ways to not lose the data? I am also planning on buying a paid version of Heroku for my project. So , the solutions with paid resources are also appreciated. Thank You in advance. -
How can translations be activated in Postorius / Mailman3-Web?
So I installed mailman3-full on a fresh debian buster machine, along with dovecot, postfix, and sqlite3. After several days of tweaking I managed to get it all running nicely, with one exception: Until now, I was not able to figure out, how I would alter the language of the web-frontend. I already did install package locales on the system, set de_DE.UTF8 as default locale and ran locale-gen set default_locale: de in /etc/mailman3/mailman.cfg set the following in /etc/mailman3/mailman-web.py: LANGUAGE_CODE = 'de' USE_I18N = True USE_L10N = True The docs give some advise, how to list available langauges: launching mailman shell, then entering from mailman.interfaces.languages import ILanguageManager from zope.component import getUtility from zope.interface.verify import verifyObject mgr = getUtility(ILanguageManager) list(mgr.codes) list(mgr.languages) I see that German (de) is available as well as others. But this page gives no advise, how to activate a specific langauge. The contibution guide states something about Weblate, and po files, but no instructions for activation here. In the installation instructions using Virtualenv there is a section Compile messages for l10n. When I replace mailman-web with /usr/share/mailman3-web/manage.py I am able to run all the commands (e.g. /usr/share/mailman3-web/manage.py collectstatic), the compilemessages command gives me an error: CommandError: This script should be … -
Django model ordering one model by count in another model referenced by GenericForeignKey
I am using Django 3.2 I have the following apps and models: social/models.py class SocialAction(models.Model): content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE,related_name='%(class)s_content_type') object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') user = models.ForeignKey(User, blank=False, null=False, on_delete=models.CASCADE,related_name='likes') created = models.DateTimeField(auto_now_add=True) class Meta: abstract = True constraints = [ models.UniqueConstraint(fields=['content_object', 'user'], name="unique_like"), ] class Like(SocialAction): pass foo/models.py class Foo(models.Model): pass Note: I cannot modify Foo code, but I want to add "Like" functionality to Foo. I have utility functions that add creates new records in the Like table, and adds the references to the object that has been liked. I want to write a queryset function, that returns a set of Foo objects, but ranked in DESC order of likes. I know I have to use either aggregation or annotations - but I'm not sure how. def get_most_liked_foo(): return Foo.objects.filter() # /* not sure how to construct rest of query */ My question is - how do I return a recordset of Foo objects, ranked by most liked? -
How does python find modules without a path?
For example, when using django I can get my settings from anywhere within the project using from djanog.conf import settings. I don't have to specify where django.conf is, it just knows. How does it know? I ask because I'm building a project where I need to be able to import a conf file without knowing the relative path. What is the best way to do this? I'm sure some variation of this question has been asked hundreds of times before but I can't seem to find the answer. If you of a good answer that already exists please let me knows. Thanks.s -
How to get few last rows from related table?
Need help with a orm request. There are 2 tables. Author and Book (names for example, so you don't need to look at the logic), linked through FK. class Book(models.Models): title = models.Charfield(...) class Author(models.Model): book = models.ForeignKey(Book) Need to group the authors by the book and go through them in a loop. The question is how to select only the last 50 authors of each book. I can write this: for book in Book.all() for author in book.author_set.all()[:50]: .... But this is not an optimal solution. -
How can I integrate django with react?
My website uses as frontend reactjs and django as backend. I couldn't do the integration between the frontend and the backend. The backend is based on a deep learning model. PS: The frontend will send a text (which you have to upload) to the backend. And the backend will send a result using the model prediction. -
How can I crop an image with Cropperjs without losing quality?
I'm showing a previously uploaded image on the client side and using cropperjs to let the user crop it and then re-upload with a button click. const submit_button = document.getElementById('submit-btn'); const input = document.getElementById('id_file'); const image = document.getElementById('image'); let cropper = new Cropper(image, { autoCropArea: 1, zoomable: false, preview: '.preview' }) input.addEventListener('change', () => { const img_data = input.files[0] image.src = URL.createObjectURL(img_data); cropper.replace(image.src) }); submit_button.addEventListener('click', () => { cropper.getCroppedCanvas({ imageSmoothingEnabled: true, imageSmoothingQuality: 'high' }).toBlob((blob) => { let file = new File([blob], "cropped.png", {type: "image/png", lastModified: new Date().getTime()}); let container = new DataTransfer(); container.items.add(file); input.files = container.files; document.getElementById("form").submit(); }, 'image/png', 1); }); The code works just fine, except that the image get's compressed with every new crop. How can I disable compression? I already tried some suggestions (imageSmoothing, setting quality to 1), but that does nothing at all. -
Hot to find out if it is first user log in with django social?
I am building an app, witch django social, and i need to do some stuff when user register, but i can not find out whether this is his first log in or not, how can i do that without alter user db, and without last_login == date_joined (because i think it's pretty dirty way, tell me if not) Also sorry for my bad english in some places. -
How to create web application for CNN model using react
I am currently working on my python project based on Keras CNN models. I want to deploy the project to a website. For front-end I want to use React.js just because I have my expertise in it. I am confuse for the backend technology I should use, below are the technologies I have explored. 1)Flask 2)Django 3)Spring I want your suggestions which is the best for me to use. I have two models one is working on the output of other which means I have python code between the results of two models. Waiting for your suggestion. Thanks in advance. -
Error (1045, "Access denied for user 'user'@'172.27.0.3' (using password: YES)")
In trying to connect to connect to mysql using docker but I get the following logs below. How do I resolve this? db_1 | Version: '5.7.34' socket: '/var/run/mysqld/mysqld.sock' port: 3307 MySQL Community Server (GPL) db_1 | 2021-05-26T17:02:40.191347Z 2 [Note] Access denied for user 'admin'@'172.27.0.3' (using password: YES) db_1 | 2021-05-26T17:02:40.259636Z 3 [Note] Access denied for user 'admin'@'172.27.0.3' (using password: YES) db_1 | 2021-05-26T17:02:40.275977Z 4 [Note] Access denied for user 'admin'@'172.27.0.3' (using password: YES) db_1 | 2021-05-26T17:02:40.361165Z 5 [Note] Access denied for user 'admin'@'172.27.0.3' (using password: YES) db_1 | 2021-05-26T17:02:40.366075Z 6 [Note] Access denied for user 'admin'@'172.27.0.3' (using password: YES) db_1 | 2021-05-26T17:02:40.367748Z 7 [Note] Access denied for user 'admin'@'172.27.0.3' (using password: YES) db_1 | 2021-05-26T17:02:40.370714Z 8 [Note] Access denied for user 'admin'@'172.27.0.3' (using password: YES) db_1 | 2021-05-26T17:02:40.372608Z 9 [Note] Access denied for user 'admin'@'172.27.0.3' (using password: YES) db_1 | 2021-05-26T17:02:40.402829Z 10 [Note] Access denied for user 'admin'@'172.27.0.3' (using password: YES) db_1 | 2021-05-26T17:05:14.885240Z 11 [Note] Access denied for user 'root'@'localhost' (using password: NO) Docker Compose File version: '3' services: # redis: # restart: always # image: redis:latest # expose: # - "6379" db: image: mysql:5.7 command: --default-authentication-plugin=mysql_native_password restart: always environment: MYSQL_DATABASE: default_schema MYSQL_USER: admin MYSQL_PASSWORD: test MYSQL_ROOT_PASSWORD: *asus@2837 MYSQL_TCP_PORT: … -
Annotate filed with first key in JSON Field
I have model with JSON type field json_field_name { "123": "1", "145": "2" } I want to use annotate function to create a new column "json_first_key" , that will contain the First key in every json . I want a new annotated field - "json_first_key" , that will contains only the first key in the json . ie "123" , in this case I can do the same using rawSQL query . I would like to do it using Django ORM instead . I am using Postgresql database. Using RawSQL models = Model.objects..annotate( json_first_key=RawSQL( """select first_key from (select distinct on (id) id,jsonb_object_keys(json_field_name) AS first_key FROM app_model) as model_row where model_row.id = app_model.id limit 1""", [], ) )