Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to filter manytoone relationship
I have a one to many relationship with category and products, category and product have active fields, once it not active I want to exclude from list. Categories and products, I can do that for categories: categories = Category.objects.filter(is_active=True) But now category can have many products, and some of them are inactive, how could I filter and exclude inactive products from all of categories ? -
How to render Django CharField?
I have a list of dynamically created Charfields in a form but I can't figure out how to render the actual input (in this case a textarea). This is the (simplified) loop: {% for field in form.implementation_fields %} <label class="col-sm-2 col-form-label"> {{ field.label }} </label> <div class="col-sm-10"> {{ field }} </div> {% endfor %} {{ field.label }} works fine, but {{ field }} just prints: django.forms.fields.CharField object at 0x104e7fb50 -
Can't login to admin site. Returns a page not found error
I am trying to host my website at a2hosting shared hosting plan. I was told to use cpanel to create a virtualenv and then, use passenger to run django. My virtualenv folder and project folder are in the root directory. After setting everything and running collectstatic and creating a superuser, I tried going to the django admin site. I get the login page, however, trying to login results in a page not found error. It states: Page not found (404) Request Method: POST Request URL: https://www.website.com/admin/login/?next=/admin/ Raised by: django.contrib.admin.sites.login Using the URLconf defined in readerspoint.urls, Django tried these URL patterns, in this order: 1) admin/ The empty path didn't match any of these. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. I trired looking at the CPanel errors, here is what it states: WARNING: /home/username/public_html/admin/login: Can't access file /home/username/public_html/admin/login: No such file or directory WARNING: /home/username/public_html/admin/login: Can't access file /home/username/public_html/admin/login: No such file or directory WARNING: /home/username/public_html/admin: Can't access file /home/username/public_html/admin: No such file or directory [ N 2018-02-28 18:53:10.6076 766038/T1 age/Cor/CoreMain.cpp:994 ]: Checking whether to disconnect long-running connections for process … -
Django - include an extra field in a model form that needs to get a value through init?
I have a modelform, using crispy forms below that I would like to add an extra field to. ive seen examples where the extra field is created under the main class. however I believe I need to use init to get the site_id from my url in order to filter the query that generates the subnet choices. Currently the form just has a blank space where the checkboxes for related subnets should be. class DeviceForm(forms.ModelForm): class Meta: model = DeviceData fields = ['site_data', 'switches', 'hostname', 'template', 'model', 'install_date','ospf_area','snmp_data'] def __init__(self, *args, **kwargs): site_id = kwargs.pop('site_id', None) self.is_add = kwargs.pop("is_add", False) super(DeviceForm, self).__init__(*args, **kwargs) subnets = forms.ModelMultipleChoiceField( queryset=SiteSubnets.objects.filter(site_id=site_id), widget = forms.CheckboxSelectMultiple( attrs = {'class': 'form-control'} ) ) self.helper = FormHelper(self) self.helper.form_id = 'device_form' self.helper.form_method = 'POST' self.helper.layout = Layout( Div( Div( Field('hostname', placeholder='hostname'), Field('model', placeholder="Model"), Field('template', placeholder="template"), Field('install_date', placeholder="Install Date"), css_class='col-lg-3' ), Div( Field('ospf_area', placeholder='OSPF Area'), Div('snmp_data', title="SNMP Data"), Field('switches', placeholder='Switches'), css_class='col-lg-3' ), Div( Div('subnets', placeholder='Subnets'), css_class='col-lg-3' ), css_class='row' ), Div( Div( HTML("""<input type="submit" name="submit" value="""), HTML('"Add Device"' if self.is_add else '"Update Device"' ), HTML(""" class="btn btn-primary"/>"""), HTML("""<a href="{% url 'config:device_details' SiteID %}" class="btn btn-primary">Cancel</a>"""), HTML("""{% if object %} <a href="{% url "config:delete_device" object.id SiteID %}" class="btn btn-danger"> Delete <i class="fa … -
I cannot get django debug toolbar to appear in the browser. Project is attached
Its a very simple small project located here https://github.com/cbaldwin20/project_8/tree/master/project_eight I tried for like two hours to get the 'django debug toolbar' to appear in the browser with no success. I'm not sure if its my code or my computer. Thanks for any help. -
Parse more than one parameter value in serializers.IntegerField(validators=...)
I'm using django with mysql. In serializers.py I have: class UserWorseQuestListSerializer(serializers.Serializer): user_id = serializers.CharField(max_length=255, validators=[user_exists]) section_id = serializers.IntegerField(validators=[section_exists_in_completed_quest]) and my section_exists_in_completed_quest contains: def section_exists_in_completed_quest(section_id): if section_id is None: raise serializers.ValidationError('section_id must be specified') quest_ids = CompletedQuestion.objects.filter(question__section_id = section_id) \ .values_list("question_id", flat=True).distinct() #print (quest_ids) if not quest_ids: msg = 'Completed questions in Section {} were not found for user {}' raise serializers.ValidationError(msg.format(section_id)) My question is whether I can pass the value of user_id in section_exists_in_completed_quest() in someway. If I pass it like def section_exists_in_completed_quest(section_id, user_id): I get HTTP/1.1" 500 27 error. Can you help me please? -
How to properly use ListView and ContetMixin in Django
I am trying to use ListView and ContextMixin to create a view for this but I'm not sure if this is a right way to do it class ImplementView(generic.ListView): template_name = 'schedule/implement.html' context_object_name = 'all_implements' def get_queryset(self): return CourseImplementation.objects.all() def get_context_data(self, **kwargs): context = super(ImplementView, self).get_context_data(**kwargs) context['teacherid'] = TeacherCourseImplementation.objects.all() return context This is my models.py class CourseImplementation(models.Model): courseid = models.ForeignKey(Course, on_delete=models.CASCADE, db_column='courseid', ) roomid = models.ForeignKey('Room', models.DO_NOTHING, db_column='roomid', blank=True, null=True) note = models.CharField(max_length=10, blank=True, null=True) class Meta: managed = False db_table = 'course_implementation' def __str__(self): return self.pk + ' - ' + self.courseid class TeacherCourseImplementation(models.Model): teacherid = models.ForeignKey(Teacher, on_delete=models.CASCADE, db_column='teacherid', primary_key=True) course_impleid = models.ForeignKey(CourseImplementation, on_delete=models.CASCADE, db_column='course_impleid') p1 = models.IntegerField(blank=True, null=True) p2 = models.IntegerField(blank=True, null=True) p3 = models.IntegerField(blank=True, null=True) p4 = models.IntegerField(blank=True, null=True) p5 = models.IntegerField(blank=True, null=True) class Meta: managed = False db_table = 'teacher_course_implementation' unique_together = (('teacherid', 'course_impleid'),) def __str__(self): return self.pk + ' - ' + self.teacherid Can anyone help me on this. Thank you. -
Have bugs in session django
i have worked shopping cart. All settings completed: In settings.TEMLATES.OPTIONS.context-processors: 'apps.cart.context_processor.cart', 'apps.cart.context_processor.desires', In my context_processor.py: from apps.cart.cart import Cart from apps.cart.desires import Desires def cart(request): return {'cart': Cart(request)} def desires(request): return {'desires': Desires(request)} Desires will do almost the same thing as Cart with some differences Cart.py: import json from decimal import Decimal from django.conf import settings from apps.product.models import Item from apps.coupons.models import Coupon from django.forms.models import model_to_dict class Cart: def __init__(self, request): self.session = request.session cart = self.session.get(settings.CART_SESSION_ID) if not cart: cart = self.session[settings.CART_SESSION_ID] = {} self.cart = cart self.coupon_id = self.session.get('coupon_id') print(self.cart) def add(self, item, quantity=1, update_quantity=False): item_id = str(item.id) if item.discount > 0 : price_in_cart = item.get_price_with_discount() else: price_in_cart = item.price if item_id not in self.cart: self.cart[item_id] = {'quantity': 0, 'price': str(price_in_cart)} if update_quantity: self.cart[item_id]['quantity'] = quantity else: self.cart[item_id]['quantity'] += quantity item.quantity -= self.cart[item_id]['quantity'] item.save() self.save() def save(self): #update the session cart self.session[settings.CART_SESSION_ID] = self.cart #mark the session as "modified" to make sure it is saved self.session.modified = True def remove(self, item): item_id = str(item.id) if item_id in self.cart: item.quantity += self.cart[item_id]['quantity'] item.save() del self.cart[item_id] self.save() def __iter__(self): item_ids = self.cart.keys() items = Item.objects.filter(id__in=item_ids) for item in items: self.cart[str(item.id)]['item'] = item for item in self.cart.values(): item['price'] = … -
Use Textarea for CSVWidget with django-filter
I use django-filter to provide search form for a large dataset. It is for scientists who'd like to provide the sample IDs and get a filtered list. For that purpose I'd like to have <textarea> instead of <input type="text"> as they would just paste a dozen or more IDs at once and it would be good if they have overview of the submitted values. Here is my code: from django import forms import django_filters as filters class TextareaCSVWidget(filters.widgets.BaseCSVWidget, forms.Textarea): """ The widget should create textarea. """ pass class CharInFilter(filters.BaseInFilter, filters.CharFilter): """ The filter should accept coma separated strings. """ pass class SampleFilter(filters.FilterSet): sample_ids = CharInFilter( name='sample_id', widget=TextareaCSVWidget() ) Now the textarea is properly displayed. The search works as expected. However there is one weird issue: when I enter more than one value (separated by coma), after submitting the search form the textarea is replaced by <input type="text"> (the entered values are preserved). This looks very awkward and I need to prevent this behaviour. This doesn't happen if I enter a single value in the textarea. What's wrong with my approach? -
Asynchronous web scraping using selenium in python
i am trying to scrap the data on run time from a REP website. as rate changes on the site then values on my site should also change. any one have solution? appreciate your help. -
Django Rest framework with Custom query
I made API server using DRF. To customize list request, I wrote views.py like this. [views.py] class articleViewSet(viewsets.ModelViewSet): def list(self, request): queryset = article.objects.all() serializer = articleSerializer(queryset, many=True) return Response(serializer.data) But, When I execute runserver, It throws error. AssertionError: base_name argument not specified, and could not automatically determine the name from the viewset, as it does not have a .queryset attribute. Where is the error occured? -
Django Viewflow - Run the complete worflow
I've a workflow. class WorkFlow1(Flow): start = flow.StartFunction(function1) \ .Next(this.task2) task2 = flow.StartFunction(function2) \ .Next(this.end) end = flow.End() @flow_start_func def function1(activation, **kwargs): print('Func1 Called.') activation.prepare() activation.done() return activation @flow_start_func def function2(activation, **kwargs): print('Func2 Called.') activation.prepare() activation.done() return activation I am able to run the workflow programmatically using `WorkFlowClass.start.run()`. It starts the workflow perfectly, but, does not the completes it. Upon completing Node1(start) of workflow, task2 is not called. Meaning, only first task of the workflow is called, not the subsequent tasks. Why? And how can I execute the complete workflow? -
Django Python framework
I started with django python framework not long ago. The basic tutorials i had enabled me to set up a virtual environment, create a project and run the server. The project i did was a web template. In this project i was able to incorporate an external css and javascript by creating the "staticfile" and adding it to my app settings.As a newbie to the django framework i would be glad if anyone could suggest to me books, in-depth tutorials and other resources relevant to the study. Thanks in advance! -
django formset not validating because ID is required
MY view receives a model formset from the template, but it doesn't pass validation, claiming that ID is required. Al my use of forms until now has never brought up this problem, and I've never had to pass ID's around. Here is a simplified version of my view: def BudgetView(request): import pdb pdb.set_trace() if request.user.is_authenticated: U=request.user #initalize formset factories ItemFormSet = modelformset_factory(Item, fields=(blabla), extra=0) CatFormset=modelformset_factory(BudgetCatagory, fields=(blabla), extra=0) #initalize Constants InitiateConstants(CatagoryItemsList) if request.method=='POST': FormsetItem=ItemFormSet(request.POST,initial=Item.objects.filter(budgetcatagory__user_id=U.id).values()) FormsetCat=CatFormset(request.POST) if FormsetItem.is_valid(): -bla -bla -bla return redirect('/HighLevelInput') else: #populate I=Item.objects.filter(budgetcatagory__user_id=U.id) C=BudgetCatagory.objects.filter(user_id=U.id) #initiate initial catagories and items for new user if (not I.exists()) or (not C.exists()): Item.objects.filter(budgetcatagory__user_id=U.id).delete() BudgetCatagory.objects.filter(user_id=U.id).delete() InitiateNewUser(U) I=Item.objects.filter(budgetcatagory__user_id=U.id) C=BudgetCatagory.objects.filter(user_id=U.id) FormsetItem=ItemFormSet(queryset=I) FormsetCat=CatFormset(queryset=C) return render(request,'getdata/budgetmachine.html', {'FormsetItem':FormsetItem, 'FormsetCat':FormsetCat }) else: return redirect('/login') is_valid returns FALSE for the reason I've mentioned above. any ideas? Thx -
Export the current table view
I currently use the TableExport class of django-tables2 to provides a result of my table but when i filter my data, i still have the table not filter for export. How have the table filtered in my export ? view.py @login_required def visualiserGeneral(request): #create filter filterA = aFilter(request.GET, queryset=a) data = [] if request.method == "POST": fieldFilterA = request.POST.get('fieldFilterA') #Select fields to filter if(fieldFilterA): data = A.objects.filter("a_test_here_for_filtering"); #Create data to display data = createDataTableGeneral(data); if request.method == "GET": #Get data data = createDataTableGeneral(data); #Add data to the table table = GeneralTable(data); export_format = request.GET.get('report-generaltable', None) if TableExport.is_valid_format(export_format): exporter = TableExport(export_format, table,exclude_columns=('somes_exclude_columns')) return exporter.response('table.{}'.format(export_format)) return render(request, 'visualisation/page_bootstrap_general.html', {'table': table, 'filterA': filterA}) Thanks in advance. -
I have settings.py in my .gitignore yet it still changes it when I do git pull
I have a different settings.py for my local project and my live project (Bitbucket repo). So I have added settings.py to my .gitignore so when I make changes to either file, they don't get sent to the other repo when my git is pulled or pushed. However, I just did a git pull from my local repo - and it did a merge and changed the settings.py file to the Bitbucket settings.py. What is going on? Edit - Gitignore file: /lib /media .env /include /reports .DS_Store *.pyc celerybeat-schedule.db __pycache__/ db.sqlite3 log.django settings.py static/ /static -
HOW TO send webcam image to websocket in LAN
I have created server using djnago and use camera for send webcam image to server so i have used websocket ssl (https) and create certificate for this It NOT SECURE in chrome , it is working in localhost but it is not working in LAN , it immidiate disconnect from server (DJANGO ERROR ' "GET /favicon.ico HTTP/1.1" 404 2085 ') HOW to can i run website on LAN ? -
In django 1.11, how to allow users to login on a read-only database?
I have 2 instances each running its own postgres database. One is for production usage. The other is a read-only database that performs replication from the production database. Both instances run the same django 1.11 application codebase. When I attempt to login to the django read-only version, I cannot login because the very action of login apparently execute some update or insert statements. I get an internal error about read-only database: cannot execute INSERT in a read-only transaction What are my options if I want to allow users to access the read-only database using the same codebase? -
Changing template forms rendering to allow multiple selects
I have a Course model which has a many-to-many field to the Student model. I made an enroll and a disenroll forms for the student, problem is, I had to change how they are rendered and so, now I cannot do multiple select. Right now a button and a checkbox appear near each student name. Problem is, if I move the button outside of the loop, it will work still, for the last student selected and not for all selected.. So I need to change the template in order to work with multiple select but keep the rendering behaviour. course = Course.objects.get(slug=slug) if request.method == 'POST': course.student.add(*request.POST.getlist('student_ids')) course.student.remove(*request.POST.getlist('student_ids2')) return redirect('classroom') {% with crs_stud=course.student.all %} {% for student in students %} {% if student in crs_stud %} <form action="." method="POST"> {% csrf_token %} <label for="id_{{ student.id }}"> <p>{{ student.name.upper }} is already enrolled.</p></label> <input type="checkbox" id="id_{{ student_id }}" value="{{ student.id }}" name="student_ids2"> <input type="submit" value="Disenroll"> </form> {% else %} <form action="." method="POST"> {% csrf_token %} <label for="id_{{ student.id }}">{{ student.name }}</label> <input type="checkbox" id="id_{{ student_id }}" value="{{ student.id }}" name="student_ids"> <input type="submit"> </form> {% endif %} {% endfor %} {% endwith %} -
Get parent and child links in the sidebar
I have the following structure: Account Company child of the Account (Foreign key to Account) Product child of the Company (Foreign key to Company) Job child of the Company (Foreign key to Company) I'm using Generic Class Based View, so I get access to the urls of the current object/model. I have a sidebar, were I need to get the links for the other Models/objects in the structure. For example: if I am in a Product page I need the links to: Account Detail Company Detail Job list - Product List (if I'm not in the ListView) I can create a custom mixin, to query all of them and get the links, but it will be a duplicate query for the page were I'm already in case of Company Detail, or ListViews. I didn't implement something yet, regarding links, I want first to get ideas how to do it. What is the best approach ? -
In Django Rest Framework, How to save Foreign Key value in to_internal_value?
Custom Field Ref: http://www.django-rest-framework.org/api-guide/fields/#using-source Here is my Serializer: class OrderSerializer(serializers.ModelSerializer): short_address = AddressField(source='*') class Meta: model = Order fields = ('id', 'order_name', 'short_address',) Custom Address field: class AddressField(serializers.Field): def to_representation(self, obj): ret = { "name": obj.address.name, "city": obj.address.city } return ret def to_internal_value(self, data): ret = { "address__name": data["name"], // Not Working "address__city": data["city"], // Not Working } return ret I have models as Below class Order(models.Model): order_name = models.CharField(max_length=20,) address= models.ForeignKey(Address, null=True, on_delete=models.SET_NULL) class Address(models.Model): name = models.CharField(max_length=20,) city = models.CharField(max_length=20,) state = models.CharField(max_length=20,) country = models.CharField(max_length=20,) Is there any way to directly store foreign key's value in to_internal_value ? -
from filtered list rebuild MPTT TreeManager
I am not able to build a filtered tree, for example, I have a category it can be true or false, and on false do not include it in tree, also in a category i need to count products cumulative. In this example: categories = Category.objects.add_related_count(Category.objects.all(), Product, 'category', 'product_counts', cumulative=True) I am able to see all categories and product counts, but it is not filtered if I am trying to do: categories = Category.objects.filter(is_active=True).add_related_count(Category.objects.all(), Product, 'category', 'product_counts', cumulative=True) I get an error, because I have to have TreeManager to be able to call add_related_count. That's the issue I cannot build a TreeManager Tried other SO answers, but did not succeed. Anyone has any idea ? -
Pymongo django connection to more replicaset can't start new threads
I've a problem when try to connect to 2 different replica set on 2 different host from my django app. When try the second connection, using MongoClient, my application raise a RuntimeError: can't start new thread Everything works if I use the django shell using the same connection parameters Any suggestion would be appreciated Tx in advance -
Multilevel annotation/aggregation using django ORM
I have been trying to implement pretty much the same thing as in query-for-total-score Does Django support multilevel aggregation? I can get the max score for each user each challenge, but I don't know how to drill down my results to fit in. Submission.objects.values('challenge','user').annotate(Max('score'),Max('total_score')) -
django rest framework create json api of model schema
I am using Django 2 and restframework to create api to use in a ionic project . I have already used schema generator to generate my api structure . Also I want to create an api to pass models structure to other application so that they can create their models dynamically. So the question is that is it a good idea to make api like that and if yes, How to do that ? Thanks