Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to add header to JSONresponce?
In my Angular/Django project I need to make query from angular frontend to the server. In response Django send me JSON data of that user of message that user does not exist. First query(option) has response code 200. Second part(exactly POST) throws CORS error. I think I need add it to response header, but I can't find something about adding header in JSONResponce. Please help me with that My Django code from django.core.exceptions import ObjectDoesNotExist from django.http import HttpResponse from django.http.response import JsonResponse from django.utils.decorators import method_decorator from django.views import View from django.views.decorators.csrf import csrf_exempt from rest_framework.parsers import JSONParser from .models import User from .serializers import UserSerializer class UserView(View): allowed_methods = ["options", "get", "put", "post", "delete"] @method_decorator(csrf_exempt) def dispatch(self, request, *args, **kwargs): return super(UserView, self).dispatch(request, *args, **kwargs) def options(self, request, email=""): response = HttpResponse() response["Access-Control-Allow-Origin"] = '*' response["Access-Control-Allow-Headers"] = "Content-Type, Access-Control-Allow-Origin, Access-Control-Allow-Headers" response["Content-Type"] = 'application/json' response["allow"] = ",".join(self.allowed_methods) return response def get(self, request, email=""): users = User.objects.all() users_serializer = UserSerializer(users, many=True) return JsonResponse(users_serializer.data, safe=False) def put(self, request, email=""): user_data = JSONParser().parse(request) user = User.objects.get(email=user_data["email"]) # щоб знати конкретного юзера, інфу якого змінюватимемо user_serializer = UserSerializer(user, data=user_data) if user_serializer.is_valid(): user_serializer.save() return JsonResponse("User information was updated successfully", safe=False) else: return JsonResponse("Failed to … -
InvalidTemplateEngineError in oscar
I am using django-oscar for my development. I have created a new app as per my requirement views.py class MediaImportView(TemplateView): template_name = 'lookup/import_media_file.html' def get(self, request): ctx = {} return render(self.template_name, ctx, request, using=request) getting the error as below. InvalidTemplateEngineError at /import_media_file Could not find config for '<WSGIRequest: GET '/import_media_file'>' in settings.TEMPLATES -
Problems with the integration of Django 3 and Vue 3
I have been trying to integrate Django 3 with Vue 3 for two days and I have partly succeeded but not as I would like. Stage. The idea is to use Vue 3 for components that require Javascript and are not important for SEO like booking forms, etc … Integrate by using django-webpack-loader to inject the bundle into django templates. const BundleTracker = require("webpack-bundle-tracker"); module.exports = { publicPath: "http://0.0.0.0:8080/", outputDir: './dist/', pages: { main: { // entry for the page entry: 'src/main.js', } }, chainWebpack: config => { config.optimization .splitChunks(false) config .plugin('BundleTracker') .use(BundleTracker, [{filename: './webpack-stats.json'}]) config.resolve.alias .set('__STATIC__', 'public') config.devServer .public('http://0.0.0.0:8080') .host('0.0.0.0') .port(8080) .hotOnly(true) .watchOptions({poll: 1000}) .https(false) .headers({"Access-Control-Allow-Origin": ["\*"]}) } }; This is the content of the ** main.js ** that is the entry point of the Vue3 app import { createApp, reactive, ref } from ‘vue’ const app = createApp({ el: ‘#app’, delimiters: [’[[’, ‘]]’], setup() { const data = { returned_task: ref(''), temp_task: ref(''), modify_index: ref(-1), tasks: reactive([]), } const methods = { select: (index) => { if (data.modify_index.value === index){ data.modify_index.value = -1; } else { data.modify_index.value = index data.temp_task.value = data.tasks[data.modify_index.value] } }, deleteSelected: () => { data.tasks.splice(data.modify_index.value, 1); data.modify_index.value = -1; }, updateSelected: () => { … -
Inheritance in classes django
I am currently working on my first website and I'm working with class-based views because I've been told their inheritance is outstanding. Here's the code so you can make yourselves an idea of what I'm trying to do before I tell you the error I'm having. class TranslatorView(View): def translate_amino(self, codon): return self.amino_mapper.get(codon, "") def build_protein(self, phrase): protein = [] i = 0 while i < len(phrase): codon = phrase[i: i + 3] amino = self.translate_amino(codon) if amino: protein.append(amino) else: print(f"The codon {codon} is not in self.mapper_1") i += 3 return protein def error_1(self, request): amino_1= self.build_protein(request.GET.get('phrase','')) if len(amino_1) % 3: messages.error(request, "DNA chain must be divisible by 3") return redirect('/') Basically, what I'm trying to do is to inherit the function build_protein to the def error_1. That's why I create a variable called amino_1 equal to the def build_protein. Afterwards, I create a condition saying if amino_1 detects a phrase that it's a total number of letters aren't divisible by three, it should raise a value error. However, it appears it's not inheriting anything at all. -
DJANGO: How to specify primary key in fixture when the primary key is not "id"
I just changed my pk name in a model. This is how my model was: class Course(LogsMixin, models.Model): """Definición del modelo de Proveedor.""" name = models.CharField("Nombre del curso", null=False, default="", max_length=200) code = models.CharField("Código del curso", null=False, default="", max_length=50) hours = models.IntegerField(("Número de horas"), null=False, default=0) price = models.DecimalField(("Precio"), max_digits=6, decimal_places=2, null=False, default=0) provider = models.ForeignKey(Provider, verbose_name=("Proveedor"), null=True, default=None, on_delete=models.SET_DEFAULT) active = models.BooleanField("Activo", default=True) As you can see I didnt specified the PK but I changed that: class Course(LogsMixin, models.Model): """Definición del modelo de Proveedor.""" reference = models.CharField("Referencia", primary_key=True, null=False, default="", max_length=50) name = models.CharField("Nombre del curso", null=False, default="", max_length=200) code = models.CharField("Código del curso", null=False, default="", max_length=50) hours = models.IntegerField(("Número de horas"), null=False, default=0) price = models.DecimalField(("Precio"), max_digits=6, decimal_places=2, null=False, default=0) provider = models.ForeignKey(Provider, verbose_name=("Proveedor"), null=True, default=None, on_delete=models.SET_DEFAULT) active = models.BooleanField("Activo", default=True) As you can see now "reference" is my pk but when I try to install this fixture: [{ "models": "consumptions.course", "pk": "AD_ADGD008PO", "fields": { "name": "ANÁLISIS DE PROBLEMAS Y TOMA DE DECISIONES", "code": "ADGD008PO", "price": "21.00", "hours": "30", "provider": "P000019", "active": true } }, I receive the next error: Traceback (most recent call last): File "C:\Users\aquesada\.virtualenvs\AVC-dSHgJ7e5\lib\site-packages\django\core\serializers\json.py", line 69, in Deserializer yield from PythonDeserializer(objects, **options) File "C:\Users\aquesada\.virtualenvs\AVC-dSHgJ7e5\lib\site-packages\django\core\serializers\python.py", line … -
Django - How to take string values on URL for PUT?
I set up my URL like this : path('voucher/<str:voucher_id>', views.update_voucher), My process def update_voucher(request, voucher_id): put = QueryDict(request.body) try: customer_id = put.get('customer_id') except: return HttpResponse("Missing parameters") updateVoucher = Voucher.objects.filter(code = voucher_id) Its a PUT call taking parameters from both body and url. (voucher_id from URL) and (customer_id from body) . I call this URL http://127.0.0.1:5448/voucher/NewVoucher I got this error: ValueError: Field 'id' expected a number but got 'NewVoucher'. The below is my model: here. class Voucher(models.Model): code = models.CharField(unique=True, max_length=255) delivery_type = models.CharField(max_length=255) description = models.CharField(max_length=255, blank=True, null=True) start_at = models.DateTimeField() end_at = models.DateTimeField() discount_type = models.CharField(max_length=255) discount_amount = models.FloatField(blank=True, null=True) P/S: I am a maintainer - cant change method function, and cant change the way this URL take parameters from both URL and body -
How to make a form with choice fields which lead to different ModelForms based on the selected item
I have two models which are very similar.For each model I just defined a different ModelForm. I am going to make a form wizard with different steps, which in the first step choose which modelform I prefer, X or Y like: step one: forms.Form (choices: ModelForm X or ModelForm Y) step two: field_A in ModelForm X step three: field_B in ModelForm X step four: field_A in ModelForm Y step five: field_B in ModelForm Y step six: submit If X is selected skips form steps related to modelform Y(Four and Five) and submit them in database table X, and vice versa. So, I am asking if you have any experience in merging two modelforms and make choice/skip steps using a seprate form which is joined as the first step of my wizard form? -
Extracting data using ajax from a database in django and then display it in view
How should I extract data from a database using ajax in Django and display it in view in the form of charts. I wanna select items from dropdown options and then display those selected data in the webpage in the form of charts. Can anyone please guide me in this. My codes are: index.html: <div class="row"> <form class="form-row" action="{{ }}" method="post"> {% csrf_token %} <div class="form-group col-md-2"> <select class="form-control select2" > <option>Select Major Head</option> {% for major in majors %} <option value="{{ major.pk }}">{{ major.pk }}: {{ major.description } </option> {% endfor %} </select> </div> <div class="form-group col-md-2"> <input type="submit" value="Display"> </div> </form> </div> . . . <div class="card-body" > <div id="chart"> <embed type="image/svg+xml" src= {{ chart|safe }} /> </div> views.py: def home(request): majors = Major.objects.filter(percentages__isnull=False).distinct().order_by("pk") if request.method == 'POST': form = request.POST.get('be_nextyr_total') line_chart = pygal.Line(width=1500) line_chart.title = 'Budget Estimation' context = { "chart": line_chart.render_data_uri(), 'majors': majors } return render(request, "website/index.html" , context ) charts.js $('form').on('Display',function(e){ e.preventDefault(); $.ajax({ type : "POST", cache : false, url : $(this).attr('action'), data : $(this).serialize(), success : function(data) { // $(".printArea").empty().append(data).css('visibility','visible'); return data; } }); }); -
How create form Html in Django_rest_framework?
My Views is : class TweetsListApiView(generics.ListCreateAPIView): queryset = Tweet.objects.all() serializer_class = TweetListSerializer renderer_classes = [TemplateHTMLRenderer] template_name = 'components/form.html' Serializers: class TweetListSerializer(serializers.ModelSerializer): likes = serializers.SerializerMethodField('get_likes') class Meta: model = Tweet fields = ['id','content','likes'] def get_likes(self,request): return random.randint(0,9999) from.html {% load rest_framework %} <form method='Post'> {% csrf_token %} {% render_form serializer %} <button type="submit" class="btn btn-secondary">Add</button> </form> urls.py: path('tweets/',TweetsListApiView.as_view()), Is it possible to have from one viewclass class TweetsListApiView standart Rest Page and HTML page where I creating new Tweet. if no what the best way to create this html using serializer and Django REST -
Fashion MNIST dataset Deploy using Streamlit
please do anyone have link where I can learn proper way to deploy mnist fashion classification(the deployment that works perfectly) using streamlit library? Or flask or django? Your quick guide will be highly appreciated. -
Django create ManytoOne relation in one form
I am trying to develop a form where the user would be able to achieve this : Database So the form would have : a TextField for the name a TextField for the description a TextField for the addresses that would be entered by the User as a list According to you, what would be the most appropriate approach to do so? Thank you very much ! -
Django full_clean method and data security
I need to take raw JSON data and put it direct into a Django model by using the Mymodel.objects.create( ... ) method. If I then run full_clean() on the instance created, is it then secure in terms of potential SQL injection or any malicious data that could potentially be injected? The reason that I am not using a form is that the logic on the form is quite complex in that it dynamically builds a form so I need to post data in json format. I don't want to use the rest api as there is just one page where it has this complexity. -
I'm facing a problem in postgresql 13 installation on windows 10
Is there any solution ??enter image description here -
i want to show category wise product and paginate
I want to show category wise product and must be in paginate but its not working . i try to do this but I don't know why its not working. Here I have allProducts variable I tried to assign the paginate class but I think I am doing this in correct way maybe but its now working please give me solution for this Here is my Views.py def get(self, request): cart = request.session.get('cart') if not cart: request.session['cart'] = {} #products = None products = Product.objects.all() catsProduct = Product.objects.values("category") cats = {item["category"] for item in catsProduct} allProducts = [] for cat in cats: prods = Product.objects.filter(category=cat) allProducts.append(prods) allProducts = Product.get_all_products() paginator = Paginator(allProducts, 12) page_number = request.GET.get('page') allProducts = paginator.get_page(page_number) cats = Category.get_categories() brands = Brand.get_brands() sliders = Slider.objects.all() offers = Offer.objects.all() categoryID = request.GET.get('category') brandID = request.GET.get('brand') if categoryID: # products = Product.get_products_by_category(categoryID) products = products.filter(category__id=categoryID) # else: # products = Product.get_all_products() if brandID: # proucts = Product.get_brands_by_products(brandID) products = products.filter(brand__id=brandID) # else: # products = Product.get_all_products() # print(request.session['customer']) args = { 'products': products, 'cats': cats, 'brands': brands, 'sliders': sliders, 'offers': offers, 'allProducts':allProducts } return render(request, 'Home/index.html', args) -
How to get a detailed overview of some articles
import React from 'react'; import axios from 'axios'; import { Card } from 'antd'; class ArticleDetail extends React.Component { state = { article: {} } componentDidMount() { const articleID = this.props.match.params.articleID; axios.get(`http://127.0.0.1:8000/api/${articleID}`) .then(res => { this.setState({ article: res.data }); }) } render() { return ( <div> <Card title={this.state.article.title}> <p>{this.state.article.content}</p> </Card> </div> ) } } export default ArticleDetail; -
Django: Execute code only for `manage.py runserver`, not for `migrate`, `help` etc
We are using Django as backend for a website that provides various things, among others using a Neural Network using Tensorflow to answer to certain requests. For that, we created an AppConfig and added loading of this app config to the INSTALLED_APPS in Django's settings.py. This AppConfig then loads the Neural Network as soon as it is initialized: settings.py: INSTALLED_APPS = [ ... 'bert_app.apps.BertAppConfig', ] .../bert_apps/app.py: class BertAppConfig(AppConfig): name = 'bert_app' if 'bert_app.apps.BertAppConfig' in settings.INSTALLED_APPS: predictor = BertPredictor() #loads the ANN. Now while that works and does what it should, the ANN is now loaded for every single command run through manage.py. While we of course want it to be executed if you call manage.py runserver, we don't want it to be run for manage.py migrate, or manage.py help and all other commands. I am generally not sure if this is the proper way how to load an ANN for a Django-Backend in general, so does anybody have any tips how to do this properly? I can imagine that loading the model on startup is not quite best practice, and I am very open to suggestions on how to do that properly instead. However, there is also some other code … -
Postgres table join with a Django generic foreign key
I want to perform a table join in Postgres (9.5) where the name of the second table is a dynamic value taken from columns of the first table (a Django generic foreign key). The JOIN query below to django_content_type allows me to obtain the name of the table I want to join my_table to. SELECT CONCAT(ctype.app_label, '_', ctype.model) AS table_name FROM my_table JOIN django_content_type ctype ON my_table.source_type_id = ctype.id; What I now want to do is extend this query to join my_table with the corresponding source_table for that row. Something like the following: WITH source_table AS ( SELECT CONCAT(ctype.app_label, '_', ctype.model) AS table_name FROM my_table JOIN django_content_type ctype ON my_table.source_type_id = ctype.id LIMIT 1 ) SELECT * FROM my_table JOIN format('%I', source_table.table_name) source ON my_table.source_id = source.id LIMIT 1; Given that this is a generic foreign key relationship it is fine if it is only possible to do this for a single my_table row at a time, ensuring that my_table is only ever joined to a single additional table via the generic foreign key relationship. -
Django Vue.js How to Handle Database Transactions Properly
I am building a web application with Django and Vue.js where you enter some data on the Vue.js frontend and can then trigger a push into the database. Two separate objects will be created and two post-queries will be executed by axios. I want the database to rollback the first query should the second one fail. As far as I can tell, I need to execute both queries and commit the result to the database only if both succeeded, unfortunately I do not know how to handle this situation with the frameworks I am using. Can anyone provide any insight into how to go about doing this? -
Unable to send a PUT request to a Django REST API using Reactjs fetch() method
I've recently started learning Reactjs & made a simple Todo react appplication in order to learn it bit-by-bit, step-by-step.The data in this Todo react front-end is coming from a simple Todo Django REST API. But the problem is I want to change the state of "completed" to depict a task completed. Im trying to do this by sending a PUT request to the API using the unique "id" but getting some errors. Below is my approach : List.js import React from 'react' import Todo from './Todo' import Nav from './Nav' //Class based Component class List extends React.Component { constructor() { super() this.state = { todos: [], } this.handleChange = this.handleChange.bind(this) } fetchData() { fetch('http://localhost:8000/Todo-api/') .then(response => response.json()) .then((data) => { this.setState({ todos: data }); }); } componentDidMount() { this.fetchData(); } handleChange(id) { this.setState(prevState => { const updatedData = prevState.todos.map(todo => { if (todo.id === id) { todo.completed = !todo.completed } return todo }) return { todos: updatedData } }) fetch(`http://127.0.0.1:8000/Todo-api/${id}/?format=json/`, { method: 'PUT', headers: { 'Content-Type': 'application/json', 'Accept' : 'application/json', // Other possible headers }, body: JSON.stringify(this.state) }).then(function (response) { return response.json(); }).then(function (data) { console.log("Data is ok", data); }).catch(function (ex) { console.log("parsing failed", ex); }); } currentDate() { return … -
Inheritance in class based views
I am currently working on my first website and I'm working with class-based views because I've been told their inheritance is outstanding. Here's the code so you can make yourselves an idea of what I'm trying to do before I tell you the error I'm having. class TranslatorView(View): def translate_amino(self, codon): return self.amino_mapper.get(codon, "") def build_protein(self, phrase): protein = [] i = 0 while i < len(phrase): codon = phrase[i: i + 3] amino = self.translate_amino(codon) if amino: protein.append(amino) else: print(f"The codon {codon} is not in self.mapper_1") i += 3 return protein def error_1(self, request): amino_1= self.build_protein if len(amino_1) % 3: messages.error(request, "DNA chain must be divisible by 3") return redirect('/') Basically, what I'm trying to do is to inherit the function build_protein to the def error_1. Specifically, I want to inherit the phrase parameter in the error_1 def so that the message error appears. However, it appears it's not inheriting anything at all. -
Django 3.1+: has background_task become obsolete?
With Django 3.1 finally supporting async views, has the library "Django Background Task" (pip install django-background-tasks) become obsolete? I have been using it extensively for time consuming, overnight tasks. Do you advice to migrate them? Recommendations or pitfalls? -
How to stop loading the page after clicking on an href link in html?
so this code <a href="" onclick="alert('ITEM ADDED TO WATCHLIST')">Add to your watchlist</a> When i click on the link, an alert pops up from the upper side and when i clicks the OK button, it reloads the page .I want it, not to reload the page after clicking and just stays right where the page currently is. -
django Cast function always sets UTC timezone
When I use: annotate(new_datetime=Cast( TruncHour('old_datetime) + timedelta(days=1), output_field=DateTimeField() )) TruncHour return a datetime in my timezone and after Cast, new_datetime's value will be in my timezone but with UTC tzinfo. How can I set custom tzinfo for Cast function in this case? -
ValueError: Cannot assign must be an instance in Django
I am new to django and I'm trying to insert some data into the database through a form but I am getting an error while inserting the data. How can I solve this issue? I have these models which are connected together: models.py class Major(models.Model): major_cd = models.IntegerField(primary_key=True) description = models.CharField(max_length=100, blank=True, null=True) class Meta: managed = False db_table = 'major' class Percentages(models.Model): # major_cd = models.IntegerField(primary_key=True) major_cd = models.OneToOneField( Major, on_delete=models.CASCADE, primary_key=True, db_column='major_cd' ) perc = models.FloatField() class Meta: managed = False db_table = 'percentages' this is my from: per.html <form id="addPercentage" action=""> <div class="form-group row"> <div class="form-group col-md-2"> <input class="form-control" type="number" name="major_cd" placeholder="Major Code" required min=1000 max=9999> </div> <div class="form-group col-md-2"> <input class="form-control" type="number" name="perc" placeholder="Percentage" required> </div> </div> <div class="form-group col-md-2" style="padding-right: 2%;"> <button class="btn btn-info form-control" type="submit">ADD</button> </div> </form> script: $("form#addPercentage").submit(function() { var majorCodeInput = $('input[name="major_cd"]').val().trim(); var perc_Input = $('input[name="perc"]').val().trim(); if (majorCodeInput && perc_Input) { // Create Ajax Call $.ajax({ type: 'POST', url: '{% url "create-percentages" %}', enctype: 'multipart/form-data', data: { 'major_cd' : majorCodeInput, 'perc' : perc_Input, }, dataType: 'json', success: function (data) { if (data.Perc) { appendToPerTable(data.Perc); // Funcion to append data } } }); } else { alert("All fields must have a valid value."); … -
Failed to deploy my django project on heroku
I was going to deploy my django project on heroku, but I meet the error, I really have no idea how to do, please help, thank you a lot for your checking and answer in advance! -----> $ python manage.py collectstatic --noinput Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/__init__.py", line 345, in execute settings.INSTALLED_APPS File "/app/.heroku/python/lib/python3.7/site-packages/django/conf/__init__.py", line 83, in __getattr__ self._setup(name) File "/app/.heroku/python/lib/python3.7/site-packages/django/conf/__init__.py", line 70, in _setup self._wrapped = Settings(settings_module) File "/app/.heroku/python/lib/python3.7/site-packages/django/conf/__init__.py", line 177, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/app/.heroku/python/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/tmp/build_696b7f56_/lonelyisland/settings.py", line 24, in <module> SECRET_KEY = os.environ['SECRET_KEY'] File "/app/.heroku/python/lib/python3.7/os.py", line 681, in __getitem__ raise KeyError(key) from None KeyError: 'SECRET_KEY' ! Error while running '$ python manage.py collectstatic --noinput'. See traceback above for details. You may need to update application code to resolve this error. Or, you …