Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to implement a connection pool in web application like django?
The purpose is to implement a pool like database connection pool in my web application. My application is write by Django. The problem is that every time a http request come, my code will be loaded and run through. So if I write some code to initiate a pool. These code will be run per http request. And the pool will be initiated per request. So it is meaningless. So how should I write this? -
Why am i getting an error when running sudo ./build.sh?
Could not find a version that satisfies the requirement pdb (from -r ./config/requirements.pip (line 37)) (from versions: ) No matching distribution found for pdb (from -r ./config/requirements.pip (line 37)) The command '/bin/sh -c pip3 install -r ./config/requirements.pip' returned a non-zero code: 1 How can i fix this issue? -
django-bootstrap3 Parameter "field" should contain a valid Django BoundField?
I am using django-bootstrap3 to render my forms on the template and i have been struggling to find what is causing the error Parameter "field" should contain a valid Django BoundField when i try to load the page with the form on it. I have attached my code and error below. can someone please point for me what i'm doing wrong? forms.py views.py template browser error -
Tracing API in flask
I have a following front-end code in js(/ember/create/app/components/someFile.js): component.$('.city-select-autocomplete').marcoPolo({ url: '/api/objects/cities', data: {range_size: 8, order_by: '-population'}, minChars: 3, required: true, param: 'search', formatData: function (data) { return data.cities.sortBy('population').reverse(); }, formatItem: function (data, $item) { var state = data.country_code === 'US' ? data.admin1_code + ', ' : ''; return data.name + ', ' + state + data.country_code; }, I am trying to find out where the implementation(server code) is written for url "/api/objects/cities". I tried searching URL mappings but couldn't find it. Project structure: config/ controllers/ deploy/ docs/ ember/ env/ models/ static/ tasks/ templates/ tests/ tools/ utils/ vacuum/ web/ serve.py .. .. .. There must be some url mapping with ("/api/objects/cities") using @app.route annotation but I wasn't able to find it. There must be some convention. api/objects is constant but the last part obj_type varies so there must be a method with the name "cities" and it might be matching by method name. /api/objects/ maps to method with name ? Right ? But I am not finding any such method in controller/web folder. -
config:push is not a heroku command. Perhaps you meant config. How to solve?
When I am typing : heroku config:push I am getting error as config:push is not a heroku command. ▸ Perhaps you meant config ▸ Run heroku help config for a list of available ▸ topics. What should I do ? -
Pass multiple email addresses into exchangelib
I am usng exchangelib in conjunction with Django 1.11 to manage Calendar items. Can anyone provide any guidance on the best way to pass emails to the required_attendees of CalendarItem in my views.py file? required_attendees = [Attendee(mailbox=Mailbox(email_address='user1@example.com'), response_type='Accept')] The number of emails could be from zero to many, eg: required_attendees = [Attendee(mailbox=Mailbox(email_address='user1@example.com'), response_type='Accept'), Attendee(mailbox=Mailbox(email_address='user2@example.com'), response_type='Accept')] At the moment I am repeating code using IF statements based on the length of a list containing all the email addresses. It works but obviously is not the correct way to do it and is very inelegant code. Any guidance will be greatly appreciated! Cheers -
Integrate IDE into Django website
Is there a way to integrate an IDE into a python Django website and have the program created in sed IDE run 24/7 and have the output from the program appear in real time? -
When I register a user, there is no password field on the page
When I register a user, there is no password field on the page: You see, there only Username and Email here, no password. My Serializers.py code: class UserCreateSerializer(ModelSerializer): """ 用户注册 """ class Meta: model = User fields = [ 'username', 'email', 'password', ] extra_kwargs = { "password":{"read_only":True} } def create(self, validated_data): username = validated_data["username"] email = validated_data["email"] password = validated_data["password"] user_obj = User( username = username, email = email, ) user_obj.set_password(password) user_obj.save() return validated_data My views.py code: # 普通用户注册 class UserCreateAPIView(CreateAPIView): serializer_class = UserCreateSerializer queryset = User.objects.all() -
`::=` and `|` in Documentation
There are ::= everywhere in Python Documentation: For instance: atom ::= identifier | literal | enclosure I searched and learned it's BNF syntax. It's really not easy to get a brief idea from dozens of files. In python : can be considered as a variant of 'assignment' symbol =, In Django's template syntax ,| is function symbol. What are ::=and | in BFN? -
I have set the Project Interpreter to `python 3.5.2`, but seems the my project still use `python 2.7`
I have set the Project Interpreter to python 3.5.2, pay attention there are two packages only python 3.5.2 have: but seems the my project still use python 2.7, when I runserver: the traceback: File "/Library/Python/2.7/site-packages/Django-1.11.2-py2.7.egg/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/Library/Python/2.7/site-packages/Django-1.11.2-py2.7.egg/django/apps/config.py", line 94, in create module = import_module(entry) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) ImportError: No module named rest_auth -
Django REST Framework updated nested object not in Model
I only want to update all order in my_stage by using PUT, something like: "Payload": { "stages": [ { "stage_id": 1, "position": 2 }, { "stage_id": 2, "position": 3 }, { "stage_id": 3, "position": 4 } ] } and "Response": { "stages": [ { "stage_id": 1, "position": 2 }, { "stage_id": 2, "position": 3 }, { "stage_id": 3, "position": 4 } ] } But I don't have "stages" in my model so I cannot use ModelSerializer. But I have to implement create() first. So what should I do to implement update? Thank you. My stage model is: class Stage(models.Model): class Meta: db_table = 'stage' position = models.IntegerField() Here are my serialzier.py class StagePositionSerializer(ModelSerializer): """Serialize order""" # company_id = IntegerField(read_only=True) stage_id = IntegerField(source='id', read_only=True) position = IntegerField(min_value=0) class Meta: model = Stage fields = [ 'stage_id', 'position' ] class PositionSerializer(Serializer): stages = StagePositionSerializer(many=True) and my view.py class StagePositionListView(APIView): serializer_class = PositionSerializer -
Cant migrate changed models.py initial - django
I created a new django project. I have a models.py file. I added a handful tables to the file. Now I am trying to migrate it so that I can start updating the project. I am trying to run the following lines but it is saying that there are no changes detected even though the file has changed. Comars-mbp:Yap omarjandali$ python3 manage.py makemigrations No changes detected omars-mbp:Yap omarjandali$ python3 manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions Running migrations: No migrations to apply. omars-mbp:Yap omarjandali$ omars-mbp:Yap omarjandali$ python3 manage.py runserver Performing system checks... System check identified no issues (0 silenced). November 08, 2017 - 02:52:28 Django version 1.11.5, using settings 'Yap.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. this is the table added to the models.py from __future__ import unicode_literals from django.db import models from django.contrib.auth.models import User from django_localflavor_us.models import USStateField #-------------------------------- # the following are tables realted to the app and general information #-------------------------------- # Profile saves every users profile information class Profile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) # server first_name = models.CharField(max_length=25, default='first') last_name = models.CharField(max_length=25, default='last') bio = models.CharField(max_length=220, default='bio') dob = models.DateField(default='1950-01-01') street = models.CharField(max_length=200, default='street address') city = … -
How to update profile pic in DRF
I have created an api where one can upload pic for profile along with rest of the details. My problem is that if one wants to change the pic, how can it be done. At present, I am able to save pic for the first time. models.py class Profile(models.Model): User = get_user_model() branch = models.CharField(max_length=20, null=True) year = models.IntegerField(null=True) image = models.ImageField(upload_to="accounts/images/", null=True, blank=True) user = models.OneToOneField( User, on_delete=models.CASCADE, primary_key=False, null=True ) views.py class ProfileView(APIView): permission_classes = (IsAuthenticated,) serializer_class = ProfileSerializer queryset = Profile.objects.all() def post(self, request, format=None): current_user = request.user param = request.data profile = Profile.objects.filter(user=current_user.pk) if profile: serializer = ProfileSerializer(profile, many=True) return Response(serializer.data) else: serializer = ProfileSerializer(data=param) if serializer.is_valid(raise_exception=True): serializer.save(user=current_user) new_data = serializer.data return Response(new_data) return Response(serializer.errors, status=HTTP_400_BAD_REQUEST) -
Ajax issue of Django user login using bootstrap 3.x modal
My purpose is once modal form submitted, ajax pass the username and password to a view and get back the json info to update the modal form, I trace the djanog code ,and 100% sure the JsonResponse(rsdic) has been executed in server side, as well as client fully receive the son info with ajax success function. The problem is how to update the #error_message1 field which embeded in model. I tried .html() or .append(), all failed. I leave the core coding for your reference, many thanks again for your help again. ajax component: $.ajax( { type: "POST", url: url, data: { 'username': username, 'password': password }, dataType: 'json', success: function(data){ $('#login-form')[0].reset(); if (data.ret != '1107'){ var htmlcode ="<p> data.info </p>"; $('#modal').find('.error_message1').append(htmlcode); } }, error: function (data) { console.log('An error occurred.'); console.log(data); }, }); html component: <div class="modal fade" id="modal"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div id="form-modal-body" class="modal-body"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times</button> <h4>EXP LOGIN</h4> <form role="form" action="{% url 'auth_login' %}" method="post" id="login-form"> {% csrf_token %} <ul> <li> <div class="g-icon"><i class="iconfont icon-yonghu"></i></div> <input type="text" name="username" id="username" value="" placeholder="User name" /> </li> <li> <div class="g-icon"><i class="iconfont icon-mima"></i></div> <input type="password" name="password" id="password" value="" placeholder="Password" onblur="check1()" /> <div class="g-cue" id="error_message1">Your email or password was … -
Django - If one model field exists, another field must be empty/inaccessible
I have a model called Team. Team has one User as team_leader and can have multiple team_member's. Under User, I added the following fields: class User(AbstractUser): team_leader = models.OneToOneField(Team, null=True, blank=True) team_member = models.ForeignKey(Team, null=True, blank=True) Obviously a User shouldn't be a team_leader and team_member at the same time. I have set both fields as null/blank so I can always just leave one of them blank. However for extra precaution I'd like to completely disable one of these fields when the other field is activated. I'm aware of the disabled function, but it is only for disabling the field on a form. I want to eliminate any chance of tampering by completely disabling one model field. Is there a way to do this? -
Receiving data from the server without updating the page
Good day! I'll Forgive Forgiveness, I'm zero in programming. But I want to learn. I need to transfer data using the POST method, without updating the page. Through django, how should the javascript and views.py look like! <form class="form-horizontal" role="form" method="post" id="lol"> <div class="form-group"> <label for="" class="col-sm-2 control-label">ФИО</label> <div class="col-sm-4"> <input name="firstname" class="form-control" placeholder="ФИО"> </div> </div> <div class="form-group"> <label for="" class="col-sm-2 control-label">Шифр Группы</label> <div class="col-sm-4"> <input name="Code" class="form-control" placeholder="Шифр Группы"> </div> </div> <div class="form-group"> <label for="" class="col-sm-2 control-label">Пол</label> <div class="col-sm-4"> <input name="Pol" class="form-control" placeholder="М или Ж"> </div> </div> <div class="form-group"> <label for="" class="col-sm-2 control-label">Семейное положение</label> <div class="col-sm-4"> <input name="Floor" class="form-control" placeholder="0 или 1"> </div> </div> <div class="form-group"> <label for="" class="col-sm-2 control-label">Номер комнаты</label> <div class="col-sm-4"> <input name="Room" class="form-control" placeholder="Номер комнаты"> </div> </div> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <button type="submit" class="btn btn-default">Войти</button> </div> </div> </form> <div class="examples"> <script language="javascript" type="text/javascript"> </script> <div class="results">Ждем ответа</div> @csrf_exempt def polls(request, form=None): if request.method == 'POST' and form.is_valid(): pass else: return render(request, 'base.html') -
Most practical and efficient way to filter objects in Django?
What is the best approach to filter objects in Django? In my case, I need to filter objects by different params sent by GET request. So, in my get_queryset of CBV I send the values to the custom function of my custom models.QuerySet and retrieve the result: return MyModel.objects.all().custom_filter(param1, param2, param3) But in my custom function, the most doubtful things happening. At first, I check passed values for existence and clean them. Then, separately for every param I filter queryset using Q Objects. In custom models.QuerySet it looks like: def custom_filter(self, param1, param2, param3): # cleaning and checking staff # ... then result = self.filter(Q() | Q()) # related to param1 if (param2 != None): result = result.filter(Q()) # related to param2 if (param3 != None): result = result.filter(Q() & Q()) # related to param3 # and etc. return result.distinct() This works fine for that time. But I think it is definitely inefficient. If anyone has a better solution, please provide it. -
Run django shell in ipython
I attempt to run django shell in ipython. ipython manage.py shell # It report error: Type 'manage.py help <subcommand>' for help on a specific subcommand. I searched and found a popular solution which guides you to install django.extensions and to enable it in settings. I am creating a minimal project while the solution is heavy. Meanwhile,I have to install and enable it on every project. Is there a lightweight way? -
What is the appropriate way to add HTML to the top of a Django ModelForm/formwizard?
I'm putting together a long, multi-page application using ModelForm and formwizard. For some of the pages, I would like to add a short introductory paragraph to the form. What is the appropriate way to do this? The best method I can figure out is to add custom templates to each page and enter the HTML that way. It seems like there should be another method, though! If I just need to add a tag, it seems like bad practice to create an entire template. -
Add CSS Class to Django-Autocomplete-Light ModelSelect2
I have a model form that is made up largely of django-autocomplete-light ModelSelect2 boxes: class AlertForm(ModelForm): class Meta: model = Alert fields = '__all__' widgets = { 'entity': ModelSelect2(url='eda', attrs={'data-minimum-input-length': 2}), 'logic': ModelSelect2(url='logic', attrs{'class':'hello'} The CSS class hello which I am attempting to add to the logic select box does not appear when the page is rendered. How do I add a CSS class to a dal select box? -
Pip having trying to uninstall appdirs while trying to install requirements.txt when deploying to pythonanywhere
I am trying to deploy my project on pythonanywhere. I have created my virtualenv and activated it but when I try to "pip install -r requirements.txt" it says "Found existing installation: appdirs1.4.2 Uninstalling appdirs-1.4.2:" and then gets a permission denied error. What's going on and how do I fix it? Full error in bpaste: https://bpaste.net/show/a7394c84c672 -
Django/WeasyPrint: Bangla Font Rendering Issue
My Python Version 3.6+, Django version 1.11.6 and OS: Windows-10 64bit. I am creating the PDF file with weasyprint within Django project. But the problem is Bengali font is not rendering. Please check this screenshot. Now this is my views.py file def get_pdf_file(request, customer_id, sys_type): sys_type = customer_id area = "pdf" site_credit = site_credit1 time_now = timezone.now() customers = get_object_or_404(CustomerInfo, pk=customer_id) due_taka_track = customers.duetaka_set.all() if due_taka_track == None: due_taka_track = 0 unpaid_taka = int(customers.customer_price - customers.customer_due_taka_info) due_taka_track = customers.duetaka_set.all() sum_cost_taka = due_taka_track.aggregate( sp=Sum('customer_due')).get('sp', 0) if sum_cost_taka == None: sum_cost_taka = 0 total_paid_taka = sum_cost_taka + customers.customer_due_taka_info payment_status = 'complete' payment_message = ' ' remain_taka='Full Paid ' remain_msg='' if customers.customer_due_taka_info < customers.customer_price: payment_status = 'incomplete' payment_message = 'সম্পূর্ন টাকা পরিষোধ করা হয়নি' remain_msg='টাকা বাকী আছে' baki_ase="পাওনা আছে " remain_taka = customers.customer_price - customers.customer_due_taka_info context = {'customers': customers, 'sys_type': sys_type, 'area': area, 'site_credit': site_credit, 'site_name': 'Moon Telecom', 'sys_type': sys_type, 'due_taka_track': due_taka_track, 'total_paid_taka': total_paid_taka, 'payment_message': payment_message, 'time_now': time_now, 'unpaid_taka': unpaid_taka, 'payment_message': payment_message, 'remain_taka': remain_taka, 'sum_cost_taka': sum_cost_taka, 'remain_msg': remain_msg} html_string = render_to_string('shop/pdf_invoice.html', context).encode(encoding="UTF-8") response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'inline; filename=invoice' + \ str(customers.id)+customers.customer_uid + customers.customer_name + '.pdf' HTML(string=html_string).write_pdf(response) return response and this is my html file <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-16"> <meta … -
Django - best way to replace custom image tag in textfield by imagefield
What is best way to replace custom "tag" (for example [IMG]image_name[/IMG]) with image url what exist in model as imagefield? For example: class ImageResource(models.Model): name = models.CharField(verbose_name='Name') img = models.ImageField(verbose_name='Image') class Post(models.Model): title = models.CharField(verbose_name='Title') text = models.TextField(verbose_name='Text') images = models.ManyToManyField(ImageResource,verbose_name="Images") DetailView to display template like this: {{ object.text }} I will replace all [IMG]name[/IMG] in object.text to html img code who has src = images.url when images.name == name only. I don't want use wysiwyg editor. I don't know what is best place to do this - on model, view (what function?) or in specific filter? -
Django Populate Hidden Input with request.user.get_username()
I have a model: class Alert(models.Model): entity = models.ForeignKey(Entity, on_delete=models.CASCADE, db_column='entity') group = user = models.CharField(max_length=12) #...More Fields def __str__(self): return '%s' % self.entity I have a corresponding model form and model formset rendered by crispy-forms: class AlertForm(ModelForm): class Meta: model = Alert fields = '__all__' widgets = { 'dispositionedBy': HiddenInput(), 'entity': ModelSelect2(url='eda', attrs={'data-minimum-input-length': 2}), AlertFormSet = modelformset_factory(Alert, extra=1, exclude=(), form=AlertForm) I have a view built on top of the formset: def alerts(request): helper = AlertFormsetHelper() if request.method == 'POST': formset = AlertFormSet(request.POST) for form in formset: if form.is_valid(): if form.has_changed(): if form.is_valid(): form.save() entity = form.cleaned_data['entity'] messages.success(request, 'SUCCESS: Alert for %s was dispositioned' % entity) return redirect('alerts') else: query = Alert.objects.filter(disposition='') paginator = Paginator(query, 12) page = request.GET.get('page') try: objects = paginator.page(page) except PageNotAnInteger: objects = paginator.page(1) except EmptyPage: objects = paginator.page(paginator.num_pages) page_query = query.filter(id__in=[object.id for object in objects]) formset = AlertFormSet(queryset=page_query.order_by('entity')) context = {'objects':objects, 'formset':formset, 'helper':helper} return render(request, 'alerts/alerts.html', context) I would like user to be populated by the current REMOTE_USER username that can be accessed with request.user.get_username(). user.get_username is performing correctly in my template and showing the current user. However, when I attempt to automatically populate the field and POST the data to the DB, the record … -
django inheritence admin site -- why do fields follow down the tree automatically whereas fields that are defined classes do not?
django inheritence admin site -- why do fields follow down the tree automatically whereas fields that are defined classes do not? I've been searching for the answer for several hours and this is my first question so please be gentle. here is my models.py from django.db import models import datetime from django.db.models import EmailField class XObj(models.Model): auto_increment_id = models.AutoField(primary_key=True) creation_date = models.DateTimeField(default=datetime.datetime.now) def __str__(self): return str(self.creation_date.datetime) def date_created(self): return self.creation_date def date_last_change(self): return str(self.auto_increment_id) class Address(XObj): # todo: differentiate between US and non US addresses and validate house = models.CharField(max_length=20, default="") street = models.CharField(max_length=200, default="") street2 = models.CharField(max_length=200, default="") city = models.CharField(max_length=200, default="") state = models.CharField(max_length=200, default="") zipcode = models.CharField(max_length=200, default="") country = models.CharField(max_length=200, default="") def __str__(self): return str(self.house, self.street, self.street2, self.city, self.state, self.zipcode, self.country) class Entity(XObj): full_name = models.CharField(max_length=200, default="") # todo: validate email email = EmailField() # def _init_(self): # self.full_name = models.CharField(max_length=200, default="") # def __str__(self): return "Entity" class Person(Entity): first_name = models.CharField(max_length=200, default="") last_name = models.CharField(max_length=200, default="") address = Address # def _init_(self): # self.first_name = models.CharField(max_length=200, default="") def __str__(self): return self.full_name class Vendor(XObj): name = models.CharField(max_length=200, default="") address = Address website = models.URLField point_of_contact = Person def __str__(self): return self.name class Hotel(Vendor): def __str__(self): return …