Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django paginator page return NoneType
I am doing a simple search with Django and using the build in pagination to paginate results and I get this error when I click on next to view the next page results, int() argument must be a string, a bytes-like object or a number, not 'NoneType' I do not know what is causing it, here is the code, q is the query string def result(request): try: q = request.GET.get('q') orders = Order.objects.filter(Q(flat_number=int(q)) | Q(customer_contact=int(q))) paginator = Paginator(orders, 10) # Show 25 contacts per page page = request.GET.get('page') orders = paginator.get_page(page) context['orders'] = orders return render(request, 'main/results.html',context) except Exception as e: print('error is ', e) return HttpResponse(str(e)) -
how can i calculate percentage by given provoiding urls
We are providing you urls for a public dataset of currency exchange rate of many different countries against Indian Rupee for two specific days as listed below: http://data.fixer.io/api/2017-01-01?access_key=401b813f53bc48488e308cb9a13e06fb Currency Exchange Rate dated 2017-01-01 wrt EUR http://data.fixer.io/api/2018-01-01?access_key=401b813f53bc48488e308cb9a13e06fb Currency Exchange Rate dated 2018-01-01 wrt EUR Above URLs will provide you currency exchange rate for following currency code AUD , BGN , BRL , CAD , CHF , CNY , CZK , DKK , EUR , GBP , HKD , HRK , HUF ,IDR,INR, ILS ,JPY ,KRW , MXN , MYR , NOK , NZD , PHP ,PLN , RON , RUB , SEK , SGD ,THB , TRY , USD and ZAR Your task is to develop a python script which when run will print the percentage change in value of currency exchange rate from each country from 2017 to 2018. The data should be sorted in ascending order of percentage change. The formula for finding percent change is : (2018 value - 2017 value) * 100 / ( 2017 value) .to 2 decimal degrees For example: if value of AUD is 56 in 2017 and 66 in 2018, then we want to see following ExchangeRate Symbol 2017 value 2018 Value PercentChange … -
How can i build Role based permissions access in multi client application in django?
I am currently making an architecture for my multi-client application, in which I want to implement role based access model. Every client will make customize-roles and will give permissions to that role. Finally that role will be assigned to the agent who will then use the application according to the permissions given to his role. Now my concern is, what can be best practice to make this possible and any idea about architecture that can be implement in Django. Previously I have made an application which has role based access to the user of application. In that, I use to save the permissions in the database and at the time of login the permissions of user will save in the session, which later can be use to check the permissions of that user. -
Django is_popup variable does not exit in base.html
I'm trying to config the django project in vscode and running via debug. python==3.6.7 Django==2.1.8 When I try to open http://127.0.0.1:8000/admin/ I am getting the following error, please refer the screen shot below. I tried many possible workaround from google, by trying to change logging level from debug to info, but nothing seems to be worked. I request you to please let me know how to fix this issues. Thanks in advance. -
Python3 OOP: Select all objects of a particular class w/o variables
I have simple class: class ChannelMessages: def __init__(self, channel, date, message): self.channel = channel self.date = date self.message = message ... somecode here ... for message in messages: ChannelMessages(name, message.to_dict()['date'], message.to_dict()['message']) ... name, date, message - is a variables ... I want now to select all ChannelMessages class objects and put it in a variable. Im dont need to saving it anywhere, i need to render this Classes once on my app. Im trying to use something like Django ORM: ChannelMessages.objects.all() but i cant select them this way. So is there a way to select all created objects w\o vars? Or i always shold specify variables for every created class object? -
Django rest - how to serialise a prefetch related set?
im trying to load a related set into a serialiser, so the entires would appear as a nested dictionary under the parent. I currently don't have any errors but my api also is not returning any data at all for circuits_subnets. any ideas? Thanks serializers.py class DeviceConn(QueryFieldsMixin,serializers.HyperlinkedModelSerializer): poll_ip = serializers.ReadOnlyField() mgmt_ip = serializers.ReadOnlyField() bgp_as = serializers.ReadOnlyField( source='site.bgp_as', ) location = serializers.ReadOnlyField( source='site.location', ) site_type = serializers.ReadOnlyField( source='site.site_type.site_type', ) device_type = serializers.ReadOnlyField( source='model.device_type.device_type_plural', ) circuit_subnets = serializers.ReadOnlyField( source='model.devicecircuitsubnets_set', ) class Meta: model = Device fields = ('site_id','poll_ip','mgmt_ip','bgp_as','hostname', 'device_type','location','site_type','circuit_subnets') views.py class DeviceConnViewSet(viewsets.ReadOnlyModelViewSet): # sub queries poll_ip = Subquery( DeviceCircuitSubnets.objects.filter(device_id=OuterRef( 'id'),subnet__subnet_type__poll=True).values('subnet__subnet')[:1]) mgmt_ip = Subquery( DeviceCircuitSubnets.objects.filter(device_id=OuterRef( 'id'),subnet__subnet_type__mgmt=True).values('subnet__subnet')[:1]) queryset = Device.objects.all().annotate( poll_ip=poll_ip, mgmt_ip=mgmt_ip ) \ .select_related('site','site__site_type','model','model__device_type') \ .prefetch_related('devicecircuitsubnets_set') \ .order_by('site__location') serializer_class = DeviceConn -
How to change form values on edit?
I'm beginner in Django. I need to change form field value if other field is editing. So, if I typed val1 and val2 in webform, val 3 is calculating automatically before press save button. Like in MS Excel, if i have cell "C1" with function "=A1+B1" , when i change A1 or B1 values then C1 value will automatically change. class DealForm(forms.ModelForm): class Meta: model = Deal fields = ['status', 'val1', 'val2', 'val3'] widgets = { 'status': forms.TextInput(attrs={'class': 'form-control'}), 'val1': forms.NumberInput(attrs={'class': 'form-control'}), 'val2': forms.NumberInput(attrs={'class': 'form-control'}), 'val3': forms.NumberInput(attrs={'class': 'form-control'}) } class Deal(models.Model): status = models.CharField(max_length=10, db_index=True) val1 = models.FloatField(null = True, blank=True) val2 = models.FloatField(null = True, blank=True) val3 = models.FloatField(null = True, blank=True) class DealCreate(View): def get(self, request): form = DealForm() return render(request, 'portfolio/deal_create.html', context={'form':form}) def post(self, request): bound_form = DealForm(request.POST) if bound_form.is_valid(): new_deal = bound_form.save() return redirect(new_deal) return render(request, 'portfolio/deal_create.html', context={'form':bound_form}) -
Unable to get all the fields of a model when we alter the table manually
I'm new django web framework. I have a models.py file where i given information about my entity fields, i ran the manage.py migrate command table generated i have alter the table manually without touch the models.py later I have run the python manage.py inspectdb > myapp/models.py in controller level using os.system models.py updated then i have tried models.objects.all() I'm unable to get the newly added field, I have called the view By using ajax call , after page refresh only new field name coming. can you help how to get all field names with in the ajax response only with out page refresh. It would be grateful if you can help me Note: I have checked in view level only with out page refresh first time only new column not came after page refresh it came Thanks in advance... I'm looking for cache in django -
Bokeh chart in Django returning a blank page
I'm trying to work through a tutorial to show a simple bokeh chart on a django page, but the web page is blank when it loads - there's no chart. There was a similar Stack Overflow question where the wrong version of bokeh was referenced in the html file - I checked to make sure that's not the case here. I also tried to use the render function, as render_to_response is apparently being deprecated, but the same thing happened. <!DOCTYPE html> <html lang='en'> <head> <link href="http://cdn.pydata.org/bokeh/release/bokeh-1.0.4.min.css" rel="stylesheet" type="text/css"> <link href="http://cdn.pydata.org/bokeh/release/bokeh-widgets-1.0.4.min.css" rel="stylesheet" type="text/css"> <script src="http://cdn.pydata.org/bokeh/release/bokeh-1.0.4.min.js"></script> <script src="http://cdn.pydata.org/bokeh/release/bokeh-widgets-1.0.4.min.js"></script> {{ script | safe }} <title>testing bokeh...</title> </head> <body> {{ div | safe }} </body> </html> from django.shortcuts import render, render_to_response from bokeh.plotting import figure, output_file, show from bokeh.embed import components def bokehTutorial(request): x, y, = [1, 2, 3, 4, 5], [1, 2, 3, 4, 5] #Setup graph plot plot = figure(title = 'Line Chart', x_axis_label = 'X axis', y_axis_label = 'Y axis', plot_width = 400, plot_height = 400) #plot line plot.line(x, y, line_width = 2) #store components script, div = components(plot) #return to django homepage with components sent as arguments which will then be displayed return render_to_response('wordUsage/bokehTutorial.html', {'script': script, 'div': div}) #return render(request, … -
Error in sending multiple mails using celery. raised unexpected: OSError(0, 'Error') and in do_handshake self._sslobj.do_handshake()
I want to send a single mail to multiple recipients asynchronously using Celery task. It is working very slow and showing errors also. Please kindly help me with this. from celery.registry import tasks from celery.task import Task import pyotp from django.core.mail import EmailMultiAlternatives class CreateDriveTask(Task): def run(self, email_list): msg = "hiiiiiiiiii" return EmailMultiAlternatives("Welcome",msg,"hardeepjethwani123@gmail.com",email_list).send() tasks.register(CreateDriveTask) want to send the mails at some speed without any errors -
How can i add a 'preview' button in the edit page of the django admin?
After long searches, i till didn't find any answers i've been able to apply. I have in my django app a models which creates new pages in the website: class Page(models.Model): name = models.CharField(max_length=255, null=False, blank=False, unique=True) content = HTMLField('Content') slug = models.CharField(max_length=255) background_image = models.ImageField( upload_to="page_background/", null=False, blank=False, default="default/livresse_logo.png", ) As you can see there's a WYSIWYG editor in it, a title and a background image. When i go to the admin page it's like this: admin edit page screenshot I'm looking for a way to add a button 'preview' (maybe next to the save button) that would show the content of my model included in the template that will be use to display the page before saving. I'd like this button only displaying for that model. Hope i'm clear enough. -
How to assign a Lead/Manager to an Employee in Django?
I am beginner in django and trying to create a web application like Employee Management System. I am trying to assign a lead to every employee. I have been trying to find this Employee Manager relationship to get my requirement done for a long time. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) designation = models.CharField(max_length=20, null=False, blank=False) empID = models.IntegerField(null=True, blank=True) Manager = models.ForeignKey('self', null=True, blank=True, on_delete=models.CASCADE) class Project(models.Model): Company = models.CharField(max_length=35) Project = models.CharField(max_length=100) Project_Details = models.TextField() Client_Contact = models.CharField(max_length=30) Client_Manager = models.CharField(max_length=30, default="Bruce") Status = models.CharField(max_length=30, choices=status_choices,default='In Progress') Status_Details = models.TextField() Created = models.DateTimeField(auto_now=True) Modified_on = models.DateTimeField(auto_now=True) Employee_Name = models.ForeignKey(User, null=True, blank=True, on_delete = models.CASCADE) I am able to select a Manager(who is also an employee) for an employee while adding a new employee. However, after saving the employee, Manager is not showing up in the details page. What could be the reason why I am not getting the manager listed for the employees? Is there anything I am missing here? -
Compare user attributes in template using IF statement
I have a list of users and want to display their tasks only if the selected user belongs to the same department. My Models have a department field that I want to compare. This is my template code. {% extends 'view_users.html' %} {% block view_user_tasks %} <a href="{% url 'view_users' %}"> Back</a> <p> todo lists for {{ user }}</p> {% for todo in view_user_tasks %} <a href="{% url 'detail' todo.id %}" id="left_pencil"></a> <a id="{{todo.id}}" class="todo_remove"></a> {% endfor %} {% endblock view_user_tasks %} What i want to do is evaluate this condition: if request.user.Department == user.Department: show user tasks This are my respective views. class ViewUsers(ListView): model = CustomUser template_name = 'view_users.html' class ViewUserTasks(ListView): model = Todo template_name = 'view_user_tasks.html' context_object_name = 'view_user_tasks' How can I be able to accomplish this? -
How to place, render and save multiple objects received from the secondary model (one to many) in 1 form
I have an issue with the multiple objects returned by object manager. Code: #Models PrimaryModel … SecondaryModel(models.Model) fk = ForeghnKey(PrimaryModel) image = ImageFiled(…) # might be multiple images #views.py (edition of the 2 models data) @login_required def viewname_edit(request, pk): obj1 = Primarymodel.objects.get(pk=pk) obj2 = SecondaryModel.objects.get(fk_id=pk) # multiple objects here(multiple images) if request.method == 'POST': form1 = PrimaryModelForm(request.POST, request.FILES, prefix="form1", instance=obj1) form2 = SecondaryModelForm(request.POST, request.FILES, prefix="form2", instance=obj2) … … … some code I can use: obj2 = SecondaryModel.objects.filter(pk=pk) to get multiple objects instead of 1 but then I can't use META dictionary here form2 = SecondaryModelForm(request.POST, request.FILES, prefix="form2", instance=obj2) because query set doesn't have META data. With 1 object in SecondaryModel all works fine but with multiple -doesn't. Exception – MultipleObjectsReturned. Question is how I can put multiple objects in form2 , render them and save them in this case ,or it is not possible at all. I can filer multiple objects to one using exceptions but i need to get and save multiple onesif it required. Thank you in advance... -
Python3 How to read a file from with in a Django Cronjob
I have a cronjob running via django-crontab module. In one of my functions I am trying to read a file which is in the same directory as my cron.py, however I am getting File not found error. cron.py def get_standard_abi() : try : data = None standard_abi_file_path = os.path.abspath("standard_abi.json") print("Reading file from path ",standard_abi_file_path) #Prints the path with open(standard_abi_file_path) as f: data = json.load(f) print(data) return data except Exception : logger.exception("An exception occurred while reading file") return None Exception : FileNotFoundError: [Errno 2] No such file or directory However, the file exist in the directory. Is this a good approach, or shall I defined this json as a global variable , if so how can I export such variable? -
How to save changes made in inlineformset_factory in UpdateView without deleting the previous data?
I want to update the changes made in inlineformset_factory rather then deleting it adding a new one. models.py class invoice(models.Model): invoice_no = models.CharField(max_length=20) invoice_date = models.DateField(auto_now=False, auto_now_add=False) class invoice_description(models.Model): invoice = models.ForeignKey(invoice, related_name='items', unique=False, on_delete=models.CASCADE) service_description = models.CharField(max_length=50, blank=False) hsn = models.CharField(max_length=50, blank=False) qty = models.IntegerField(blank=False) per = models.CharField(max_length=50, blank=False) rate = models.IntegerField(blank=False) currency = models.CharField(max_length=50, blank=False) ex_rate = models.IntegerField(blank=False) amount = models.IntegerField(blank=False) gst = models.IntegerField(blank=False) forms.py class InvoiceForm(forms.ModelForm): class Meta: model = invoice fields = ['invoice_no', 'invoice_date'] widgets = { 'invoice_no': forms.TextInput(attrs={'class': 'form-control'}), 'invoice_date': forms.DateInput(attrs={'type': 'date', 'class': 'form-control'}, format="%Y-%m-%d"), } class InvoiceDesForm(forms.ModelForm): class Meta: model = invoice_description fields = '__all__' widgets = { 'service_description': forms.TextInput(attrs={'size': 20}), 'hsn': forms.TextInput(attrs={'size': 5}), 'qty': forms.NumberInput(attrs={'class': 'form-number1'}), 'per': forms.TextInput(attrs={'size': 5}), 'currency': forms.TextInput(attrs={'size': 5}), 'rate': forms.NumberInput(attrs={'class': 'form-number1'}), 'ex_rate': forms.NumberInput(attrs={'class': 'form-number1'}), 'amount': forms.TextInput(attrs={'size': 5}), 'gst': forms.NumberInput(attrs={'class': 'form-number'}), } InvoiceFormSet = inlineformset_factory(invoice, invoice_description, form=InvoiceDesForm, extra=5, can_delete=True) views.py class InvoiceUpdateView(UpdateView): template_name = 'home/invoice_form.html' model = invoice form_class = InvoiceForm def get_success_url(self): self.success_url = 'home/invoice_form.html' return self.success_url def get_context_data(self, **kwargs): context = super(InvoiceUpdateView, self).get_context_data(**kwargs) if self.request.POST: context['form'] = InvoiceForm(self.request.POST, instance=self.object) context['invdescription_form'] = InvoiceFormSet(self.request.POST, instance=self.object) else: context['form'] = InvoiceForm(instance=self.object) context['invdescription_form'] = InvoiceFormSet(instance=self.object) return context def post(self, request, *args, **kwargs): self.object = self.get_object() form_class = self.get_form_class() form = self.get_form(form_class) qs = … -
Following nested foreign keys while prefetching in Django
I have an information model with deep and complex foreign key relations. And LOTS of them. Becuase of it I am trying to use select_related() and prefetch_related() to mimimize the number of queries to my DB. I am having the problem, however, that I cannot figure out a way to make prefetching operators follow foreign keys to an arbitrary depth. I am aware of the double underscore operator (__), but that isn't really an option, because I do not know in advance how deep the nesting will be. So for example let's say I have obects A, B, C,...Z. Any object can have an arbitrary number of foreign keys pointing to any object that appear, say, later on in the alphabet. How can I make sure that, for example, prefetching the foreign key that from A points to B will follow all the foreign keys on B? My best shot for now was a semi-hardcoded approach on the get_queryset() method on the object manager. Thank you in advance -
Django saving model inline
I have two model's , Model1 class Model1(models.Model): ........ Model2 class Model2(models.Model): model1 = models.ForeignKey(Model1, related_name='Model1Objects',on_delete=models.CASCADE) ...... Model1.admin class Model2Inline(admin.StackedInline): model = Model2 form = Model2Form extra = 0 max_num = 3 class Model1Admin(admin.ModelAdmin): form = Model1Form model = Model1 inlines = [Model1Inline] In the django permissions I created a group where they can only see what is happening in model1 and being able to edit the model2. Whenever I try to make a change in model2, it will not let me, but if I change the permissions and allow to change the model1 it already lets change the model2 as well. How can I do to be able to change model2 without having to allow changing model1? -
How to add mini_wishlist for django-oscar?
I am working for e-commerce sites with django-oscar. I have problem with wishlist. I want to add mini_whislist on navbar. It's looks like oscar's basket_quick. I did try this one, but its only working on wishlists section. {% if wishlists %} {% for wishlist in wishlists %} <span class="text-muted b">{{ wishlist.name }}</span> <span class="text-muted b">{{ wishlist.lines.count }}</span> {% endfor %} {% else %} <img src="{% static "images/topview.png" %}"> <span class="p-2 text-muted b">EMPTY</span> {% endif %} How can I make it appear on every page? -
Can I make migration from setup.py as post install command?
In a Django project deployment, I am trying to execute migration from a post install code according to https://stackoverflow.com/a/36902139/8473819 This code should run the migrate command automatically. I keep running into problems with DJAGO_SETTINGS_MODULE not being set or, when I try to configure settings right at setup.py an error: AttributeError: 'str' object has no attribute 'INSTALLED_APPS' My first question is: is it possible at all to run migrations right at installation? Second: How to configure the settings so that they can be accessed both from setup file at installation and later on normally from within the app. #setup.py import os from setuptools import setup, find_packages from setuptools.command.install import install from django.conf import settings from django.core.management import call_command with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme: README = readme.read() # allow setup.py to be run from any path os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir))) class PostInstallCommand(install): """Post-installation for installation mode.""" def run(self): settings.configure('zebrafish.zebrafish.settings', DEBUG=True) call_command("migrate") install.run(self) setup( name='django-genetisc', version='0.1', packages=find_packages(), include_package_data=True, license='BSD License', description='Web application for management of data about Zebrafish.', long_description=README, url='http://127.0.0.1:8000/zebrafish_app/', author='Tomas Dockal', author_email='tomas-dockal@email.cz', install_requires=['setuptools', 'Django'], cmdclass={'install': PostInstallCommand}, scripts=['zebrafish/manage.py'], ) My settings file is two directory levels under the setup.py and mange.py is one level under it, if that is relevant information. I am trying to … -
i want to make carbontfoot print calculator form but there is feild error
raise FieldError(message) django.core.exceptions.FieldError: Unknown field(s) (propane, heating_oil, wooden_pellets, lpg, coal, electricity, natural_gas) specified for User -
How to fix delete process of a record when using django_tables2 and django fm modal forms
My issue is that I can not successfully delete an object of my class when using django_tables2 and fm modal forms. The action of editing works but the action of delete is not working properly since after pressing the delete button the app redirects to the same endpoint without deleting the object. Notice: The edit and delete fields of my ProductSerialNumbers class are added by me in the tables.py Is there anything that I am missing here? urls.py url(r'^warehouse_stuffing/edit/(?P<pk>\d+)/$', views.ProductSerialNumbersUpdateView.as_view(), name='warehouse_stuffing_update'), url(r'^warehouse_stuffing/delete/(?P<pk>\d+)/$', views.ProductSerialNumbersDeleteView.as_view(), name='warehouse_stuffing_delete'), tables.py class ProductSerialNumbersTable(tables.Table): #add new columns(edit,delete) edit=tables.LinkColumn('warehouse_stuffing_update',args=[A('pk')],accessor='Edit',orderable=False,empty_values=()) delete=tables.LinkColumn('warehouse_stuffing_delete',args=[A('pk')],accessor='Delete',orderable=False,empty_values=()) class Meta: #define the model model = ProductSerialNumbers template_name = 'django_tables2/bootstrap.html' def render_delete(self,record): #create the link with modal form for delete return format_html('<a href="/warehouse_stuffing/delete/{}/" class="fm-delete" data-fm-head="Delete of Serial Number" data-fm-callback="redirect" data-fm-target="/psn/"><button class="btn btn-danger btn-sm" type="">Delete</button></a>',record.id) def render_edit(self,record): #create the link with modal form for edit return format_html('<a href="/warehouse_stuffing/edit/{}/" class="fm-update" data-fm-head="Edit of Serial Number" data-fm-callback="reload"><button class="btn btn-primary btn-sm" type="">edit</button></a>',record.id) views.py def psn(request): #psns stands for prodct serial numbers 's psns=ProductSerialNumbers.objects.all() table = ProductSerialNumbersTable(psns) RequestConfig(request).configure(table) return render(request, 'warehouse/simple_list.html', {'table': table}) -
What is the relation of these 3 models: user, birthday, label?
I'm creating a birthday calendar app. It will have the following models: - Django's user model - Birthday - Label (i.e. friends, family) I'm not sure how to model the Label class. The user should have the ability to create a new Label object which can then be used when creating a Birthday object. The user should also be able to filter Birthday's based on the Label. How would you model these relationships in a db? from django.conf import settings from django.db import models from django.utils import timezone class Birthday(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) name = models.CharField(max_length=25) day = models.DateField() class Label(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) tag = models.CharField(max_length=25) -
my django project runtwice file jquery how to fix this bug?
i have a project django. In file template.html i was have a script jquery with content: <script> console.log('test') </script> When i run: python manage.py runsever the script allway runtwice in my browser. >> test >> test How to fix this bug? Please help me! thankyou -
getting error EvaluationTest object is not subscriptable?
I am creating an update function but i am getting an error in Django rest framework like this EvaluationTest object is not Subscriptable basically i am trying to update nested serializer i am newbie i have searched a lot but didn't able to make it work Update Function def update(self,instance,validated_data): data = self.context['request'].data evaluationtest = EvaluationTest() #admin= User.objects.get('username') cat=Category.objects.get(id=data['category']) instance.category=cat instance.category = validated_data.get('id',instance.category) instance.title = validated_data.get('title',instance.title) instance.type = validated_data.get('type',instance.type) instance.save() instance = EvaluationTest() # keep_questions=[] # existing_id=[q.id for q in instance.questions] order = 1 for q in instance['questions']: newQ = Question() newQ.question=q['title'] newQ.order = order newQ.save() for c in q['choices']: newC = Choice() newC.title = c newC.save() newQ.choices.add(newC) newQ.answer = Choice.objects.get(title=q['answer']) newQ.instance = instance newQ.save() order += 1 return instance