Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to write this expression in Django latest vers? [closed]
I try to realise simple template inheritance in Django, so I founded some expression, but it's not worked in the newest vers of Django! Please, anybody can help me? :) path(r'^(?P<project_id>\d+)/$', views.project_detail, name='project-detail') best regards -
How to pack model queryset in serializer into one field DRF?
For example i have a few models: class Parent(Model): api_key = CharField(max_length=250) class Child(Model): parent = ForeignKey(Parent, related_name='children') status = CharField(max_length=250) I wrote view based on ListAPIView, and serializer: class ChildSerializer(ModelSerializer): class Meta: fields = ['id'] I need to take all Children with parent by find Parent by api_key and return this as: { children:[ {'id':1}, {'id':2} ]} But i take this: [ {'id':1}, {'id':2} ] -
How and where we can host a multicontainer docker application?
I have whole configuration setup for django docker application . My applications is running using docker-compose command locally successfully as it should be . Now I want to deploy it so that anyone can access it . Also it is a multi container application having 24 containers . So, on which platform should I deploy my application. Any help will mean a lot. -
Django: Specifying Dynamic Database at Runtime
I'm attempting to trial setting up a system in Django whereby I specify the database connection to use at runtime. I feel I may need to go as low level as possible, but want to try and work within the idioms of Django where possible, perhaps stretching it as much as can be possible. I have kind of the following idea: db = {} db['ENGINE'] = 'django.db.backends.postgresql' db['OPTIONS'] = {'autocommit': True} db['NAME'] = my_model_db['database'] db['PASSWORD'] = my_model_db['password'] db['USER'] = my_model_db['user'] db['HOST'] = my_model_db['host'] logger.info("Connecting to database {db} on {host}".format(db=source_db['NAME'], host=source_db['HOST'])) connections.databases['my_model_dynamic_db'] = db DynamicObj.objects.using('my_model_dynamic_db').all() Has anyone achieved this? And how? -
Error: Cannot read property 'filter' of undefined, cannot get props
i am getting error while trying to filter out items in array. I suppose it is something connected with not right way to approach state or maybe i am not getting props. Main purpose is to filter trainings based on search value and show them in list. Source code: import React from 'react'; import axios from 'axios'; import Trainings from '../components/Training'; import CustomForm from '../components/Form'; class TrainingList extends React.Component { constructor() { super(); this.state = { search: '' }; } updateSearch(event) { this.setState({search: event.target.value.substr(0, 20)}) } state = { trainings: [] } componentDidMount() { axios.get('http://127.0.0.1:8000/api/') .then(res => { this.setState({ trainings: res.data }); console.log(res.data); }) } render() { let filteredTrainings = this.state.trainings.filter( (trainings) => { return trainings.title.indexOf(this.state. search) !== -1; } ); return ( <div> <Trainings data={filteredTrainings} /> <input type="text" value={this.state.search} onChange={this.updateSearch.bind(this)}/> </div> ) } } export default TrainingList; -
How to override the CharField max_length validation error message that will be responded when sending a post request via API?
I have a Customer model that has a mobile_phone field. When I send a post request via API to create a customer with a mobile phone value more than 15 I get that validation error message "Ensure this field has no more than 15 characters.". I don't like this message and I would like to override it. Is there a solution to do so? class Customer(models.Model): ... name = models.CharField(_('full name'), max_length=200) mobile_phone = models.CharField(_('mobile phone'), max_length=15, blank=True, null=True) ... I tried to do something like that def validate_value_lt_fifteen(value): if value > 15: raise ValidationError(_('Ensure that the mobile phone has no more than 15 characters.'), params={'value': value}) class Customer(models.Model): ... name = models.CharField(_('full name'), max_length=200) mobile_phone = models.CharField(_('mobile phone'), max_length=15, blank=True, null=True, validators=[validate_value_lt_fifteen]) ... But unfortunately, it does not solve the problem. On the contrary, it shows both error messages together. "Ensure this field has no more than 15 characters." and "Ensure that the mobile phone has no more than 15 characters." -
Django formsets and files
I have this web app, created with Django framework and I'm struggling with one particular issue. I would like to create formset with file attachment (Attachment is related to Document vie FK relationship), and I would like to provide url to mentioned file in frontend. model.py class Attachment(models.Model): name = models.CharField(max_length=100, verbose_name='name') file = models.FileField(upload_to='attachments', null=True, verbose_name='file') class Document(models.Model): attachment = models.ForeignKey( 'Attachment', null=True, on_delete=models.CASCADE) date = models.DateField(blank=True, null=True,) title = models.CharField(max_length=250, null=True, blank=False) def get_attachment_file(self): return self.attachment.file.url def get_attachment_filename(self): return str(self.attachment.file)[12:] form.py class DocumentForm(forms.ModelForm): class Meta: model = Contract fields = ('attachment', 'date', 'title', 'approved') DocumentFormset = modelformset_factory(Document, form=DocumentForm, extra=0) view.py def documents(request): ... some logic and filtering, get doc_id documents = Document.objects.filter(document=doc_id) formset = DocumentFormset(queryset=documents) return render(request, 'documents.html', {'formset': formset}) template: documents.html {% for form in formset %} <div class="form-group"> <label for="{{ form.attachment.id_for_label }}">Title</label> {{ form.attachment}} </div> {% endfor %} I have hard time to access file url in attachment object, in template engine I cant call get_attachment_file() function, form.attachment.file.url is empty. Is there a way to get file url from attachment object? Thank you. -
Django and DataBase
How can I read a filtered database from a website that it can be edited? This means that there is a database that is filtered by the specified criteria, creating a new table on the site. The problem is that I don't know how to read this new table in order to continue using it. -
Python Django set DJANGO_SETTINGS_MODULE when migrating source code
Task: Set up a new running environment by being provided python/Django source code and some additional details. Problem: Cannot get Django-admin to validate due to missing/incorrect settings configuration "django.core.exceptions.ImproperlyConfigured Requested setting USE_I18N, but settings are not configured. ..... " You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings Env Details: Ubuntu OS, Python 2.7, Django 1.7, PostgreSQL (also Supervisor + gunicorn) Running a venv located **/home/dave/python-env/vas/**bin/activate Python sys.path /usr/lib/python2.7/* (multiple defined) /home/dave/python-env/vas/python2.7/site-packages So tried several methods (including #export DJANGO_SETTINGS_MODULE=project-name.settings....) with little success. How can one set the DJANGO_SETTINGS_MODULE variable? os.environ.setdefault() is set in wsgi (I know this is the next step) BUT this value is also set in /manage.py ...? os.environ.setdefault("DJANGO_SETTINGS_MODULE", project_name.settings) The directory /var/www/app/ (where the python source code is located) has several files, one of them is the project_name where the settings.py sits.... I am new to python/django... Trying to get django-admin.py validate to validate. -
Django model file example is a bit weird to me
In the documentation I understand the principle of this example, but I dont get how it works technically (see my comments in the code): >>> import os >>> from django.conf import settings >>> initial_path = car.photo.path >>> car.photo.name = 'cars/chevy_ii.jpg' >>> new_path = settings.MEDIA_ROOT + car.photo.name >>> # Move the file on the filesystem: it's using strings: initial_path and new_path: >>> os.rename(initial_path, new_path) >>> # the following "save()" seems to "guess" that it has been renamed... but how?? >>> car.save() >>> car.photo.path '/media/cars/chevy_ii.jpg' >>> car.photo.path == new_path True -
Django 2.1.5 SQL-Server how to save to Database with data from different table
I'm trying to save data from a diffenent table, but it won't work. I have assigned the values to the fields and if i print out the fields they show me the right values, but wont save in my table. my models: class test(models.Model): id= models.IntegerField(db_column='id', primary_key=True) weight= models.IntegerField(db_column='weight', blank=True, null=True) count= models.IntegerField(db_column='count', blank=True, null=True) class flow(models.Model): id= models.IntegerField(db_column='id', primary_key=True) weightkg= models.IntegerField(db_column='weightkg', blank=True, null=True) counter= models.IntegerField(db_column='counter', blank=True, null=True) I'm using Modelform my view: def flow_view(request): form = flowForm() if request.method == 'POST': form = flowForm(request.POST) if form.is_valid(): entnahme = test.objects.last() if entnahme.weight == 2000: abschaltung = test.objects.get(pk=1) else: abschaltung = test.objects.get(pk=2) weightkg=request.POST.get('weight') counter = abschaltung.count form.weightkg = weightkg form.counter= counter form.save() print(form.weightkg) print(form.counter) return render(request, "seiten/test.html") I get the right Data, and everything seems to work. Only the data wont save. -
Deploying django app in heroku and aws amazaon
I'am going to deploy my first Django app, i want to use Heroku as a host and AWS for database and statics storage. Can you please how it can be done? -
How to integrate an ERP to a Django website?
I have a Django website which it contains a system that users can add their data and create machine learning models, make predictions, etc. I have to integrate an ERP which it's name is LOGO to my website for users can pull their data directly from that ERP software, not manually. I did a lot of research, but I couldn't find any descriptive document, tutorial, paper, etc. I'm pretty new about it. How should my road map be? I would be glad if you can share your suggestions or useful links and documents on this subject. Thank you. -
422 http error when trying to upload a file from request in django
I'm working on a django project.i want to upload a video through 'tuspy' package. but i got 422 error. here is part of my view.py : my_client = client.TusClient('https://napi.arvancloud.com/vod/2.0/channels/' + channelId + '/files', headers={'Authorization': 'xxxxxxxxxxxxx', 'Accept-Language': 'en'}) with request.FILES.get('video-file') as f: uploader = my_client.uploader(f.temporary_file_path(), chunk_size=200) result = uploader.upload() print(result) return -
No Such File or Directory when Deploying Django to Elastic Beanstalk with Immutable Deployment Policy
I have already deployed my Django project to EB on AWS and it is working fine. I tried deploying it now with an Immutable Deployment Policy and I am getting this error: Command failed on instance. Return code: 2 Output: python: can't open file '/opt/python/current/app/manage.py': [Errno pt/python/current/app/manage.py': [Errno 2] No such file or directory. And that happens during the command: source /opt/python/current/env && python /opt/python/current/app/manage.py migrate For some reason, I can't include that command on the first deployment. Does anyone know how to use the immutable deployment method with Django? -
Showing video feed in on two different views in django?
I'm trying to build a web application using django backend which displays the live feed from IP Cameras. Below is the code for the getting the feed from the camera ip. class IPWebCam(object): def __init__(self,camera_ip): self.url = "rtsp://"+camera_ip+ ":5060 "+"/live" def __del__(self): cv2.destroyAllWindows() def get_frame(self): imgResp = urllib.request.urlopen(self.url,context=context) imgNp = np.array(bytearray(imgResp.read()), dtype=np.uint8) img = cv2.imdecode(imgNp, -1) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) resize = cv2.resize(img, (270,250), interpolation=cv2.INTER_LINEAR) ret, jpeg = cv2.imencode('.jpg', resize) return jpeg.tobytes() I also have the code for the views below: def gen(camera): while True: frame = camera.get_frame() yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n') def video(request,camera_ip): return StreamingHttpResponse(gen(IPWebCam(camera_ip)),content_type='multipart/x-mixed-replace; boundary=frame') Using these two functions i'm able to display the feed in one of the pages in the application.What i would like to do is to trigger the live feed on one page and make it run in the background. Now, when i'm on a different page i want to show the same feed when it loads up, without actually running the function again. My final goal is to run an object detection algorithm in one page(trigger it using button press or something) and display it on the page initially. But, there also an other page to where is have … -
How to automate recurring dates so as to automatically add one month after current date?[Python-Django]
Need help in automating recurring dates so as to automatically add one month after the current date? Raw Example: joining date: 2020/6/1 due_date:2020/7/1 Q1-> How to change the month of due date every month automatically Q2-> How to set a current due amount by calculating the due + price - paid =? My models.py: class Property(models.Model): property_type = ( ('Room', "Room"), ('PG', "PG"), ('Co-Living', "Co-Living"), ('1BHK', "1BHK"), ('2BHK', "2BHK"), ('3BHK', "3BHK"), ) bath_type = ( ('Attached Bath', "Attached-Bath"), ('Common Bath', "Common-Bath") ) furnish_status = ( ('Yes', "Yes"), ('No', "No") ) payment_category = ( ('Company', "Company"), ('Individual', "Individual") ) due_status = ( ('Due', "Due"), ('Paid', "Paid") ) name = models.CharField(max_length=50) room_id = models.CharField(max_length=50) bed_id = models.CharField(max_length=50, unique=True) building_category = models.ForeignKey('Category', null=True, on_delete=models.SET_NULL) property_type = models.CharField(choices=property_type, max_length=25) bath_type = models.CharField(choices=bath_type, max_length=25) furnish_status = models.CharField(choices=furnish_status, max_length=25) brand = models.ForeignKey('Brand', on_delete=models.SET_NULL, null=True) area = models.DecimalField(decimal_places=2, max_digits=8) beds_number = models.PositiveIntegerField() floor_number = models.PositiveIntegerField() image = models.ImageField(upload_to='property/', null=True) location = models.CharField(max_length=50) created_at = models.DateField(auto_now=True) price = models.PositiveIntegerField() advance = models.PositiveIntegerField() paid = models.PositiveIntegerField() due = models.PositiveIntegerField() due_status = models.CharField(choices=due_status, max_length=25) joined_date = models.DateField() due_date = models.DateField() tenant_name = models.CharField(max_length=50) tenant_number = models.BigIntegerField(unique=True) payment_category = models.CharField(choices=payment_category, max_length=25) slug = models.SlugField(blank=True, null=True) def save(self, *args, **kwargs): if not … -
Real time application outside the prevalent "Chat" server using django channels [closed]
I have a project that requires the use of Django channels. I have gone through its documentation and the prevailing "chat server" buzz, but yet to be fully equipped with the required knowledge. My project requires that some data will be fetched from some cloud service, stored in the database and displayed to users in real-time. Any suggestions and maybe working example? -
How to return array of urls in django
There are some files in a directory, and I want to return url of every file in the directory. How can i do that in django ? dir_id_1 -->img1.png -->img2.png -->img3.png dir_id_2 -->img4.png When user send a get request to correspond endpoint with the directory name, It should return urls of images. Something like this. [10.10.10.10:8000/.../dir_id_1/img1.png, 10.10.10.10:8000/.../dir_id_1/img2.png, 10.10.10.10:8000/.../dir_id_1/img2.png] PS: I am keeping these images in filesystem, not in db. -
Sending a file to a Django REST endpoint that has a FileField
I am sending data to an endpoint that requires a file in one of it's values. The data that I am sending : The document's value is a file. But when I check the payload of the PATCH request in the network tab, the document is empty : I have verified that I am sending the right data, but the payload doesn't seem to have it. -
how to use multiple select with image in django and save values in database?
I am trying to create a page where user can select his interests(multiple) with images and key value will be stored in database. so i can use these value to show posts accordingly to user based on his choices. But i am unable to add images in checkboxes and storing its value in database. Any suggestion and fixing will be helpful for me. thank you. views.py def interestview(request): if request.method == 'POST': int_form = interestform(data=request.POST) if int_form.is_valid: int_form.save() return redirect('photo_home.html') else: HttpResponse('error') int_form = interestform() return render(request, 'interest_landing_page.html', {'int_form' : int_form}) models.py class interests(models.Model): int_choices = ( ('music',"Music"), ('photography',"Photography"), ('acting',"Acting"), ('art',"Acting"), ('travel',"Travel"), ('sports',"Sports"), ('humanity',"Humanity"), ('dance',"Dance"), ) user = models.ForeignKey(User, on_delete=models.CASCADE ) comm = MultiSelectField(max_length=255, choices=int_choices) template.html {% csrf_token %} {% for value, text in int_form.int_fields.field.choices %} <div class="ui slider checkbox"> <input id="id_providers_{{ forloop.counter0 }}" name="{{ int_form.int_fields.name }}" type="checkbox" value="{{ value }}"{% if value in int_fields %} checked="checked"{% endif %}> <label>{{ text }}</label> </div> {% endfor %} -
Getting a list of field names but unable to access the values from an object
I am having one issues One of my function return field names of an model For example my models.py class Branch( Model): branch_name = models.CharField(max_length=255, blank=True) branch_area = models.ForeignKey( Location, on_delete=models.SET_NULL, blank=True, null=True) manager = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True, ) in my views.py def sample_function(request, id=None): query = get_object_or_404(Branch, id=id) if object_id else None secured_fields = secured_fields( Branch ) # This will return the secured fields of that model in the list # form example : secured_fields = ['manager'] for f in secured_fields: print(query.f) It showing an error 'Branch' object has no attribute 'f' -
Where Does Django Test Store Its' files?
Where Does Django Test Store Its' files? I have the following code: def setUp(self): ... parser_file = io.StringIO(lenta_parser_string) parser_file = InMemoryUploadedFile( parser_file, None, 'parser.py', 'text/x-python', len(parser_file.getvalue()), None ) parser = Parser.objects.create(file=parser_file) ... Once tests are done, database is destroyed as stated in django docs. But what happens to In Memory Files? If I run tests multiple times, it says that there is no file named parser_GHDds3.py. Django add symbols to InMemoryUploadedFile, because there is a file already, but how do I get rid of these files. I thought they removed after test are done -
File Upload handling in Django rest framework
I am trying to add a filefield in my django models but I am not sure how to handle the files coming from React Front-end. Models.py class Product(models.Model): name = models.CharField(max_length=500, default=0) short_code = models.CharField(max_length=500, default=0,unique=True) document = models.FileField(upload_to='products/', null=True, blank=True) owner = models.ForeignKey(User, on_delete=models.CASCADE) Serializer.py class ProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = "__all__" When the File is uploaded from Frontend it gives the following error in Network {"detail":"Unsupported media type "multipart/form-data boundary=967753268136369" in request."} I have gone through the documentation of DRF and I am sure I need to implement MultiParser in it but I am not sure how. Also Is there a better way to handle "File Handling"? I am using Ant Design File Upload in the application -
How to override/customize ALL server errors in Django and Django rest framework
I have a ViewSet: ... from handlers import specific_exception_handler... ... class SomeViewSet(GenericViewSet): """ Some custom generic viewset """ queryset = SomeModel.objects.all() serializer_class = SomeSerializer parser_classes = (ParserClassThatReadSpecificXML,) renderer_classes = (RendererClassThatConvertResponseIntoSpecificXML,) def get_exception_handler(self): return specific_exception_handler_function_that_return_specific_xml_format_error @action(methods=['post'], detail=False, url_path='some_url', url_name='some_url') def register(self, request, format=None): some_variable = request.data.get('some_value', None) if not some_variable: raise ValueError return Response(data=some_variable, content_type="text/xml; charset=shift_jis") I have a render: ... import xmltodict class RendererClassThatConvertResponseIntoSpecificXML(BaseRenderer): media_type = 'text/xml' format = 'txt' charset = 'shift_jis' def render(self, data, media_type=None, renderer_context=None): # return data as non utf-8 xml string return xmltodict.unparse(data).encode("shift_jis") I have a custom error handler: ... from rest_framework.views import exception_handler def specific_exception_handler_function_that_return_specific_xml_format_error(exc, context): response = exception_handler(exc, context) if response is not None: status_code = response.status_code else: status_code = status.HTTP_500_INTERNAL_SERVER_ERROR specific_data_that_will_be_converted_into_xml_by_render = {'ERROR_STATUS': status_code} headers = {'Retry-After': '300'} return Response(data, content_type='text/xml; charset=shift_jis', status=status_code, headers=headers) Problem: If View's raise ValueError will be raised I get my custom XML formatted error message. But if some exception will be happened inside render, there is appears Django's standard 500 Server Error message If I will try to access outside View , there is appears Django's standard 404 Server Error message again I want to show my custom XML error anytime. How can I do it?