Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Parse JSON nested data from Requests POST response
I'm working on a project using Python(3.7) in which I have to parse a JSON returned from the POST request using Requests library. I googled a lot and tried too many solutions but nothing helped me, so don't mark this as duplicate, please! Here's what I have tried: def process_req(payload): try: headers = { 'Content-Type': 'application/json' } data = payload resp = requests.post( 'http://<EXAMPLE_URL>', data=data, headers=headers ) print('returned data: {}'.format(resp.content.decode('utf8').replace("'", '"'))) resp = resp.content.decode('utf8').replace("'", '"') When I print the resp it provide the following JSON: { "code": "00", "message": "Successful", "data": "{\"requestId\":\"0012602\",\"responseCode\":\"68\",\"responseDescription\":\"Invalid Institution Code\"}" } Now, I need to access the data field of that JSON, here what I tried: resp['data'] But it returns an error as: string indices must be integers -
What is the best practice to let users set a variable which is then be available for all views?
The app I'm working on is a kind of an internal portal for the big Holding (Group of Companies), where various financial and non-financial data stored for all the companies of the Holding. Users are logging into the portal and on the home page they see the list of all Companies that they are authorized to see. Then user should be able to enter into one particular Company from the list and afterwards all subsequent views should show data filtered only for that selected Company until user does not exit it and enter into another Company from home page. I'm trying to achieve this functionality by following but I'm not sure is it proper django way to do it: In views.py I have Mylogin view which is setting global variable Selected_Company='None' when User logs in. Then when User selects any particular Company to work with that Selected_Company variable gets that company's name as a value. All other views which show company related data have a django filter showing model objects matching with the value of Selected_Company. If you know any other proper way to do it, I'd appreciate your advice. Thx -
django test - how to avoid the ForeignKeyViolation
I am struggling to create tests with django with objects that have foreign keys. The tests run with no errors when run individually, but when running all, i get ForeignKeyViolation in the teardown phase (which I don't understand what it does and can't find any info on it). When starting the testsuite I am creating a bunch of dummy data like this: def setUp(self) -> None: create_bulk_users(5) create_categories() create_tags() create_technologies() self.tags = Tag.objects.all() self.categories = Category.objects.all() self.technologies = Technology.objects.all() The problems I need help figuring out are: What exactly the teardown phase does? Are there any detailed docs on it? How should I structure my tests so to avoid the ForeignKeyViolation issue? -
django subprocess.call doesn't work properly when deployed with apache
I have an apache server on centos 7 that run django, in django web I receive http request and pass some parameters to another python file (call file_1) via subprocess.call, in file_1 I'm trying to access database (sqlite3) and change the value in it, for some reason the database doesn't change anything. But when I tested with the following they ran correctly: 1. python command with parameters: python3 file_1 para_1 para_2 2. run webserver with command: python3 manage.py runserver 0.0.0.0:80 -
Django model.py Many To Many Error Query clash
I am trying to create my model.py with a many to many relationship between 2 tables as per the Django practice like follows: class Options(models.Model): # Many to many relationship with Payment OPTIONS_CHOICES = ( ('yearly', 'YEARLY'), ('bi-yearly', 'BI-YEARLY'), ('quarterly', 'QUARTERLY'), ('monthly', 'MONTHLY'), ('weekly', 'WEEKLY'), ('daily', 'DAILY')) can_be_paid_yearly = models.CharField(max_length=25, choices=OPTIONS_CHOICES, default='yearly') payment = models.ManyToManyField('Payment', through='PaymentOptions') def __str__(self): return self.can_be_paid_yearly class Payment(models.Model): # Many to many relationship with Options price = models.PositiveIntegerField() deposit = models.PositiveIntegerField() options = models.ManyToManyField('Options', through='PaymentOptions') def __str__(self): return self.price, self.deposit class PaymentOptions(models.Model): payment = models.ForeignKey('Payment', on_delete=models.SET) options = models.ForeignKey('Options', on_delete=models.CASCADE) This is the error I get: ERROR: rental.Options.payment: (fields.E303) Reverse query name for 'Options.payment' clashes with field name 'Payment.options'. HINT: Rename field 'Payment.options', or add/change a related_name argument to the definition for field 'Options.payment'. rental.Payment.options: (fields.E303) Reverse query name for 'Payment.options' clashes with field name 'Options.payment'. HINT: Rename field 'Options.payment', or add/change a related_name argument to the definition for field 'Payment.options'. How to fix this error and what am I doing wrong? -
Django: export excel using openpyxl
I've faced a problem with exporting of an instance of a model. I have a function that renders a detail view of model and I'd like to export some information about that instance in excel, but my code doesn't work. Hope you have a answer! Thanks)) **def exportToExcel(wb): with NamedTemporaryFile() as tmp: wb.save(tmp.name) tmp.seek(0) stream = tmp.read() response = HttpResponse(content=stream, content_type='application/ms-excel', ) response['Content-Disposition'] = 'attachment; filename=Inform.xlsx' return response def equipment_SIDatailView(request, pk): equip_obj=Equipment_SI.objects.get(pk=pk) parts_obj=Equip_SI_part.objects.filter(name_of_equip=equip_obj) wb = Workbook() ws = wb.active ws.title = "Kniga" ws['A1']='Название оборудования' ws['A2']=equip_obj.name_of_equipment book = exportToExcel(wb) dict={'partis':parts_obj,'equip':equip_obj,'book':book} return render(request,'reestrOMVOiG/equipment_datail.html', context= dict)** HTML **<p><b>Примечание:</b> {{equip.fact}}</p> <p><b>Наименование оборудования:</b> {{equip.name_of_equipment}}</p> <a href="{{book}}">Карточка</a>** -
How to call a function within a function from another function in Django
I'm trying implement Test numbering scheme. On the screen to display/modify a numbering scheme there is a button to test that scheme. Goal of that button is, that the numbering scheme can be tested using the def testnums, which should calll the def nextNums. The result should be displayed in a way you can define, but as such, that the user can easily see, if the increment produced the desired result. [Test numbering scheme][1]`@login_required def nextNums (request, inAppName): try: numsEntry = get_object_or_404(RDdbNums, application=request.inAppName) except: numsEntry = RDdbPref() numsEntry.application = inAppName numsEntry.nextnbr = inAppName + "-000001" numsEntry.scheme = inAppName + "-nnnnnn" numsEntry.ncount = 6 numsEntry.reccount = 1 numsEntry.recincr = 1 numsEntry.Comment = "default value created by rddb" numsEntry.createdBy = request.user numsEntry.modifiedBy = request.user nextNumNbr = numsEntry.nextnbr writeLogfileEntry(request, 0, 'nextNums.nextnbr ' + inAppName + ' ' + nextNumNbr) numsEntry.nextnbr = numsEntry.scheme writeLogfileEntry(request, 0, 'numsEntry.scheme ' + inAppName + ' ' + numsEntry.nextnbr) numsEntry.nextnbr = (numsEntry.nextnbr.replace("YYYY", datetime.datetime.today().strftime('%Y'))) numsEntry.nextnbr = (numsEntry.nextnbr.replace("yy", datetime.datetime.today().strftime('%y'))) numsEntry.nextnbr = (numsEntry.nextnbr.replace("MM", datetime.datetime.today().strftime('%m'))) numsEntry.nextnbr = (numsEntry.nextnbr.replace("DD", datetime.datetime.today().strftime('%d'))) nextNumTxt = str(numsEntry.reccount) while len(nextNumTxt) < numsEntry.ncount: nextNumTxt = '0' + nextNumTxt if numsEntry.ncount == 9: numsEntry.nextnbr = (numsEntry.nextnbr.replace("nnnnnnnnn", nextNumTxt)) elif numsEntry.ncount == 8: numsEntry.nextnbr = (numsEntry.nextnbr.replace("nnnnnnnn", nextNumTxt)) elif numsEntry.ncount == 7: numsEntry.nextnbr = … -
A function with the given name and argument types was not found. Why can't I search for trigram in m-t-m field?
I have a provider model that has addresses that are linked with many-to-many relationship: addresses/models.py: class Street(models.Model): town = models.ForeignKey(Town, default=None, related_name='streets', on_delete=models.CASCADE, verbose_name='') name = models.CharField(max_length=200, db_index=True, verbose_name='', help_text='') slug = models.SlugField(max_length=200, db_index=True, verbose_name='') ... The provider model itself providers/models.py: class Provider(models.Model): location = models.ManyToManyField(Street, db_index=True, symmetrical=False, related_name='providers', verbose_name='') name = models.CharField(max_length=200, db_index=True, verbose_name='') slug = models.SlugField(max_length=200, db_index=True, verbose_name='') ... Next, I want to do a search for the client. The bottom line is that the client enters the name of the street, and as a result he gets a list of all providers that match the search query on the street. Since people tend to make mistakes in street names, I decided to use trigram. So this is the search query handler home/views.py: def providers_search(request): form = SearchForm() query = None results = [] if 'query' in request.GET: form = SearchForm(request.GET) if form.is_valid(): query = form.cleaned_data['query'] results = Provider.objects.annotate( similarity=TrigramSimilarity('location', query), ).filter(similarity__gt=0.3).order_by('-similarity') context = { 'form': form, 'query': query, 'results': results, } return render(request, 'home/search.html', context) And here is a simple form for entering a request home/forms.py: class SearchForm(forms.Form): query = forms.CharField() I end up getting an error that the function similarity(integer, unknown) does not exist (a function … -
How can I improve query performance in Django, N + 1 issue?
I'm having problems with the performance of Django query. Assume I have 3 models and I have 100 rows in Company table: from django.db import models class Company(models.Model): name = models.CharField() def order_count(self): return self.orders.count() def order_sum(self): return (self.orders.all().aggregate(models.Sum('total')))['total__sum'] class Customer(models.Model): company = models.ForeignKey(Company, related_name="customer", on_delete=models.PROTECT) name = models.CharField() def order_count(self): return self.orders.count() class Order(models.Model): company = models.ForeignKey(Company, related_name='orders') customer = models.ForeignKey(Customer, related_name="orders") value = models.FloatField() I want my template to show company's name and sum of its orders, then for each customer of this company, I want to show the customer name with the number of their orders. My query code in views.py is using prefetch like this: queryset = Company.objects.prefetch_related( models.Prefetch('customer', queryset=Customer.objects.prefetch_related('orders')), 'orders') My pseudocode for template: for company in queryset: print(company.name, company.order_count, company.order_sum) for customer in company: print(customer.name, customer.order_count) I've checked with Django Debug Toolbar, it takes 105 queries, with these SQL sentence (pseudo code): SELECT * FROM company SELECT * FROM customer WHERE customer.company_id IN (100 IDs of the companies) SELECT * FROM order WHERE order.customer_id IN (the IDs from previous command)(this duplicates 2 times) SELECT * FROM order WHERE order.company_id IN (100 IDs of the companies) SELECT SUM(order.value) FROM order WHERE order.company_id = %s (this … -
How to render Django page in ASP.NET core page?
I want to render Django Page in asp.net core project and do some database related operation using Django page. So please help me. -
model.save return instance id none
i have 2 models product and review class ProductReview(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) review_heading = models.CharField(max_length=30) review_date = models.DateTimeField(auto_now_add=True) review_description = models.CharField(max_length=200) review_rating = models.PositiveIntegerField() review_product_image = models.ImageField(upload_to='review_image/', blank=True) class Product(models.Model): name = models.CharField(max_length=100) price = models.IntegerField(default=0) category = models.ForeignKey(Category, on_delete=models.CASCADE) description = models.CharField(max_length=300, default='', null=True, blank=True) product_image = models.ImageField(upload_to='', blank=True) is_varient = models.BooleanField(default=False) has_varient = models.BooleanField(default=False) is_published = models.BooleanField(default=False) varient_property = models.ManyToManyField(to='store.AttributeValue', blank=True) parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True) i am saving review using form. def post(self, request, *args, **kwargs): form = ReviewForm(request.POST) if form.is_valid(): instance = ProductReview(**form.cleaned_data) instance.save() print(model_to_dict(instance)) # i have also tried form.save() but results the same # form.save() return redirect('OrderView') model_to_dict output is {'id': None, 'user': 1, 'product': 278, 'review_heading': 'nice product', 'review_description': 'ok', 'review_rating': 4, 'review_product_image': <ImageFieldFile: None>} here it returns id=none and nothing get saved. if i save child instance of product it get saved and also returns id=25 but when i save master product then it returns id=none please help me to save master product -
How Do I create database Models in Django?
Before heading straight to my issue,I would like to state that I am a newbie in Django. My database models were created in Sqlalchemy Flask. I want to write the same database model in my Django application as well. To keep it simple this is how a model was created using Sqlalchemy in Flask. flask_model.py class LeadsStatus(db.Model): __tablename__ = 'leads_status' if leadgenapp.config['TESTING']: f_key = 'companies.id' else: __table_args__ = {'schema': tbl_schema} f_key = f'' + tbl_schema + '.companies.id' id = db.Column(db.Integer, primary_key=True, autoincrement=True) company_id = db.Column(db.Integer, db.ForeignKey(f_key), nullable=False, index=True) status = db.Column(db.String(120)) users_id = db.Column(db.Integer) assign_date = db.Column(db.DateTime) companies = db.relationship('Companies', backref='leadstatus') This model contains a foreign key. My issue is while I am creating the same model it throws an error stating that f_key is not defined. This is how I have written the model. django_model.py class LeadsStatus(models.Model): __tablename__ = 'leads_status' # if leadgenapp.config['TESTING']: # f_key = 'companies.id' # else: # __table_args__ = {'schema': tbl_schema} # f_key = f'' + tbl_schema + '.companies.id' id = models.IntegerField(primary_key=True, auto_created=True) company_id = models.ForeignKey(f_key, nullable=False, index=True, on_delete=models.CASCADE) status = models.CharField(max_length=120) users_id = models.IntegerField() assign_date = models.DateTimeField() companies = models.relationship('Companies', backref='leadstatus') I understood the reason of the error but what I cannot understand is how … -
How to Add Delete view according to role based in django
Hi I am working on Tree Structure role. There are 4 roles 1.A 2.B 3.C 4.D Where A can add,delete view B,C,D and B,C,D cannot delete or view A. B can add,delete view C,D but can cannot delete A and its parent. Similary for C and D. I can create different views and use permissions in Django. But I want to implement this using one view.I will be adding the role through url suppose through url and not from choice. Please help me with this. Thanks in Advance. -
Displaying data from one database table without using id and objects.all() -django
I want to display some of the field values from member table (fullname, email, contactno, companyname etc..,) in profile page fieldset. models.py for member table class Member(models.Model): fullname=models.CharField(max_length=30) companyname=models.CharField(max_length=30) Email=models.CharField(max_length=50) password=models.CharField(max_length=12) contactno = models.CharField(max_length=30,default='anything') models.py for profile table. class Profile(models.Model): fullname=models.CharField(max_length=60) contactno=models.CharField(max_length=10) worknumber=models.CharField(max_length=10) email=models.CharField(max_length=30) companyname=models.CharField(max_length=30) timezone=models.CharField(max_length=20) here is the profile page, the data should displayed automatically -
i want to display registered person values to another html page in django
i have member table for registration.. i want to display that table values(like firstname,lastname, email etc..) in another page (only registered person values ) i tried with id.. if i give id means only that particular value is displaying... but i want registered person values this is my member table class Member(models.Model): firstname=models.CharField(max_length=30) lastname=models.CharField(max_length=30) Email=models.CharField(max_length=50) password=models.CharField(max_length=12) Thanks for your time. -
DRF: Set ImageField to not required in external serializer
UserSerializer contains an ImageField, which is set to blank=True, null=True and a default picture URL is given. In my OtherSerializer, I try to get the ImageField into it via: class OtherSerializer(serializers.ModelSerializer): user_image = serializers.SerializerMethodField() class Meta: model = OtherModel fields = ('user_image') def get_user_image(self, obj): return obj.find_user_and_all_that_stuff_not_an_actual_method.image However, when I try to call the data from OtherSerializer, I get: image attribute has no file associated with it. Any way I can set required = False, if the field is external and doesn't have that parameter? -
Program not parsing whole in POST method
I am getting " AssertionError: 'CouponValidationView' should either include a serializer_class attribute, or override the get_serializer_class() method." when i click on API link but when i put 'serializer_class' in my django class based viewset, program do not parse through subsequent function it just get over after serializer_class() method. Here is my views.py file : class CouponValidationView(viewsets.ModelViewSet): queryset = Coupon.objects.all() serializer_class = CouponSerializer def get(self, request, code, format=None): try: coupon = Coupon.objects.get(code=code) except ObjectDoesNotExist: return Response( data={"message": "Success"}, status=status.HTTP_404_NOT_FOUND ) serializer= CouponSerializer(coupon) resp = {"data": serializer.data, "message": "Failure"} return Response(resp, status=status.HTTP_200_OK) Please do Help -
Django Admin Model Thousand Separator in Change form when using Grappelli extension
I am working on an internal Django project using the Grappelli Admin Theme. I am in Australia and would like to format decimal numbers above 999 as 1,000.00 2,000.00. I have added the following to my settings.py file and the Model field has been defined as a Decimal. The Change List form displays the number correctly formatted. However, the changeform does not and retains the unlocalized format. LANGUAGE_CODE = 'en-us' TIME_ZONE = 'Australia/Queensland' USE_I18N = True USE_L10N = True USE_THOUSAND_SEPARATOR = True NUMBER_GROUPING = 3 I have found numerous similar posts such as Make Django forms use comma as decimal separator And it does state localization does need to be turned on explicitly for every field. For a model form (including the ones used in the admin app), a convenient way to do this is to subclass ModelForm and turn on localization for each DecimalField However, at this stage I just need the Admin Change Form to carry the localisation and I am not sure how to do this when the Grappelli extension is in play. And as I have mentioned the Change List Form does render the same field with the thousand separator as I had hoped. Your thoughts … -
how can i send email using djcelery
here i am using djangorestframework and i am trying to send email using celery whenever is trying to login with a report but i am getting smtp error every time i have used api view serialiazer and trying to send email whoever login i couldn't understand what is my error and did i wrote the tasks.py correctly settings.py """ Django settings for MyMovie project. Generated by 'django-admin startproject' using Django 2.2. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) import djcelery djcelery.setup_loader() # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '=g9h-vb%r2^_lngqh_mn3y29g2n_7zvfkj(ysshs#hv5pbj0=%' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'knox', 'djcelery', 'django_celery_beat', 'TestApp' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ # 'rest_framework.authentication.BasicAuthentication', # 'rest_framework.authentication.SessionAuthentication', 'knox.auth.TokenAuthentication', ], 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.AllowAny', ] } ROOT_URLCONF = 'MyMovie.urls' TEMPLATES … -
raise EnvironmentError( OSError: pdftotext not installed. Can be downloaded from https://poppler.freedesktop.org/) in python
I am using the invoice2data library to extract data from the invoice and getting this error... > Traceback (most recent call last): File "C:\Users\{user-name}\Envs\django\lib\site-packages\django\core\handlers\exception.py", > line 47, in inner > response = get_response(request) File "C:\Users\Abhishek Saini\Envs\django\lib\site-packages\django\core\handlers\base.py", > line 179, in _get_response > response = wrapped_callback(request, *callback_args, **callback_kwargs) File "E:\stuff\pdf_reader\pdf_processing\structuredpdf\views.py", line 41, > in fileUpload > pdf = extract_data(str(files.name),templates=read_templates("invoice/")) > File "C:\Users\Abhishek > Saini\Envs\django\lib\site-packages\invoice2data\main.py", line 82, in > extract_data > extracted_str = input_module.to_text(invoicefile).decode('utf-8')File "C:\Users\{user- name}\Envs\django\lib\site-packages\invoice2data\input\pdftotext.py", > line 29, in to_text > raise EnvironmentError( OSError: pdftotext not installed. Can be downloaded from https://poppler.freedesktop.org/ I already install pdftotext and tried reinstalling anaconda and poppler but got the same error what should I do now -
django static error in bash linux command
File "/usr/lib/python3.7/os.py", line 221, in makedirs mkdir(name, mode) PermissionError: [Errno 13] Permission denied: '/static' -
Failure: Azure GitHub Deployment for Django-React Web App
I'm completely new to Azure and I deployed my Django-React web app. It says the deployment was successful, however, on the actual web address, it says the application failed. I have a few dumb questions: In the settings.py file that's in the GitHub repo, I removed the security key and database password for security reasons. Is that the issue? The runtime stack is Python 3.8, but could that be an issue since the frontend is react.js? What are HTTP errors 503 and 502 associated with? -
Django POST data from admin not being displayed
So I have looked over this so many times now and cannot seem to find the issue for the life of me. Not only does it not display the database information that it queried for, I cannot seem to add anything to it through the form. The views.py method I have is supposed to either render all the info into the divs, yet it renders the right amount of divs with no information in it. Also, the post request goes through as i can see on cmd, but the database remains unchanged, and no changes are made to the HTML. please i could use some help. views.py from django.shortcuts import render from .models import Note def notes(request): if request.method == "POST": new_note = request.objects.all() Note.objects.add(new_note) return render(request, "notebook/notes.html", { "notes": Note.objects.all() }) models.py from django.db import models class Note(models.Model): title = models.CharField(max_length=64) content = models.CharField(max_length=300) def __str__(self): return f"{Note.title} {Note.content}" layout.html(just the relevant part) <div class="card content"> <div class="card-body"> <h4 class="card-title" style="font-weight: bold;"> Post A New Note </h4> <form action="{% url 'notebook:notes' %}" method="post"> {% csrf_token %} <div class="input"> Note Title </div> <div><input name="title" style="margin-top: -10px;"></div> <div class="input">Note Content </div> <div><input class="note_txt" name="content"></div> <div class="row"> <input class="btn" type="submit" style="margin-top: 20px;"> … -
Packaging my Django Application to Windows Installer
I have a Django application, and it is working fine with Apache and MySQL. Now I need to distribute it as a windows installer. I normally use Ubuntu, so I don't know much about creating a windows installer. The installer basically should do the below things. Extract the package ( I am thinking of packaging my application, python(with all the dependencies installed), Apache, and MySQL in the package) Set the Env Variables for Python referring to the python in the package. Install or Extract Apache and configure the same to point to my application. Install MySQL. Create DB and run manage.py migrate. Bring up the apache, The targeted end users are just laymen, so the installation process should as installing a windows application. Request you to please suggest on the best way package the same. -
django queryset to select max id of each distinct filed
I'm new to django, and I want to select last message of each thread: models.py class ChatMessage(models.Model): thread = models.ForeignKey('Thread', null=True, blank=True, on_delete=models.CASCADE) user = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name="sender", on_delete=models.CASCADE) message = models.TextField(null=True) timestamp = models.DateTimeField(auto_now_add=True) voice = models.FileField(upload_to=upload_voice_dir, blank=True, null=True) I'v no idea how to filter(I just know basics of filtering). to sum it up I want the last message of each thread.