Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
Django queryset annotate on two field
I have a django models (It record the activities for some group_id) class Record(models.Model): group_id = models.PositiveSmallIntegerField(null=True, blank=True, default=None) update_date = models.DateTimeField(auto_now=True) status = models.PositiveSmallIntegerField(default=1) #only 2 status number: 1 or 2 activites = models.CharField(max_length=64, null=True, blank=True, default=None) #Not important for this question ... .. . I want to get a result like this: group the result by update_date count the number of status '1' and '2' separately {'update_date':'2020-01-01', 'status_equal_to_1': 10, 'status_equal_to_2': 20}, {'update_date':'2020-01-03', 'status_equal_to_1': 12, 'status_equal_to_2': 9},...... I have tried to use, result = Record.objects.values('group_id', 'update_date', 'status').annotate(count=Count('update_date')) However, it only count the update_date. How to count the status on this queryset? -
can't connect details.html to index.html in django
index.html {% for item in item_list%} <ul> <li> <a href="/foodmenu/{{item.id}}">{{item.id}} -- {{item.item_name}}</a> </li> </ul> {% endfor %} detail.html <h1>{{item.item_name}}</h1> <h2>{{item.item_desc}}</h2> <h3>{{item.item_price}}</h3> views.py from django.shortcuts import render from django.http import HttpResponse from django.http import HttpResponseRedirect from .models import item from django.template import loader # Create your views here. def index(request): item_list = item.objects.all() template_name = loader.get_template('foodmenu/index.html') context = { 'item_list':item_list, } return HttpResponse(template_name.render(context,request)) def detail(request,item_id): item = Item.objects.get(pk=item_id) template_name = loader.get_template('foodmenu/detail.html') context = { 'item':item, } return HttpResponse(template_name.render(context,request)) urls.py from . import views from django.conf.urls import url urlpatterns = [ #foodmenu/ url("foodmenu", views.index,name='index'), #foodmenu/1 url("<int:item_id>/", views.detail,name='detail'), ] this is a django website where the index creates the link and by clicking on the hyperlink it takes me to the details page but problem whith current code is upon clicking hyperlink it does not take me to the details page , is something wrong with the urls.py or views.py ? -
Retrieving a Foreign Key value with django-rest-framework
I have to simple model, one is department, that creating successfully, when I going to create designation with the value of department id its said Could not find department. Here is my designation view class DesignationCreateView(CreateAPIView): serializer_class = DesignationSerializers permission_classes = (IsAuthenticated, ) # queryset = Designation.objects.all() lookup_url_kwarg = 'department_id' def get_queryset(self): return Designation.objects.filter(department_id=self.kwargs.get(self.lookup_url_kwarg)) def create(self, request, *args, **kwargs): try: department = Department.objects.get(id=request.data.get('department_id')) request.data['department'] = department.id except Department.DoesNotExist: raise NotFound(detail='department not found') return super(DesignationCreateView, self).create(request, *args, **kwargs) -
How to create multiple model instance (have one-to-many relationship) with an API call in DRF
I have 2 models Product and Watch like below class Product(models.Model): id = models.CharField(max_length=255, primary_key=True) # other fields And the Watch model have the product_id foreign key connected with Product model class Watch(models.Model): product_id = models.ForeignKey( Product, related_name='watches', on_delete=models.CASCADE, null=True, ) # other fields When I call an API to create a new watch with product_id in the request body. I want to check if the product with that product_id does exist or not. If not, I create a new product instance at the same time. Currently, I'd overiding the create() method in serializer class like so def create(self, validated_data): product_id = validated_data['product_id'] is_product_exist = self.is_product_exist(product_id) if (is_product_exist): watch = Watch.objects.create(**watch_data) else: Product.objects.create(**product_data) watch = Watch.objects.create(**watch_data) return watch But when calling API, I got the error {"product_id":["Invalid pk \"57668290\" - object does not exist."]} So how can I deal with this error? thank you guys -
Is it possbile to acces pythonanywhere database? [By free account] [closed]
I tried so many times to connect pythonanywhere database. I have hostname and password (Database too). OperationalError at /login/ (1044, "Access denied for user 'username'@'%' to database 'mybase'") -
no such table: (Django)
when i run my code (its for a project) i get this error: "no such table: encyclopedia_article". The error appears to come from 9 line of views.py (obj = article.objects.get(id=1). here is the code: views.py from django.shortcuts import render from django.http import HttpResponse from . import util import random from .models import article from .forms import ArticleForm def index(request): obj = article.objects.get(id=1) #THIS IS WHAT APPERS TO CAUSE THE ERROR context = { 'object': obj } entries = util.list_entries() random_page = random.choice(entries) return render(request, "encyclopedia/index.html", { "entries": util.list_entries(), "random_page": random_page, }) def CSS(request): return render(request, "encyclopedia/css_tem.html", { "article_css": "css is slug and cat" }) def Python(request): return render(request, "encyclopedia/python_tem.html", { "article_python": "python says repost if scav" }) def HTML(request): return render(request, "encyclopedia/HTML_tem.html", { "article_HTML": "game theory: scavs are future humans" }) def Git(request): return render(request, "encyclopedia/Git_tem.html", { "article_Git": "github is git" }) def Django(request): return render(request, "encyclopedia/Django_tem.html", { "article_Django": "this is a framework" }) def new_article(request): form = ArticleForm(request.POST or None) if form.is_valid(): form.save() context = { 'form': form } return render(request, "encyclopedia/new_article_tem.html", context) models.py: class article(models.Model): title = models.CharField(max_length = 120) description = models.TextField(blank=True, null = False) forms.py: from django import forms from .models import article class ArticleForm(forms.ModelForm): class … -
django orm how to update calculate data using only one query
i create one feature about item_buy data here is my ORM class class BuyData(models.Model): buy_count = models.IntegerField(default=0) refund_count = models.IntegerField(default=0) refund_rate = models.FloatField(default=0.0, help_test='refund_count / buy_count') when i create a function about refund i want update my BuyData model like def refund(): buy_data_queryset.update( refund_count = F('refund_count') + 1 ) buy_data_queryset.update( refund_rate = F('refund_count') / F('buy_count') * 100 ) but i think this way is not good because when this function called a lot of time per second, may be this 2 step queries raise some problem... so i found some document, and changed like this def refund(): with transaction.atomic(): buy_data_queryset.update( refund_count = F('refund_count') + 1 ) buy_data_queryset.update( refund_rate = F('refund_count') / F('buy_count') * 100 ) i think this way is good. but i want to know that solve this problem using only one query i know this is not a solution def refund(): # not a solution buy_data_queryset.update( refund_count = F('refund_count') + 1 refund_rate = F('refund_count') / F('buy_count') * 100 ) please give me some advice thank you :))