Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I am confused about what the CheckingAccounts class returning inside my Customer class in the following code
Here is my base Class Accounts, class Accounts: def init(self,account_no,total_balance): self.account_no = account_no self.total_balance = total_balance def __str__(self): return '{:.2f}'.format(self.total_balance) def deposit(self,deposit): self.total_balance = self.total_balance + deposit return self.total_balance def withdrawl(self, withdrawl): if self.total_balance >= withdrawl: self.total_balance = self.total_balance - withdrawl else: return ("Funds Unavaliable") CheckingAccounts class is inheriting base class Accounts class CheckingAccount(Accounts): def init(self, account_no,total_balance): super().init(account_no,total_balance) def str(self): return "The account number is:\n#{0} \nThe balance is:\n{1}".format(self.account_no, Accounts.str(self)) Now a customer class, and this is where I am having confusing about the open_checking function which is using CheckingAccount class and I do not understand whats it will return and store in the accounts list. class Customer: def init(self, name, PIN): self.name = name self.PIN = PIN # Create a dictionary of accounts, with lists to hold multiple accounts self.accts = {'C':[],'S':[],'B':[]} def __str__(self): return self.name def open_checking(self,acct_nbr,opening_deposit): self.accts['C'].append(Checking(acct_nbr,opening_deposit)) -
Django count integer up_vote/down_vote's won't work
i want to increase/decrease the integer vaule of my category_request model-fields up_vote/down_down but for some reason i always get to the else block. views.py from django.db.models import F ... def category_request_up_vote (request, pk): category_request = get_object_or_404(CategoryRequests, pk=pk) if request.method == 'POST': category_request.up_vote = F('up_vote') + 1 category_request.save() messages.success(request, 'You have successfully Provided an Up-Vote for this Request') return redirect('category_request_detail', pk=category_request.pk) else: messages.error(request, 'Uuups, something went wrong, please try again.') return redirect('category_request_detail', pk=category_request.pk) def category_request_down_vote(request, pk): category_request = get_object_or_404(CategoryRequests, pk=pk) if request.method == 'POST': category_request.down_vote = F('down_vote') - 1 category_request.save() messages.success(request, 'You have successfully Provided an Down-Vote for this Request') return redirect('category_request_detail', pk=category_request.pk) else: messages.error(request, 'Uuups, something went wrong, please try again.') return redirect('category_request_detail', pk=category_request.pk) Thanks in advance -
Django JSONField dynamic contains and key lookups
I need to filter objects by key-value pair contained in JSONField with list of dicts where key and value are model fields. This question is related to Django JSONField list of dicts "contains" filter inside Subquery This one works perfectly: EntityObject.objects.filter( data__list_of_dicts__contains=[{'static_key': 'static_value'}] ) But with dynamic values: EntityObject.objects.filter( data__list_of_dicts__contains=[{F('field1'): F('field2')}] ) It causes an error: TypeError: keys must be a string And with static key and dynamic value: EntityObject.objects.filter( data__list_of_dicts__contains=[{'static_key': F('field2')}] ) Another error: TypeError: F(field2) is not JSON serializable -
How does Django deployments happen on Servers?
I'm sorry if it's offtopic but I didn't find any other better to place to ask. I started learning Django six months ago and I really really loved it. I learnt how to deploy the django projects to EC2 instances. Basically 1st time when the django project is deployed to EC2, the instance will be configured with httpd.conf, wsgi, change permissions on files and folders and other stuff and the project will be cloned to the EC2 instance and server is restarted. My question is how do they do future deployments? They in this context is anyone who deploys Django on EC2 instances. Do they login to EC2 instances and manually clone the repository from VCS site and restart the server? Do they have any other automated mechanism to pull the code, ensure permissions and restarting the apache server etc. How is it done basically every time they go for a release? Someone please help me understand this. -
Django model not finding a field, keeps saying NoneType yet database shows it
I have a django model: @python_2_unicode_compatible class GroupProviderInformation(models.Model): group = models.ForeignKey('Group', null=True, blank=True, on_delete=models.PROTECT) provider = models.ForeignKey('Provider', null=True, blank=True, on_delete=models.PROTECT) specialty = models.ForeignKey('Specialty', on_delete=models.SET_NULL, null=True, blank=True) provider_contact = models.CharField(max_length = 50, blank=True, null=True) credentialing_contact = models.CharField(max_length = 50, blank=True, null=True) hospital_affiliation = models.CharField(max_length = 50, null=True, blank=True) date_joined_group = models.DateField(auto_now=False, auto_now_add=False, null=True, blank=True) #models.DateField(auto_now_add=True) def __str__(self): return "SP PK: " + str(self.specialty.pk) + " GRP: " + str(self.group.pk) + " PROV: " + str(self.provider.pk) I import data into this model, and then do a query from a view: group = Group.objects.get(pk=gid) provider = Provider.objects.get(pk=pid) grpProvInfo = GroupProviderInformation(group=group, provider=provider) (the id's are 136 and 24). I look in my database the table is there, the record is there all the way across even has specialty_id as containing 16 looks good. Yet if i try to print print(grpProvInfo) the return "SP PK: " + str(self.specialty.pk) + " GRP: " + str(self.group.pk) + " PROV: " + str(self.provider.pk) Throws an error 'NoneType' object has no attribute 'pk', it means the self.specialty yet I know it exsists. Does this in my view when I try to use the object and get the data grpProvInfo.specialty.whateverfield I am perplexed as to why this isn't taking, it … -
Django - add a Integerfield in the template to every m2m object
I'm trying to add functionality to add a IntegerField next to every 'stockItem' in the template so that the user can type how many of that item was needed and then update the 'count' value in the 'Stock' model. As for now it only works when the user only selects one item. (I know that how I implement this now would never work but I try to show how I intend it to work) Models: class Machine_Service(models.Model): title = models.CharField(max_length = 100) stockItem = models.ManyToManyField(Stock) date = models.DateTimeField(default=timezone.now) comment = models.TextField() machine = models.ForeignKey(Machine, on_delete=models.CASCADE) def __str__(self): return self.title class Stock(models.Model): title = models.CharField(max_length=100) count = models.IntegerField(default=10) minLimit = models.IntegerField(default=1) resellerCompany = models.CharField(max_length=100) resellerPerson = models.CharField(max_length=100) resellerEmail = models.EmailField() def __str__(self): return self.title (I left the 'Machine' model out of this because it does not belong to the question) view: def CreateService(request): if request.method == 'POST': form = CreateServiceForm(request.POST) if form.is_valid(): m = Machine.objects.get(id=form['machine'].value()) service = Machine_Service(title=form['title'].value(), date=form['date'].value(), comment=form['comment'].value(), machine=m) service.save() items = form['stockItem'].value() for item in items: s = Stock.objects.get(id=item) service.stockItem.add(s) service.save() return redirect('Machines-Home') else: form = CreateServiceForm() context = { 'form': form } form: class CreateServiceForm(forms.ModelForm): count = forms.IntegerField(required=False) class Meta: model = Machine_Service fields = ['title', 'stockItem', … -
Django vs Django Rest Framework (DRF) and a Front-end Framework - What is the development time difference?
We are getting started on a project and it is up for debate whether Django should be used on it's own with the django templates and some React/Vue javascript added in for fancy things. OR We should use the django rest framework and use React/Vue for all of the front-end work. How much more work is the second option in comparison to the 1st? If option 1 is chosen, we will likely transition into option 2. How much work will that be? Any insights or comments would be much appreciated. -
Create a django password in a simple python script
I need to generate an encrypted password that can be used within Django in a simple python script. What package/module would I need to import to achieve that? I am looking for something like: from django.auth import create_password_from_string django_password = create_password_from_string('coolpassword') The background is, that I have a PHP application on server1 which should share the accounts with a Django application on server2. When an account is created in the PHP application, I want to fire up a python script that generates the encrypted password for the django application and transfers it to server2. -
Optimizing a large Django project by moving certain process to dedicated machine (microservice?)
I'm working on a large Django project that uses application server(s) to process Latex. As our site grows, the Latex processing is affecting performance when site traffic is high. One idea I had was to move the Latex processing to a separate EC2 instance optimized for: processing Latex using TexLiv, creating a PNG, saving PNG to S3, and then returning a URL for the image. I also need to communicate with my existing Django ORM to update the object's image URL with the one just created on the dedicated machine. I have several questions: 1) what kind of EC2 instance should I use (computer or memory optimized?) 2) what kind of web server should I use on this dedicated Latex processing machine (is this a microservice?) Django, Tornado, Flask? 3) How do I get my existing project to communicate with new, dedicated Latex processing machine. 4) anything else I might be missing Thanks -
Django debug toolbar 1.8 offline mode
I started using django debug toolbar 1.8 in project with django 1.11.17, everything goes well until I tried to used it from home (is not showing at all) where I don't have internet, that is the only difference I can think off. Any ideas? -
AttributeError: 'TestimonyForm' object has no attribute 'save'
Help needed. I have no idea what is error-ed in the line of code. The traceback points to the form.save() line. #views.py class TestimonyFormFunction(View): form = TestimonyForm template = 'variablized_form.html' @method_decorator(login_required) def get(self, request): form = self.form_class(None) return render(request, self.template, {'form':form}) def post(self, request): if request.method == 'POST': form = TestimonyForm(request.POST, request.FILES) if form.is_valid(): form.save() return render(request, 'testimony_post.html', {'Testimony':Testimony}) else: form = TestimonyForm() return render(request, 'variablized_form.html', {'form': form}) -
django-tables2: Table.render_Foo naming
I got the following Table and want to implement a render_foo() function for the modelField.ST and modelField.ZF fields. 34 class MyTable(Table): 35 class Meta: 36 model = MyModel 37 fields = ('modelField.ST', 'modelField.ZF', 'score' ) How are they named? def render_modelField_ST(self,record) and def render_modelField__ST(self,record) did not work Thank you! -
validation for date field
i have override date format in django modelform widget and jquirey datepicker, it given error that field is not valid class Sale_Invoice_Main_Page(forms.ModelForm): class Meta: model = SaleInvoice fields = '__all__' exclude = ['created_at','updated_at','transiction_type'] widgets = {'description' : forms.TextInput(attrs={ 'placeholder' : 'description'}), 'invoice_no' : forms.TextInput(attrs={ 'readonly' : 'True'}), 'total_amount' : forms.TextInput(attrs={ 'readonly' : 'True'}), 'invoice_date' : forms.DateInput(attrs={ 'class' : "vdate" },format=('%d-%m-%Y')), 'due_date' : forms.DateInput(attrs={ 'readonly' : "True" },format=('%d-%m-%Y')), } class SaleInvoice(models.Model): customer = models.ForeignKey(Customer_data , on_delete=models.CASCADE) invoice_date = models.DateField(null=True,blank=True) invoice_no = models.PositiveIntegerField(unique=True) due_date = models.DateField(blank=True,null=True) address = models.TextField() total_amount = models.PositiveIntegerField(null=True,blank=True) description = models.TextField(null=True,blank=True) transiction_type = models.CharField(max_length=50,blank=True) author = models.CharField(max_length=30) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.address jquirey date picker {# Date Picker#} <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> <link rel="stylesheet" href="/resources/demos/style.css"> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <script> $( function() { $( ".vdate" ).datepicker({ dateFormat: "dd-mm-yy" }); } ); </script> i want to find what is i am doing wrong that it is given validation error -
Referencing search groups in Django's RegexValidator
I have a regex validator which has a named search group. Something like this: my_validator = RegexValidator(r'^[a-zA-Z0-9]*/(?P<pk>[0-9]*)$') Now, I use this to check patterns. Something like this: search = my_validator('articles/421') search.group('pk') The last line returns an error: AttributeError: 'NoneType' object has no attribute 'group' Why is this? Is a RegexValidator different from normal regexes, in the sense that it does not have groups? -
customize implementation of multiple databases in django
i am begginer in django. i wanted to develop an web app that choose database after user authentication or at user authentication.. ie. i am having a business which have multiple branches so i would like to give functionality that each branch can have different database so that my database could be distributed.. and one master login which can access all the databases united... so models, templates even all databases will have same tables but the only data will be distributed.. i want dropdown for selection of branch at user authentication page.. or it will do automatically recognized which user is from which branch is there any way to do these kind of functionality?? -
Django-Python strategic game between human and computer
I am working on a project which aims to develop a web-based game. My plan is to use Django framework along with some other Python APIs such as gurobi, cplex, or ortools. The game is played as follows: There are two players: the human user and the computer. The user chooses a game setting, including the number of rounds the game will be played. Before the game begins, the computer receives the game setting and generates its prior belief about the user's certain preferences on the game. Moves in each round are made simultaneously. In each round, the user chooses his/her strategy and the computer generates its strategy by solving a linear programming problem. The computer makes use of previous moves of the user to update its prior belief to generate better strategies. The computer's belief is an input for the linear programming problem in each round. As the round played, the user is informed about the computer's strategy, so he/she can adjust his/her strategy accordingly. During the game, the page will not be loaded again. Apparently, for each round, two way information flow occurs. In a given round, server needs to solve the linear programming problem that triggered by … -
amazon elasticbeanstalk vs s3 for django static files
As I see in aws django guides, I should configure django collectstatic command to copy static files to amazon s3 storage. I see that in the elastic beanstalk configuration I can set a static path to configure a the proxy server to serve static files directly from the webapp folder. As described here under "static files": https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-container.html The question: what is the difference between the two methods, i.e serving static files from s3 or using the eb configuration. Does one method has a better performance over the other? -
How should I POST and serialize and array of arrays with DRF?
I'm having an issue POST-ing a JSON object that contains and array of arrays and deserializing it using Django Rest Framework. The idea here is that there can be a dynamic number of players (players: 2) and a list of lists/array of arrays of weapons that the players have (player_weapons [[], []]). //javascript on client var post_data = { players: 2, player_weapons: [ ["sword", "shield"], ["mace", "slingshot"], ]}; var results = jQuery.post( url, post_data ); #serializers.py class GameSerializer(serializers.Serializer): players = serializers.IntegerField(min_value=1) player_weapons = serializers.ListField( child=serializers.ListField( child=serializers.CharField(min_length=1, allow_blank=True), min_length=0, required=False), min_length=0, required=False ) The request.POST I get is: <QueryDict: {'runs': ['1000'], 'additional_players': ['2'], 'player_weapons': ['sword,shield', 'mace,slingshot']}> What's really weird is that when I do request.POST['player_weapons'] I get: mace,slingshot whereas I'm expecting/hoping to get: [['sword', 'shield'], ['mace', 'slingshot']] Any help on how I should be structuring the POST and handling it in DRF would be awesome. -
Django - create CSV on the fly and save it to filesystem and model file field
In my django app, I have a management command which I want to use to process some data and create a model instance as well as file in filesystem and save its path to above instance's file field. My management command: import datetime import timy from django.core.management.base import BaseCommand import tempfile from core.models import Entry from np_web.models import Dump import calendar import csv class Command(BaseCommand): help = 'Create dump and file for current day' def handle(self, *args, **options): with timy.Timer() as timer: today = datetime.date.today() dump_title = '{}.{}.{}.csv'.format(today.day, today.month, today.year) entries = Entry.objects.all() dump = Dump.objects.create(all_entries=entries.count()) dump.save() print('Dump created with uuid:', dump.uuid) print('Now create data file for dump') with tempfile.NamedTemporaryFile() as temp_csv: writer = csv.writer(temp_csv) writer.writerow([ 'Column1', 'Column2', ]) for entry in entries: writer.writerow([ entry.first_name, entry.last_name ]) dump.file.save(dump_title, temp_csv) My Dump model: class Dump(BaseModel): created = models.DateField(auto_now_add=True) all_entries = models.PositiveIntegerField() file = models.FileField(verbose_name=_('Attachment'), upload_to=dump_file_upload_path, max_length=2048, storage=attachment_upload_storage, null=True, blank=True) Anyway, it doesn't work. It is throwing an error: TypeError: a bytes-like object is required, not 'str' I am also not sure if using temporary file is a best solution out there. -
ajax django form to submit just a partial of data
I have a form, that is standard django. Fill it out send it off goes to a different page upon success..shows errors if you don't fill out portions. Now I have a modal form that will pop up to fill out some extra data. I have decided to try to my hand at ajax for this. I have some of it working: Inside the class that is an UpdateView: def post(self, request, *args, **kwargs): if self.request.POST.has_key('group_info_submit') and request.is_ajax(): print("YOU SURE DID SUBMIT") return HttpResponse("hi ya!") The problem is it always redirects to a different page, and fails validation anyway because the form the modal pops over is not complete and trying to be submitted. I saw this post here: Ajax Form Submit to Partial View This seems overly complicated, I just have a small div in my form that is a modal div that I would like to submit sort of separately from the rest... The java script I have in the code: $.ajax({ data: $("#groupinfoForm").serialize(), success: function(resp){ alert ("resp: "+resp.name); } }) Then the little modal html snippet is: <div class="container"> <div id="groupinfo-dialog" class="modal" title="Group Information" style="display:none"> <div class="modal-dialog"> <h1> Group Information </h1> <div class="modal-content"> <div class="modal-body"> <form action="." … -
Reroute import pathes in django
I want to use a django app (newapp) in my django project. To keep it simply updated, I would like to include it as git submodule, but this will lead to a folder structure like: myproject |-app |-newapp-git |-newapp |-settings.py |-urls.py |-... |-README.md That is because, newapp is unfortuntely not only the appfolder but also some files (like readme) and the subfolder newapp. I can add this in INSTALLED_APPS with newapp-git.newapp, but the app itself imports models etc. with import newapp which does not work, and I cannot change it because I dont want to modify the content in newapp to keep it updated simply. So, is there a chance to tell django, that imports from newapp should be rerouted to newapp-git.newapp? -
How to set tag max length
Have my app up and running with django (1.11), django-taggit (0.22.2) and taggit-selectize (2.6.0). However, some users seem to prefer long sentence like tags instead of using multiple short tags. Anyway of limiting the tag length? -
Django: correct way to pass AJAX
I've a view that recives parameters from the frontend via AJAX. I've passing AJAX parameters in a maner, but this time my way didn't work. I've asked a friend for help, and he send me another way of sending AJAX data. To my untrained eyes they both work equal. So I don't know why mine does not work: Why? My friend's AJAX: <script> $("#id_shipping_province").change(function () { var val_d = $("#id_shipping_department").val() var val_p = $("#id_shipping_province").val() $.ajax({ url: "/district/?d_name=" + val_d + "&p_name=" + val_p }).done(function (result) { $("#id_shipping_district").html(result); }); }); </script> My AJAX: <script> $("#id_shipping_province").change(function () { var val_d = $("#id_shipping_department").val() var val_p = $("#id_shipping_province").val() $.ajax({ url: "/district/", d_name: val_d, p_name: val_p }).done(function (result) { $("#id_shipping_district").html(result); }); }); }); </script> View def get_district(request): d_name = request.GET.get("d_name") p_name = request.GET.get("p_name") data = Peru.objects.filter(departamento=d_name, provincia=p_name).values_list("distrito", flat=True) # data = Peru.objects.filter(provincia=p_name).values_list("provincia", flat=True) return render(request, "accounts/district_dropdown.html", { "districts": set(list(data)) }) -
Postgres query to Django ORM
I want to do this query bellow in django orm, i've tried to do with the queryset example and it doesn't work, always returns the error, i want to know if is possible to solve this. I think the problem migth be GROUP BY, and the Django ORM doens't do the GROUP BY, but this it is just a guess. error: Traceback (most recent call last): File "C:\Python35\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Python35\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Python35\lib\site-packages\django\core\handlers\base.py", line 124, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Python35\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "C:\Python35\lib\site-packages\rest_framework\viewsets.py", line 116, in view return self.dispatch(request, *args, **kwargs) File "C:\Python35\lib\site-packages\rest_framework\views.py", line 495, in dispatch response = self.handle_exception(exc) File "C:\Python35\lib\site-packages\rest_framework\views.py", line 455, in handle_exception self.raise_uncaught_exception(exc) File "C:\Python35\lib\site-packages\rest_framework\views.py", line 492, in dispatch response = handler(request, *args, **kwargs) File "C:\Python35\lib\site-packages\drf_multiple_model\mixins.py", line 112, in list data = query_data['serializer_class'](queryset, many=True, context=context).data File "C:\Python35\lib\site-packages\rest_framework\serializers.py", line 765, in data ret = super(ListSerializer, self).data File "C:\Python35\lib\site-packages\rest_framework\serializers.py", line 262, in data self._data = self.to_representation(self.instance) File "C:\Python35\lib\site-packages\rest_framework\serializers.py", line 683, in to_representation self.child.to_representation(item) for item in iterable File "C:\Python35\lib\site-packages\django\db\models\query.py", line 268, in __iter__ self._fetch_all() File "C:\Python35\lib\site-packages\django\db\models\query.py", line 1186, in _fetch_all self._result_cache = list(self._iterable_class(self)) File … -
NoReverseMatch: Reverse for 'details' with arguments '('',)' not found. 2 pattern(s) tried:
I can't seem to spot the error in my code and I have tried everything. It is probably something simple that is escaping my eye. Please help! Any imput is appreciated. New Django learner here. #views.py def details(self, Testimony_id): Testimony=get_object_or_404(Testimony, pk= Testimony_id) return render(request, 'details.html', {'Testimony': Testimony}) #template <header class="w3-container w3-blue"> <h1><a href="{% url 'Testimony:details' Testimony.id %}">{{Testimony.Title}}</h1> </header> #urls.py app_name='Testimony urlpattern=[ ... re_path('<int:id>/', views.detail, name='details'),] #models.py class Testimony(models.Model): ... def get_queryset(self): return Testimony.objects.all() def __str__(self): return self.title def __str__(self): return str(self.id)