Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I relate a model instance to another in django?
I'm trying to relate a model instance to another. For example, If I have a model named Person and I'd like to relate a person to his/her father. How can I do that? I'm not proving a code because there isn't one about this specific question. But the example above is basically what I'm trying to do: I have a model of people (named Voter) I'm trying to relate each instance to another as a relative (father, mother, sister) Thanks in advance. -
Enforcing max_length on CharField
I'm have a CharField that has a max_length of 200 set in the model definition. I'm able to save strings of longer than 200 to an instance of this model without any error being thrown. Is there a way to enforce max_length when saving data to a CharField or is this limit only enforced on ModelForms? Thanks! -
Exclude null values from Django's ArrayAgg
I'm using Django's postgres-specific ArrayAgg aggregator. It works fine but when the list is empty I get [None] instead of []. Is there any way to filter these null values out? I've tried to pass a filter argument to ArrayAgg but it didn't work. Here's a simplified example of my setup: class Image(models.Model): # ... class Reporter(models.Model): # ... class Article(models.Model): reporter = models.ForeignKey(Reporter, related_name='reporters') featured_image = models.ForeignKey(Image, related_name='featured_images') # ... Then if I make this query: reporter = Reporter.objects.annotate( article_images=ArrayAgg('articles__featured_image'), distinct=True ).first() And the first reporter in the result set doesn't have any associated article, I get: > reporter.article_images [None] I've tried to add a filter, but no luck: Reporter.objects.annotate( article_images=ArrayAgg( 'articles__featured_image', filter=Q(articles__featured_image__isnull=False) ) ) I've tried to use Case/When, again no luck: Reporter.objects.annotate( article_images=ArrayAgg( 'articles__featured_image', filter=Q(articles__featured_image__isnull=False) ) ) -
Tables not working on Postgres "relation does not exist"
So I have a lot of trouble using MySql in local and Postgres on Heroku. I have this models.py class AdressBook(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="Nom de l'utilisateur") text = models.CharField(max_length=200,verbose_name="Description") number = models.CharField(max_length=20,verbose_name="Numéro de téléphone") def __str__(self): return self.text def get_absolute_url(self): return reverse('dashboard-home') It is working fine on my local machine, but when I push to Heroku I have this message : ProgrammingError at /admin/dashboard/adressbook/ relation "dashboard_adressbook" does not exist LINE 1: SELECT COUNT(*) AS "__count" FROM "dashboard_adressbook" And it does exist ... -
Issue while fetching all records while collapsing and expanding them
I'm fetching records from my table in Django view and passing those to my template. Without the javascript code, I can see all the records on the front end. But when I add the js code I'm facing issue with fetching all records. Only the first key's values is being accessed. Here's my code views.py def user_files(request): folder_name = [] f_dict = {} years_dict = dict() files = FileUpload.objects.all() for f in files: f_name = f.File1.url[15:25:1] name = f.File1.url if f_name in years_dict: years_dict[f_name].append(name) else: years_dict[f_name] = [name] print(years_dict,'years_dict') # print(folder_name,'folder_name') user = request.user.username return render(request, 'user_files.html', {'files': files, 'users':user, 'years_dict':years_dict}) and my template file code {% for key, values in years_dict.items %} <div id="expand"> {{key}} <span id="plusMinus">+</span><br> </div> <p id="para1" style="display: none;"> {% for v in values %} {% for file in files %} {% if file.File1.url == v %} <a href="{{ v }}" target="_blank">{{ file.Filename }}</a><br/> {% endif %} {% endfor %} {% endfor %} </p> {% endfor %} and js script is as follows : var expandEl = document.getElementById("expand"); var plusMinusEl = document.getElementById("plusMinus"); var para1El = document.getElementById("para1"); function toggleMe(el) { if(el.offsetParent === null) { plusMinusEl.textContent = "-"; el.style.display = "block" } else { plusMinusEl.textContent = "+"; el.style.display … -
How to get title, artist, and album art using mutagen (Python and Django)?
So i am using mutagen to get information about uploaded musics in my website. I tried the following code: import mutagen mutagen.File(filePath) it displays the following message: {'TXXX:compatible_brands': TXXX(encoding=<Encoding.UTF8: 3>, desc='compatible_brands', text=['isommp42']), 'TXXX:minor_version': TXXX(encoding=<Encoding.UTF8: 3>, desc='minor_version', text=['0']), 'TXXX:major_brand': TXXX(encoding=<Encoding.UTF8: 3>, desc='major_brand', text=['mp42']), 'TSSE': TSSE(encoding=<Encoding.UTF8: 3>, text=['Lavf57.56.101'])} Isn't this code supposed to print artist and title as described in their documentation? I am confused. Is it encoded? if so, how do i decode it? -
domain name disallow error in django nginx gunicorn setup
I have successfully gotten the site to run, and it loads well via the the IP Address. However, when I use my domain name, I get a error Invalid HTTP_HOST header(Disallowed Host ). Pinging the domain name works. i have also allow domain name inside settings .py and server name. -
Django Password Reset Security Issue?
I may have found a security hole in Django's authentication framework for resetting passwords. When using django.contrib.auth views, the password reset form only asks for an email, with the expectation that it is the email of the logged in account requesting the password reset. However, I can enter the email of any registered account, and have the password reset link sent to that email. If I open the link in that email and enter the new desired password, it changes to password for the account registered to that email, not for the account that entered that email address. This means that if a user gains access to another user's email, that user can reset the password of the compromised user without ever having to log in as the compromised user. Is there a way to check if the entered email for the password reset is actually the email of the user currently requesting the reset? If not, is there a better, more secure way to handle password reset requests? -
How to solve a attribute error in Django?
I am trying to log in a user but I am getting an attribute error. Here is my forms.py: class Login(forms.Form): email = forms.EmailField(max_length=250) password = forms.CharField(widget=forms.PasswordInput) def login_user(self): email = self.cleaned_data['email'] password = self.cleaned_data.get('password') user = authenticate(email=email, password=password) if user in User.objects.all(): login(self, user) else: return render(self, 'todoapp/waiting_2.html') Here is my views.py: def login_user(request): if request.method == 'POST': login_form = Login(request.POST) if login_form.is_valid(): login_form.login_user() login_form.save() return HttpResponseRedirect(reverse('dashboard')) else: return render(request, 'todoapp/waiting_2.html') return render(request, 'registration/login.html', {'form': Login()}) When I fill in the fields and try to log in, I am getting the error: AttributeError at /login/ 'Login' object has no attribute 'session' -
change input text field value using ng-template in angular 6
How to change this input value using ng-template <input #value pInputText type="number" [formControl]="delivary_charge" min="1" max="9999999999" class="input-width"> -
Django: Mock model's create method
I have a model called Job. And I made a file services.py where I am going to put some methods and business logic. I am trying to test them using Mock. The problem is that If I want to mock Job.objects.create it, it gives me an error. services.py from .models import Job class CreateJob: def __init__( self, title, email, ): self._title = title self._email = email def execute(self): # Create dictionary with the keys without the first _ in the name params = {k[1:] if k[0] == '_' else k:v for k,v in self.__dict__.items() if v is not None} job = Job.objects.create(**params) return job This is mi test case, and it runs OK class TestExecute(TestCase): def setUp(self): self._use_case = CreateJob( title='How to test a job creation', email='john.smith@example.com', ) def test_return_job_type(self): result = self._use_case.execute() assert isinstance(result, Job) But If I want to patch the create method, so I do not hit the database, like this def create_job(params): return Job(**params) @patch.object(Job.objects, 'create', side_effect=create_job) class TestExecute(TestCase): def setUp(self): self._use_case = CreateJob( title='How to test a job creation', email='john.smith@example.com', ) def test_return_job_type(self,mock_create): result = self._use_case.execute() assert isinstance(result, Job) I have the following error: TypeError: create_job() got an unexpected keyword argument 'title' And here is … -
Chart JS. datasets - separate dataset options to dataset properties
I have a json array which is to be rendered in a linegraph. This is the sample structure of my json data returned from the api. 'datasets': [ { 'label': 'Dataset 1', 'data': [11, 12, 13, 14, 15] }, { 'label': 'Dataset 2', 'data': [21, 22, 23, 24, 25] }, { 'label': 'Dataset 3', 'data': [31, 32, 33, 34, 35] }, ] But I need to style each data set with borderDash, borderCapStyle, borderWidth, backgroundColor, borderColor which are all statics and would make more sense if these styling data are excluded on the returned json data from the api, and better be declared statically on the frontend side instead. datasets: [ { label: "Dataset 1", data: [11, 12, 13, 14, 15], borderDash: [3,15], borderCapStyle: "round", borderWidth: 2, backgroundColor: 'rgba(20, 199, 110, 0.1)', borderColor: 'rgb(20, 199, 110)', }, { label: "Dataset 2", data: [21, 22, 23, 24, 25], borderDash: [3,15], borderCapStyle: "round", borderWidth: 2, backgroundColor: 'rgba(255, 99, 132, 0.1)', borderColor: 'rgb(255, 99, 132)', }, { label: "Dataset 3", data: [31, 32, 33, 34, 35], borderDash: [3,15], borderCapStyle: "round", borderWidth: 2, backgroundColor: 'rgba(31, 151, 145, 0.1)', borderColor: 'rgb(31, 151, 145)', } ] Is there any way I can separate the arrays for … -
How to keep Local mysql database in sync with remote mysql database?
How do I sync local mysql to remote mysql all the time. Can I take help of firebase to sync the data to remote database. Or is there anything available with django to perform this action -
How to prevent recursion in django post_save signal?
I tried this answer https://stackoverflow.com/a/28369908/9902571 in my model and done the following :- from functools import wraps def prevent_recursion(func): @wraps(func) def no_recursion(sender, instance=None, **kwargs): if not instance: return if hasattr(instance, '_dirty'): return func(sender, instance=instance, **kwargs) try: instance._dirty = True instance.save() finally: del instance._dirty return no_recursion My model: class Journal(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,null=True,blank=True) company = models.ForeignKey(company,on_delete=models.CASCADE,null=True,blank=True,related_name='Companyname') date = models.DateField(default=datetime.date.today) voucher_id = models.PositiveIntegerField(blank=True,null=True) by = models.ForeignKey(ledger1,on_delete=models.CASCADE,related_name='Debitledgers') to = models.ForeignKey(ledger1,on_delete=models.CASCADE,related_name='Creditledgers') debit = models.DecimalField(max_digits=10,decimal_places=2,null=True) credit = models.DecimalField(max_digits=10,decimal_places=2,null=True) My signal: @receiver(post_save, sender=journal) @prevent_recursion def pl_journal(sender, instance, created, **kwargs): if created: if instance.By.group1_Name.group_Name == 'Indirect Expense': Journal.objects.update_or_create(user=instance.user,company=instance.company,date=instance.date, voucher_id=instance.id, voucher_type= "Journal",by=instance.by,To=ledger1.objects.filter(user=instance.user,company=instance.company,name__icontains='Profit & Loss A/c').first(),debit=instance.debit,credit=instance.credit) But the RecursionError of maximum recursion depth exceeded while calling a Python object stills comes while creating a journal object. I want to pass the post_save signal for the same model (Journal) which when matches the condition in the signal gets called recursively. Any anyone tell me what is wrong in my code? Thank you -
How can I implement all the business logic from views to forms?
I am working on a webapp and I want to move my logic in views to forms. In views I only want to keep the checking of validation. That is: Example: def myformview(request): if request.POST: form = MForm(request.POST) if form.is_valid(): form.save() redirect("to-some-view") render(request, "template_name.html", { 'form': form }) Here is my views.py: def login_user(request): if request.method == 'POST': login_form = Login(request.POST) if login_form.is_valid(): email = login_form.cleaned_data['email'] password = login_form.cleaned_data.get('password') user = authenticate(email=email, password=password) if user in User.objects.all(): login(request, user) return HttpResponseRedirect(reverse('dashboard')) else: return render(request, 'todoapp/waiting_2.html') return render(request, 'registration/login.html', {'form': Login()}) Here is my forms.py: class Login(forms.Form): email = forms.EmailField(max_length=250) password = forms.CharField(widget=forms.PasswordInput) Everything is working fine for now. I just want to move the logic in views to forms. That's it. -
Circular import in Django 2 python "urls" file
I have request login API using Django framework but error through in "circular import" error of URL patterns. please, anyone, give us a solution regarding point. Error log write in log file: [Sun Mar 10 20:30:47.407794 2019] [wsgi:error] [pid 21457:tid 139659590813440] Internal Server Error: /ai_chat_bot/users/login [Sun Mar 10 20:30:47.407814 2019] [wsgi:error] [pid 21457:tid 139659590813440] Traceback (most recent call last): [Sun Mar 10 20:30:47.407816 2019] [wsgi:error] [pid 21457:tid 139659590813440] File "/opt/python/ai_rest_env/lib/python3.5/site-packages/django/urls/resolvers.py", line 542, in url_patterns [Sun Mar 10 20:30:47.407818 2019] [wsgi:error] [pid 21457:tid 139659590813440] iter(patterns) [Sun Mar 10 20:30:47.407819 2019] [wsgi:error] [pid 21457:tid 139659590813440] TypeError: 'module' object is not iterable [Sun Mar 10 20:30:47.407821 2019] [wsgi:error] [pid 21457:tid 139659590813440] [Sun Mar 10 20:30:47.407822 2019] [wsgi:error] [pid 21457:tid 139659590813440] During handling of the above exception, another exception occurred: [Sun Mar 10 20:30:47.407823 2019] [wsgi:error] [pid 21457:tid 139659590813440] [Sun Mar 10 20:30:47.407825 2019] [wsgi:error] [pid 21457:tid 139659590813440] Traceback (most recent call last): [Sun Mar 10 20:30:47.407826 2019] [wsgi:error] [pid 21457:tid 139659590813440] File "/opt/python/ai_rest_env/lib/python3.5/site-packages/django/core/handlers/exception.py", line 35, in inner [Sun Mar 10 20:30:47.407828 2019] [wsgi:error] [pid 21457:tid 139659590813440] response = get_response(request) [Sun Mar 10 20:30:47.407829 2019] [wsgi:error] [pid 21457:tid 139659590813440] File "/opt/python/ai_rest_env/lib/python3.5/site-packages/django/utils/deprecation.py", line 93, in __call__ [Sun Mar 10 20:30:47.407831 2019] [wsgi:error] [pid 21457:tid 139659590813440] … -
Breadcrum in django
my question is simple , i want to make this below breadcrum is in dictionary format,for eg:- Dict={0-->"url1", 1-->"url2"} 0--Home------------------->Home 1--HCPC------------------->Home>HCPC 2--TCPC------------------->Home>TCPC 3--|-A--------------------->Home>TCPC>A 4--|-B--------------------->Home>TCPC>B (Home) (TCPC) (B) 0----->2----->4 | | | | 1 3 (A) (HCPC) -
Create two apache processes for one Django app
I have one django project with two apps. What I want is to create two apache process, each will handle apis requests to each app urls. If I create multiple virtual hosts with WSGIDaemonProcess and WSGIScriptAlias pointing to each app, will that work? Can anyone share apache config which I can use. -
Django Calculate Opening Balance sql query
Can anyone please help transform this view function logic into Django mysql query. with this I can get the results i want but as the database gets bulky, it becomes slower and slower. The need here is to calculate opening and closing balances. Models: class Item(models.Model): item = models.CharField(max-length=50) opening_balance = models.PositiveIntegerField() class Transaction(models.Model): item_name = models.ForeignKey(Item, on_delete=models.CASCADE) purchases = models.PositiveIntegerField() sales = models.PositiveIntegerField() View def display_balances(request): balances = [] items = Item.objects.all() for i in items: opening = i.opening_balance bal = Transaction.objects.filter(item_name=i) for item in bal: dict = {} opening_balance = opening closing_balance = opening_balance + item.purchases - item.sales opening = closing_balance dict['opening']=opening dict['purchases']=item.purchases dict['sales']=item.sales dict['closing']=closing_balance balances.append(dict) return render(request, '123/details.html', {'balances':balances}) Template {% for b in balances %} <td>{{b.opening}}</td> <td>{{b.purchases}}</td> <td>{{b.sales}}</td> <td>{{b.closing}}</td> {% endforfor %} Output: opening purchases sales closing 10 20 10 20 20 10 15 15 15 0 10 5 and so on... I need someone to help me transform the View Logic into sql query instead of using List of Dictioneries as i am doing. it becomes slow when the database is bulky. -
What is a calling signature?
I'm reading Django Docs for the Model Class and it says to: ...take care not to change the calling signature as any change may prevent... I've heard of calling signature before, I've always assumed it was the function name, but then I question why they would mention something so obvious. I checked Wikipedia and it only gave me results for type signature which I (assume) think is the same? If I'm wrong, then what is a calling signature? And more importantly, how do I not alter it? -
Nested serializers for rest api in django
My current api shows as below, and I'd like to modify it to show desired api. I posted similar question before, but the answer was not adequate and was a hacky solution. I've added in one more serializer, but I'd like it to show desired api as shown below, input coming in this format. I'm getting error when I modified as shown below. "type" : [ { "age" : "27", "nationality" : "usa" } { "age" : "24", "nationality" : "canada" }, { "age" : "26", "nationality" : "thailand" }, Current API [ { "name" : "Jay", "school" : "college", "type" : "usa" "age": "27" "nationality": "usa" }, ] Desired API [ { "name" : "Jay", "school" : "college", "type" : [ { "age" : "27", "nationality" : "usa" }, { "age" : "24", "nationality" : "canada" }, { "age" : "26", "nationality" : "thailand" }, ] } ] Serializers.py class SchoolSerializer(serializers.ModelSerializer): class Meta: model = School fields = ("name", "school") def update(self, instance, validated_data): instance.name = validated_data.get("name", instance.name) instance.school = validated_data.get("school", instance.session) instance.type = validated_data.get("type", instance.session) instance.age = validated_data.get("age", instance.session) instance.nationality = validated_data.get("nationality", instance.session) instance.save() return instance class TypeSerializer(serializers.ModelSerializer): class Meta: model = School fields = ("type", "age", "nationality") … -
How to get JSON obeject from view using REST framework
I using django Rest Framework and i want to get JSON that build by Rest Framework and using search. So i need to use empidlong for calling outside JSON request. e.g. http://localhost:8000/abc/?search=12 if u surf above url u will get This is making from Rest API when call above URL HTTP 200 OK Allow: GET, POST, HEAD, OPTIONS Content-Type: application/json Vary: Accept [ { "company": "ABC", "plate_no": "1234", "project_code": "ABC1234", "empidlong": "123456", }, ] This is my code views.py from django.shortcuts import render # Create your views here. from rest_framework import viewsets, filters from .models import getData from .serializers import CarSerializer import requests #def res(requests): # res = pd.DataFrame(list(getData.objects.all().values())) class CarViewSet(viewsets.ModelViewSet): #filter_class = getDataFilter #filter_backends = (filters.SearchFilter, DjangoFilterBackend) #queryset = getData.objects.all() #serializer_class = CarSerializer queryset = getData.objects.all() serializer_class = CarSerializer filter_backends = (filters.SearchFilter,) __basic_fields = ('plate_no',) search_fields = __basic_fields def retrieve(self, request, *args, **kwargs): instance = self.get_object() #serializer = ProfileSerializer(instance=instance) serializer = CarSerializer(instance=instance) data = serializer.data for a in data: empid= a['empidlong'] requests.get('http://192.168.10.32/BASIC%20DATA/GetEmployees/'+empid +'/Y') return Response(serializer.data) def get_queryset(self): queryset = getData.objects.all() emp = self.request.query_params.get('emp', None) if emp is not None: queryset = queryset.filter(empidlong=emp) return queryset The Problem is while i ran this code requests.get('http://192.168.10.32/GetEmployees/'+empid) This URL Request wont working(not send … -
Update dynamic field django queryset
i want build update django queryset with dynamic field like param. Example my field is planned: def update_data(period, old_planned, new_planned): Cost.objects.filter(period=period).update( planned=F('planned') - old_planned + new_planned) If i want pass planned field like param input in def like def(period, old_planned, new_planned, update_field), how to do it with keep use F inside ? -
Drawing shapes on html canvas in python/django
I am trying to draw shapes, line, triangles, rectangle on a web page using Django. How to accomplish this? Below is my code. views.py import tkinter from django.shortcuts import render from django.http import HttpResponse from django.template import loader def drawchart(): root = tkinter.Tk() canvas = root.Canvas(root, width=400, height=500) canvas.pack() blackline = canvas.create_line (0, 0, 200, 0) root.mainloop() return blackline html file <!DOCTYPE html> <html> <Head> <title>Line</title> </Head> <body> <h3>test</h3> <canvas id="myCanvas" width="400" height="500"> {{drawchart()}} </canvas> </body> </html> -
How to write urlpatterns in django?
I have this structure of urls: page/section/subsection/article, where section, subsection and article is user-generated slug names. how can i write the urlpatterns? i do this, but may be exist better method? urlpatterns = [ url(r'^$', views.index), url(r'^(?P<slug>[-\w]+)/$', views.section), url(r'^(?P<slug>[-\w]+)/(?P<subslug>[-\w]+)/$', views.subsection), url(r'^(?P<slug>[-\w]+)/(?P<subslug>[-\w]+)/(?P<articleslug>[-\w]+)/$', views.article) ] My views: def index(request): return render(request, 'MotherBeeApp/index.html', {}) def section(request, slug): sections = Section.objects.filter(page=slug) if sections: return render(request, 'MotherBeeApp/section.html', {'Sections': sections}) else: return render(request, 'MotherBeeApp/404.html', status=404) def subsection(request, slug, subslug): subsection = Section.objects.get(link_title=subslug) articles = Article.objects.filter(section=subsection.pk) page_title = subsection.title return render(request, 'MotherBeeApp/subsection.html', {'Articles': articles, 'PageTitle': page_title}) def article(request, slug, subslug, articleslug): article = Article.objects.get(link_title=articleslug) return render(request, 'MotherBeeApp/article.html', {'Article': article})