Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Lightsail - attempt to write a readonly database
for a few days now I have been trying to deploy my Djago app on AWS Lightsail, and it's just one problem after another. The frustration levels are over the roof. This time, when I try to login/register, I am getting this error: Attempt to write a readonly database I have been googling solutions for quite some time and have tried setting different permissions, even giving away all permissions which might be huge security risk, however it still doesn't work. Could anyone help me. Thank you -
Django Rest Framework: how to access single API elements in URL?
I want to access every API element by URL like this "/api/v1/element_id" I have explicitly defined the pk in serializers serializers.py class TweetSerializer(serializers.ModelSerializer): tweet_id = serializers.IntegerField() class Meta: fields = ('tweet_id', 'author', 'text', 'created_at', 'retweet_count', 'favourite_count',) model = Tweet But it does not work. I get Not found error models.py class Tweet(models.Model): #tweet_id = models.ForeignKey(User, on_delete=models.CASCADE) tweet_id = models.IntegerField() created_at = models.CharField(max_length=100) text = models.TextField() author = models.CharField(max_length=100) retweet_count = models.IntegerField() favourite_count = models.IntegerField() def __str__(self): return str(self.tweet_id) views.py class TweetList(generics.ListCreateAPIView): queryset = Tweet.objects.all() serializer_class = TweetSerializer class TweetDetail(generics.RetrieveUpdateDestroyAPIView): queryset = Tweet.objects.all() serializer_class = TweetSerializer urls.py urlpatterns = [ path('<int:pk>/', TweetDetail.as_view()), path('', TweetList.as_view()), ] Listing all tweets works fine, /api/v1/, but single tweet is not returned. I have tried to set a ForeignKey in the models but then I get an error column tweet_id_id not found. -
Django FileField and Media config
I'm completely stuck with this, I have a simple Model with a File-Field: class EmailTemplate(models.Model): template_name = models.CharField(max_length=100, primary_key=True, verbose_name='Template Name') template_file = models.FileField(upload_to=f'documents/non_voice/email_templates', verbose_name='File', validators=[validate_txt_extension]) def __str__(self): return self.template_name The User is able to upload a file through a form and should be able to download them as reference later on. Upload works like a charm but when I present the file in a django_table - Table it links to it's relative path and download won't work since it tries to serve only the partial file path. Shouldn't Django automatically pre-pend my Media Dir to build the correct path?? (I can't provide a full path as "upload_to" only accepts relative ones!) Also the standard upload widget is showing it's current path as a link which is also not working when you click on it, so I would assume the issue has to be somewhere else (best guess is my media settings...) My Media Settings look like this: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates') STATIC_DIR = os.path.join(BASE_DIR, 'static') MEDIA_DIR = os.path.join(BASE_DIR, 'media') LOG_DIR = os.path.join(BASE_DIR, 'logs') # MEDIA MEDIA_ROOT = MEDIA_DIR MEDIA_URL = '/media/' Any ideas? -
Tus JS Client file upload without CSRF in Django
I want to upload a large video file using tus-js-client to my django media directory. I am encountering a csrf token 403 error. How can I the crsf token to the tus POST and PUT/PATCH requests. See my code below let video_file = $('#id_video_file')[0].files[0]; let tus_uploader = new tus.Upload(video_file, { endpoint: 'http://127.0.0.1:8000/media/myfolder/', retryDelays: [0, 1000, 3000, 5000, 10000], metadata:{ filename: video_file.name, filetype: video_file.type, }, uploadSize: video_file.size, onError: function (error) { }, onProgress: function (bytesUploaded, bytesTotal) { let percentage = (bytesUploaded/bytesTotal * 100).toFixed(2); console.log(percentage); }, onSuccess: function () { console.log("Download %s from %s", tus_uploader.file.name, tus_uploader.url) } }); tus_uploader.start(); -
How do I use django formset_factories?
I am trying to work on a django-based project/website that logs who took out our dogs last. I am very new to django so please bear with lack of knowledge in the field. I currently have my project set up so that I have models based on users/family members, the families' dogs, posts (logs of when and who took out the dogs), and actions, which is a child class that uses the dog and post models as foreign keys to see if the dogs peed and or pooped when they were taken out. The part that I am stuck on is trying to figure out how I create the post form. Since we have two dogs I need the form/post page to display a set of check boxes (for peeing and pooping actions) for each dog model that exists. While I can successfully display one action set, I run into the difficulty of trying to display the correct number of action sets and also to post the set of actions and the post itself. I have been trying to work with the formset_factory function but I am confused as to how I get it to function properly. Can anyone help? … -
temporarily adding watermark image/copyright text while displaying image in django template
I am creating a stock photo site. I need to add watermark temporarily while displaying in django template so that user shouldn't be able to download original photo without purchasing. I've tried django-watermark but got error while migrating. python 3.8+ and django 3.1.3+ So far I've overlapped images using this code, water_mark_image = Image.open(settings.MEDIA_ROOT+'/water.png') water_mark_image = wat.resize((int(im.width/2), int((im.width/2)*(h/w)))) Original_image.paste(wat, (int((im.width-wat.width)/2), int((im.height-wat.height)/1)), mask=wat) but while downloading image comes along with watermark. I dont want to save duplicate image. Please suggest me a way to add watermark temporarily while displaying in detail. -
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 …