Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How should Python virtual environment be handled on Azure?
Background I want to set up an Azure Web Service with Django. On my local machine that app runs error-free in a virtual environment. (The virtual environment name, deploydjango, is indicated leftmost in my prompt - after activating using source deploydjango/bin/activate in repo root folder - before starting the Django server). The virtual environment is "documented" by pip freeze > requirements.txt. (As I am aware of this answer I git push'ed from my local machine to my GitHub repository with the virtual environment. activated. Question How come that Azure creates another virtual environment, antenv? Would it be right to edit the appropriate line of the Oryx manifest (Azure project root /oryx-manifest.toml) from virtualEnvName="antenv" to virtualEnvName="deploydjango" Or put in other words: Do I need to deploy my virtual environment? -
return elements from OnetoOne and ForeignKey Query using Django
I have the three tables below and i am trying to write a query(or multiple queries) that would return all the address and events fields from their respective tables. class Activity(models.Model): name = models.CharField(max_length=50) description = models.TextField(max_length=500) class Event(models.Model): date = models.DateField() start_time = models.TimeField() duration = models.PositiveSmallIntegerField() activity = models.ForeignKey(Activity, on_delete=models.CASCADE, related_name="activities") class Address(models.Model): event = models.OneToOneField(Event, on_delete=models.CASCADE, primary_key=True) address = models.CharField(max_length=100) This is what i tried but it does not seem to be appropriate, it crashes! adds = Address.objects.all() for ad in adds: for events in ad.event.all(): print("events", events) is there a better way to do it? how can i achieve it? Thanks -
React Axios call in componentDidMount()
I am trying to build a 'DataLoader' component that calls a Django Rest API via Axios and for testing purposes shows the results of the API call in an . The query terms are being generated in a parent component and passed via props. Initially, the API is called with the query terms manufacturer & model_name both being blank. This part works, after the initial render I can see a that shows all the expected results. When the parent component passes new query terms via props to the 'DataLoader' component, the render() function is being executed, as I can see the <ul><li>Data {this.props.selectedManufacturer}</li><li>Data {this.props.selectedModels}</li></ul> part being executed and re-rendered correctly. However, it seems that the componentDidMount() function with the Axios part is not being called again. How do I get React to call Axios again once new props have been passed from the parent component to the 'DataLoader' component? import React from 'react'; import axios from 'axios'; import { getDefaultNormalizer } from '@testing-library/react'; class DataLoader extends React.Component { state = { cars: [] } componentDidMount(props) { axios.get(`http://127.0.0.1:8000/firstdraft/api/data?manufacturer=${this.props.selectedManufacturer}&model_name=${this.props.selectedModels}`) .then(res => { const cars = res.data; this.setState({ cars }); console.log(this.state.cars) } ) } render(){ return( <> <h1>Top Selling Cars</h1> <ul>{this.state.cars.map(car => <li> … -
Django - Creating a checklist form
I've been working on a little side project for a while and I've gone into a deep hole. I'm hoping for some guidance from people who have been in the Django world longer than I. Currently, I'm working on a simple maintenance form, where we have a Model Maintenance_Items (which holds just a ID, Name and Description). I have a second model, which CheckList model, that use a ForeignKey from Maintenance_Items and has a BooleanField to mark an item as compliance that day. Note, I capture CreatedDate under my CommonInfo fields. class Maintenance_Item(CommonInfo): id = models.AutoField(primary_key=True) name = models.CharField(max_length=100, unique=True) name_description = models.CharField(max_length=255) class MaintenanceCheckList(CommonInfo): id = models.AutoField(primary_key=True) item = models.ForeignKey(Maintenance_Item, on_delete=models.CASCADE) is_compliant = models.BooleanField I'm looking for a way to generate a form, and I was thinking Formsets would be the answer, where a Form is generated for each Item in Maintenance Item with the Item Name prefilled. Where a user can quickly mark the item as compliance. But, i'm stuck where to begin and have been reading over all the formsets documentation. I'm hoping someone could provide some guidance. -
insert additional attributes during put-as-create requests (generic)
So I have a mixin like this. class PutAsCreateMixin: """ The following mixin class may be used in order to support PUT-as-create behavior for incoming requests. """ def update(self, request, *args, **kwargs): partial = kwargs.pop('partial', False) instance = self.get_object_or_none() serializer = self.get_serializer(instance, data=request.data, partial=partial) serializer.is_valid(raise_exception=True) if instance is None: if not hasattr(self, 'lookup_fields'): lookup_url_kwarg = self.lookup_url_kwarg or self.lookup_field lookup_value = self.kwargs[lookup_url_kwarg] extra_kwargs = {self.lookup_field: lookup_value} else: # add kwargs for additional fields extra_kwargs = {field: self.kwargs[field] for field in self.lookup_fields if self.kwargs[field]} serializer.save(**extra_kwargs) return Response(serializer.data, status=status.HTTP_201_CREATED) self.perform_update(serializer) return Response(serializer.data) def partial_update(self, request, *args, **kwargs): kwargs['partial'] = True return self.update(request, *args, **kwargs) def get_object_or_none(self): try: return self.get_object() except Http404: if self.request.method == 'PUT': # For PUT-as-create operation, we need to ensure that we have # relevant permissions, as if this was a POST request. This # will either raise a PermissionDenied exception, or simply # return None. self.check_permissions(clone_request(self.request, 'POST')) else: # PATCH requests where the object does not exist should still # return a 404 response. raise I subclass this mixin to do put-as-create operations like this. class OverwritePutDestroyView(PutAsCreateMixin, MultipleFieldMixin, PutDeleteAPIView): queryset = Overwrite.objects.all() permission_classes = [IsAuthenticated, ManageRoles, EditOverwrites] serializer_class = OverwriteSerializer lookup_fields = ['channel_id', 'role_id'] path('channels/<int:channel_id>/permissions/<int:role_id>/', views.OverwritePutDestroyView.as_view(), name='overwrites-put-destroy'), However, I … -
DatePicker is not showing in the form
I am building a BlogApp and I am stuck on an Problem. I was building a DatePicker in the form in template. BUT nothing is displaying. What i am trying to do I am trying to build a DateTimePicker in template using Jquery. The Problem DateTimePicker is not displaying in the form in template. I have also put widgets in forms fields but nothing is worked. forms.py class PostForm(forms.ModelForm): date_added = forms.DateTimeField(initial=timezone.now) class Meta: fields = ('date_added') widgets = {'date_added':forms.TextInput(attrs={'class':'datepicker'})} base.html <script type="text/javascript" src="scripts/bootstrap.min.js"></script> <script type="text/javascript" src="scripts/moment-2.4.0.js"></script> <script type="text/javascript" src="scripts/bootstrap-datetimepicker.js"> new_blog_post.html <form method="post" enctype="multipart/form-data" id="formUpload"> {% csrf_token %} {{ form|crispy }} <script> $(function() { $( ".datepicker" ).datepicker({ changeMonth: true, changeYear: true, yearRange: "1900:2012", }); }); </script> <button type="submit">Save Changes</button> </form> I don't know what am i doing wrong. Any help would be appreciated. Thank You in Advance. -
Passing parameters between classes Django
I have a viewset file, which get data from serializer serializer = MeterListsSerializer(data=request.query_params) start, end = serializer.data['start_date'], serializer.data['end_date'] Values start and end is datetime values I need to use them in function in other class to compare values_dict = [] values = [self.readings[i].values for i in range(len(self.readings))] dates = [self.readings[i].period for i in range(len(self.readings))] for i in range(len(values)): if dates[i] > 'end' and dates[i] < 'start': values_dict.append({ 'date': dates[i], 'value': values[i] } ) values start and end should be instead 'start' and 'end' How can I do this? -
Specify a database name for a django model
Here is my problem : i have a django class : Fiber in a Data app. So it gives me a : Data_fiber table in postgres. using uppercase is really painful in psql and gives me a lot of error. Is there a way to define the table in my Fiber model ? Regards -
Convert x-y coordinates using SRID=25832 and send to database with SRID=4362
I am struggling converting x-y coordinates to the correct longitude and latitude using the correct SRID in my django app. Please bear with me: I have a custom coordinate system and an underlying layer which is using SRID=25832. Let's say I have the realistic but only dummy point x=760168.4573802829 and y=183915.7423387466 which translates to a shapely.Point like POINT(760168.4573802829, 183915.7423387466). Using inter/extra polation of scipy I am transforming this to longitude and latitude and get the values 8.116117939245648 51.58507982440602. I transform somewhat like this: def point_xy_to_lonlat(point_xy_x, point_xy_y, ref_0_xy, ref_1_xy, ref_0_lonlat, ref_1_lonlat): """x-y to lon-lat based on reference points. interp_lon = interpolate.interp1d( [ref_0_xy.x, ref_1_xy.x], [ref_0_lonlat.x, ref_1_lonlat.x], fill_value="extrapolate", ) interp_lat = interpolate.interp1d( [ref_0_xy.y, ref_1_xy.y], [ref_0_lonlat.y, ref_1_lonlat.y], fill_value="extrapolate", ) lon = interp_lon(point_xy_x) lat = interp_lat(point_xy_y) lonlat = Point(lon, lat) lonlat result That gives me valid longitude and latitude. Now I want to send those values to my database using the correct projection. I am sending these values, specifying the SRID. My database defaults to SRID 4326 and automatically converts the points sent with a different SRID to SRID 4326 So when I am sending my coordinates: data = { coordinate = "SRID:25832; POINT(8.116117939245648 51.58507982440602)" } requests.request("post", data=data, url=url) The coordinates end in the water. … -
Why password is not changing?
If I enter incorrect old password, I get message. But if new_pass1 != new_pass2, nothing changes. And if I enter all right, nothing changes too. views.py def change_password(request): if request.method == 'POST': form = ChangePassword(request.user, request.POST) if form.is_valid(): user = form.save() update_session_auth_hash(request, user) messages.success(request, 'Your password was successfully updated!') return redirect('password_change_done') else: messages.error(request, 'Please correct the error below.') else: form = ChangePassword(request.user) return render(request, 'account/password_change.html', {'form': form}) forms.py class ChangePassword(PasswordChangeForm): old_password = forms.CharField(label='', widget=forms.PasswordInput( attrs={'class': 'form-control input_pass', 'placeholder': 'Старый пароль'})) new_password1 = forms.CharField(label='', widget=forms.PasswordInput( attrs={'class': 'form-control input_pass', 'placeholder': 'Новый пароль'})) new_password2 = forms.CharField(label='', widget=forms.PasswordInput( attrs={'class': 'form-control input_pass', 'placeholder': 'Новый пароль'})) password_change.html <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit" name="button" class="btn login_btn">Сменить</button> </form> -
Unable to deploy django project on windows server using mod_wsgi and wamp
Instead of my django project running and showing my landing page. I'm only able to view my project files on localhost. The project runs fine on development when using python manage.py runserver but does not work with mod_wsgi and wamp. in my wamp's apache httpd.conf file, I've added: ServerName localhost:8000 Listen localhost:8000 Listen [::0]:80 . . Include "conf/extra/httpd-vhosts.conf" . . # Django Project LoadFile "c:/python3.6/python36.dll" LoadModule wsgi_module "c:/python3.6/lib/site-packages/mod_wsgi/server/mod_wsgi.cp36-win_amd64.pyd" WSGIPythonHome "c:/python3.6" WSGIPythonPath "C:/irfan/metatrader_api/mt5" in my httpd-vhost.conf, I have : # WSGIPythonPath "C:/irfan/metatrader_api/mt5" <VirtualHost *:8000> WSGIPassAuthorization On ErrorLog "logs/mt5.error.log" CustomLog "logs/mt5.access.log" combined DocumentRoot "c:/irfan/metatrader_api/mt5/mt5" WSGIScriptAlias / "C:\irfan\metatrader_api\mt5\mt5\wsgi_windows.py" <Directory "c:\irfan\metatrader_api\mt5\mt5"> <Files wsgi_windows.py> Require all granted </Files> </Directory> </VirtualHost> WSGIApplicationGroup %{GLOBAL} in wsgi_windows.py, I have activate_this = "C:/irfan/irfan/Scripts/activate_this.py" # execfile(activate_this, dict(__file__=activate_this)) exec(open(activate_this).read(),dict(__file__=activate_this)) import os import sys import site # Add the site-packages of the chosen virtualenv to work with site.addsitedir("C:/irfan/irfan/Lib/site-packages")[![enter image description here][1]][1] # Add the app's directory to the PYTHONPATH sys.path.append('C:/irfan/metatrader_api/mt5') sys.path.append('C:/irfan/metatrader_api/mt5/mt5') os.environ['DJANGO_SETTINGS_MODULE'] = 'mt5.settings' os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mt5.settings") from django.core.wsgi import get_wsgi_application application = get_wsgi_application() -
STATICFILES DJANGO
I have a problem with Django, managing static files.. I know there are already similar questions here and I have gone through them all and tried them,but an error still pops up. here is my code STATICFILES_DIRS = [ BASE_DIR / "static", ] and the following message pops up BASE_DIR/'static', TypeError: unsupported operand type(s) for /: 'str' and 'str' -
Parsing large JSON in Javascript (larger 4 MB)
I want to send json data from my Django views.py into my HTML template. The data is a python-dict object which I converted via json.dumps() to json. Then I move it to the context variable for the template. On client side I use JSON.parse() and it works as expected except for one object, which is larger than 4 MB of string. I found on https://www.ibm.com/support/knowledgecenter/SS9H2Y_7.6.0/com.ibm.dp.doc/json_parserlimits.html that there might be parser limits, but I'm not sure how accurate this source fits to my problem. The debugger (Chromium) shows me that the parser is cutting the string, which leads to the error. The error is: VM37378:1 Uncaught SyntaxError: Unexpected token in JSON at position 9117 but looking at this position show the that there is a line break in the parser, but no actual "error". Checking the data on https://jsoneditoronline.org shows me that the string is valid json in every step from json.dumps() to JSON.parse() Is there any way I can check if the string is too long for JSON.parse()? Or is there any useful library to handle this? Thanks in advance -
how to determine if request object was initiated from web-browser or REST API call?
Our website has django template webpages and API calls that interact with it. Some of the inner business logic functions have access to the request object and I need an effective way to determine whether it was an API call that initiated it, or a django template as this will affect the data I send back. Any ideas? -
Storing redirect response in Django
I have a simple python function inside my Django app's views.py: def some_function(requests): return redirect('some_url') The redirect returns some useful information that I want to use later in the other function. Is there any way I can store the response URL given by the redirect in a variable so that I can use it later in my app. Thanks -
I will not map proper url in html page
when I hit this url <a href="/cart/pk">Cart<span>{{request.session.cart|length}}</span></a> I got error "The current path, cart/, didn't match any of these." so please tell how map proper url my url.py file: path('cart/<int:pk>',views.cartitem,name='cart'), My cartitem.py file: def cartitem(request,pk): cart=request.session.get('cart') if cart is None: cart=[] for c in cart: tshirt_id=c.get('tshirt') product_id=c.get('product') product = get_object_or_404(Product,pk=pk) tshirt=Tshirt.objects.get(pk=pk) c['size']= Sizevariant.objects.get(tshirt=tshirt_id, size=c['size']) c['tshirt']=tshirt c['product']=product return render(request,"cart.html",{'cart':cart,'product':product,'tshirt':tshirt}) -
Retrieve data from a table and register it as a model on Django's admin page
I'm using APscheduler to schedule some jobs in my app. I'm using my database as a job store, saving all info in a table named Jobs. Since this table is created and populated by APscheduler, I don't have access to it as a Django model instance (it's not defined in models.py). How can I retrieve data from this table and register it as a model on the admin page? I've searched the web and found Django's RawQuery, but it doesn't seem to work for me. -
How to validate a Django form based on Parent and Child form fields?
I have this structure, in Django 2.2: # models.py class Child(models.Model): parent2 = models.ForeignKey(Parent_2, on_delete=models.SET_NULL, null=True) parent = models.ForeignKey(Parent_1, on_delete=models.CASCADE, null=True) name = models.CharField('Name') class Parent_1(models.Model): cost = models.DecimalField('Cost', max_digits=6, decimal_places=2) date = models.DateField('Date', default=datetime.date.today) def __init__(self, *args, **kwargs): super(Parent_1, self).__init__(*args, **kwargs) self.__formset_is_valid__ = None # admin.py class ChildInline(admin.TabularInline): model = Child form = ChildInlineForm class Parent_1Admin(admin.ModelAdmin): inlines = [ChildInline] form = Parent_1AdminForm # form.py class ChildInlineForm(forms.ModelForm): class Meta: model = Child def clean(self): cleaned_data = super(ChildInlineForm, self).clean() self.instance.__formset_is_valid__ = self.is_valid() # print(self.instance.__formset_is_valid__) class Parent_1AdminForm(forms.ModelForm): extra_field = forms.CharField(widget=forms.Textarea(attrs={'rows': 10})) extra_field.required = False class Meta: model = Parent_1 def clean(self): cleaned_data = super(Parent_1AdminForm, self).clean() fields_warning = "Please fill 'extra_field' OR ChildInlineForm" if self.has_changed(): extra_field_cleaned = cleaned_data.get("extra_field") if not extra_field_cleaned and (self.instance.__formset_is_valid__ is not True): self.add_error("extra_field", ValidationError(fields_warning, code='%s-extra_field' % self.prefix)) return cleaned_data I based the code above on this answer to realize a chained validation between Parent1 form and Child Form. I would like a user can fill the extra_field OR at least a formset to have a valid form, but using the logic above: if I fill extra_field field the form is valid and content is saved if I fill the child form, parent form is not valid because it already … -
Django forms: inlineformset_factory inside another inlineformset_factory
My current task is to markup comments by the tonality. TONAL_TYPES = ['positive', 'negative', 'neutral', 'undefined'] For this purpose I'm building a service for a group of 'experts', which will consider each comment 3 times and make a decision based on 'majority rule'. I have following models: class Result(models.Model): text = models.TextField(null=True) title = models.TextField(null=True) class Comment(models.Model): text = models.TextField(blank=True, null=True) result = models.ForeignKey(Result, models.DO_NOTHING, null=True) class CommentRound(models.Model): comment = models.ForeignKey(Comment, models.DO_NOTHING, blank=True, null=True) tonal_type = models.CharField(choices=TONAL_TYPES, default='1') During first round expert needs to create result, add comments and make first markup for the comments. Currently first 2 things are working with following code(simplified): [views.py] from django.forms import inlineformset_factory from ..forms import ResultForm, CommentForm from ..models import Result, Comment def createResult(request): CommentFormSet = inlineformset_factory(Result, Comment, form=CommentForm, can_delete=False, extra=3, max_num=1) if request.method == 'POST': form = ResultForm(request.POST) if form.is_valid(): result = form.save() formset = CommentFormSet(request.POST, instance=result) if formset.is_valid(): formset.save() return redirect('/') else: logger.debug(formset.errors) else: logger.debug(form.errors) else: form = ResultForm() formset = CommentFormSet() render(request, 'my_app/result_form.html', {'form': form, 'formset': formset}) [forms.py] from django.forms import ModelForm from django import forms class CommentForm(ModelForm): class Meta: model = Comment class ResultForm(ModelForm): class Meta: model = Result How can I add one or several instances of 'CommentRound' … -
Dynamic DateTime field in Django form
I'm working on an Django 3 app which allows users to add and remove data requests for review. The user will select the user and site from a list and depending on the availability of data will populate a date/time field to be able to select a start and end date range. I'm using the Tempus Dominus time date picker to set the available dates in the date picker and am hardcoding them for the time being. The end goal will be to query Elasticsearch for them but hardcoded is fine for now. My question is; At the moment the form is static, meaning none of the selections change the content in other sections of the form, how can i make it dynamic so that the list of enableDates dates changes when the user selects a different user or site from the dropdown lists. Just to be clear, the list of users and sites will never change, it's just the enableDates that need to change. At the moment the form for submitting a request, along with displaying any existing requests looks like: This is my MODEL for storing data requests: class DataRequest(models.Model): USERS = [ ('User1', 'User1'), ('User2', 'User2'), ('User3', … -
Does LogEntry objects gets create while running the tests scripts in Django?
I am trying to write test script def test_logentry_gets_created(self): print("##############==================###############") path = 'url' t = self._create_blog() data = {'_selected_action': [t.pk], 'action': 'create_blog', 'csrfmiddlewaretoken': 'test',} self.client.post(path, data, follow=True) # I have a method defined which clones a blog article and then adds its actions in the LogEntry Model clone = t.clone(user) self.assertIn('test-blog (Clone)', str(LogEntry.objects.first())) print(LogEntry.objects.all().count()) print("##############==================###############") I am getting the count as Zero But since I am calling the LogEntry in the clone method shouldn't the object of this model get created? -
How can I scale my image down with the size of the screen in html/css, or is scaling even the issue?
I have done this many times before, but I cannot seem to find the issue. The page is fine at a certain size, but once I start testing it out and scaling down to around 1260px width, the image starts to overflow and white space is created. I removed one of the column divs so the image was moved, and I could scale smaller before the white started to do this, but then part of my footer did the same thing. I know this likely has something to do with the @media queries, but things just got a little messy along the way and I had to take a break from the project. Can anybody point out what is going on? Thanks. Here is an image showing the issue. Here is an image showing correct scaling and alignment. I provided as much HTML as I could (the chunk with the image), without going over character limit. And I have provided my entire CSS file below that. ``` <!-- Two --> <section id="two" class="main style2"> <div class="container"> <div class="row gtr-150"> <div class="col-6 col-12-medium"> <header class="major"> <h2>Lorem ipsum dolor adipiscing<br/> amet dolor consequat</h2> </header> <p>Adipiscing a commodo ante nunc accumsan interdum mi … -
django model change OneToOneField to ForeignKey with no DownTime
I made one field of my django model as OneToOneField. So, It's not possible to store duplicate FK value. I think changing OneToOneField to ForeignKey is the solution. Current class MyModel(models.Model): ... abc = models.OneToOneField(YourModel, related_name='my_model', blank=True, null=True, on_delete=models.CASCADE) ... Future class MyModel(models.Model): ... abc = models.ForeignKey(YourModel, related_name='my_model', blank=True, null=True, on_delete=models.CASCADE) ... The problem is downtime when migrating. This model is an important model in my service, many requests come in even in a moment. It also has many data. Is there a way to fix this without downtime? And my service is using mysql 5.6 and django 2.2. -
Save list of images from models django
I am using Django 3 and I want to create a Model where I upload a tensor file, then I elaborate it, extract the slices of this tensor and save the single slices as different images. here is my model: class Case(models.Model): slug = ShortUUIDField(max_length=3) title = models.CharField(max_length=50) #... ct = models.FileField() # here I want to save a series of images that I extracted from the tensor 'ct' The number of images extracted is not constant. Can you please help me? -
creating multi-lingual website using django
I am creating a website from scratch where I am planning to make it dynamically multilingual. Tools I use are: MongoDB for my database (atlas) pymongo to connect to DB django as my framework env My idea is to have a website that can have multiple languages as necessary. languages can be RTL and LTR. I can add any language in a form of json file that has an item against its translation to the desired language, for instance english-french json file would be: {"door":"porte"} {"direction": "LTR"} by adding such a file my website should be able to have the right information regarding the french language for instance and everything should appear in french correctly as specified in the json file. I plan to have two types of html pages in my DB for each of my website pages; one for "RTL" and one for "LTR", I render them based on the request of the user. (language chosen in the front end). In translation process, after picking the right orientation of the language, I use django template variables in my html to place the right language using the correct json file of the language, all my json files are stored …