Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django ORM: How can I filter based on an annotation timedelta result
I have a model like this: class Interval(models.Model): start = models.Datetime() end = models.Datetime(null=True) I would like to query all intervals that are larger then 5 minutes. I'am able to do intervals=Interval.objects.exclude(end=None).annotate(d=models.F("end")-models.F("start")) When I do intervals[0].d , I have the interval, which is correct. Now I would like to only get as results the entries where d is greater than 5 minutes. I tried intervals=Interval.objects.exclude(end=None).annotate(d=models.F("end")-models.F("start")).filter(d__gt=timedelta(0, 300)), but I get the following error: TypeError: expected string or bytes-like object. It tries to match the timedelta with a regex of datetime. ` Any ideas? Thanks in advance -
(1052, "Column 'name' in field list is ambiguous")
I get the bellow error when I query my instances: (1052, "Column 'name' in field list is ambiguous") If I use: http://localhost:8000/api/physicalserver/list/?switchesport__id=5 I can get the right results. but if I use: http://localhost:8000/api/physicalserver/list/?switchesport__bandwidth=10 I will get the error. My list API view is bellow: class PhysicalServerListAPIView(ListAPIView): serializer_class = PhysicalServerListSerializer permission_classes = [AllowAny] filters = {'{}__contains'.format(key): value for key, value in query_params.items()} return PhysicalServer.objects.filter(**filters) How can I use the switchesport__bandwidth as the query param? -
Django is not taking GET input in AJAX call
I am trying to take username input and return in ajax call whether the username is taken or not in Django. But the method in DJango is not taking the input. I am sharing the code here. URL.py url(r'^search_username/$', user.views.search_product, name="search_username"), script + HTML {% load staticfiles %} {% block content %} <form method="post"> {% csrf_token %} <input name="search" id="search" type="text"/> <button type="submit">Sign up</button> </form> {% endblock %} $("#search").change(function () { var username = $(this).val(); $.ajax({ url: '/search_username/', data: { 'username': username }, dataType: 'json', error: function(){ alert('failure'); }, success: function (data) { if (data.is_taken) { alert("A user with this username already exists."); } } }); }); Views.py def search_username(request): print('Entered into search') username = request.GET.get('search', None) print(username) data = { 'is_taken': allproductlist.objects.filter(product_name_english__iexact=username).exists() } return JsonResponse(data) The problem is it prints Entered into search.But when I print username it shows NOne. Can anyone please specify what is happening ? -
pytest django: unable to access db in fixture teardown
I need to explicitly delete a fixture after it is used. I know that pytest-django by default drops all objects on teardown but in this particular case I need to do it manually. However, although my tests are marked as pytest.mark.django_db, I am able to create a fixture, but unable to delete it after a yield line: import pytest from tgapps.models import TelegramApp @pytest.fixture(scope='module') def some_fixture(): app = TelegramApp.objects.create( session_data=b'\xa2\x8f#', app_owner_phone=79856235474, app_id=182475, app_hash='aad9ab4384fea1af0342b77b606d13b0' ) yield app print('deleting object...') app.delete() class TestTelegramServiceObject(object): @pytest.mark.django_db def test1(self, some_fixture): print('Fixture created:') print(some_fixture) this is my test output: ============================= test session starts ============================== platform darwin -- Python 3.6.4, pytest-3.4.0, py-1.5.2, pluggy-0.6.0 Django settings: inviter.settings.staging (from ini file) rootdir: /Users/1111/_projects/fasttrack/inviter, inifile: pytest.ini plugins: mock-1.7.1, dotenv-0.1.0, django-3.1.2 collected 1 item test_example.py E.Fixture created: <79856235474 - 182475> deleting object... tests/api/test_example.py:25 (TestTelegramServiceObject.test1) @pytest.fixture(scope='module') def some_fixture(): app = TelegramApp.objects.create( session_data=b'\xa2\x8f#', app_owner_phone=79856235474, app_id=182475, app_hash='aad9ab4384fea1af0342b77b606d13b0' ) yield app print('deleting object...') > app.delete() test_example.py:21: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /Users/1111/.virtualenvs/inviter-WB5rPISo/lib/python3.6/site-packages/django/db/models/base.py:890: in delete collector.collect([self], keep_parents=keep_parents) /Users/1111/.virtualenvs/inviter-WB5rPISo/lib/python3.6/site-packages/django/db/models/deletion.py:221: in collect elif … -
Django global variable based on user groups
In my Django project I have a database that is populated from outside Django, but needs the Django functionality to display data in the database in a user friendly manner. The legacy database structure is as follows: class SomeModel(models.Model): #some fields group_access = models.ForeignKey(AccessGroup,on_delete=models.CASCADE() class AccessGroup(models.Model): group_name = models.CharField(max_length=200) The users have a custom User profile with manytomany relationship with group names assigned to the specific user: class CustomUser(models.Model): #some values projects = models.ManyToManyField(AccessGroup) Currently I am able to display data from all groups a user has access to, but what I am looking for is a way to create a drop down menu so that users can switch between groups without the need to log out or reenter group on every view. -
Django - create object in a specifiq data base
To save a model to my 'not_default_db' i'm using : p = Person(name='James') p.save(using='not_default_db') But using Model.create() save the model in the default DB: Person.objects.create(name='James') Is it possible to use Model.create() on a specifc Data Base ? -
Filter Django ModelForm without validating it
I have a form which I would like to filter based on information passed by another form, but without validating it just yet: forms.py: class SampleRunSearchForm(forms.ModelForm): class Meta: model = SampleRun fields = ('id',) def __init__(self, sr_obj, *args, **kwargs): super(SampleRunSearchForm, self).__init__(*args, **kwargs) self.fields['id'] = forms.ChoiceField(required=True, label='Sample:', widget=forms.CheckboxSelectMultiple, choices=((s.id, s) for s in sr_obj) ) self.helper = FormHelper() self.helper.layout = Layout( Field('id', css_class='sample-run-display',), Submit('submit', 'Report samples', css_class='upload-btn') ) self.helper.form_method = 'POST' views.py: class SearchSampleRun(View): samplerunform = SampleRunSearchForm template_name = 'results/samplerun_search_form.html' def get(self, request, *args, **kwargs): self.run_obj = get_object_or_404(Run, id=kwargs['run_id']) self.choice = kwargs['choice'] self.sample_run_obj = self.obtainCorrectSamples() samplerunform = self.samplerunform(sr_obj=self.sample_run_obj) context = {'samplerunform': samplerunform} return render(request, self.template_name, context) def post(self, request, *args, **kwargs): samplerunform = self.samplerunform(request.POST) if samplerunform.is_valid(): HttpResponseRedirect(...somewhere to display information) context = {} return render(request, self.template_name, context) The initial form (not shown) takes a charfield and redirects to my SearchSampleRun view with **kwargs. I want to filter my SampleRunSearchForm based on these kwargs and display a list of check boxes - filtered model object from the SampleRun model. This works, but when i click these buttons, and submit the form, it initialised again, and sr_obj is None, so the form field produces an error. I have tried using: sr_obj = kwargs.pop('sr_obj', … -
How to host a django project on IIS?
I tried using Fast CGI method but i get a 500 error i tried this method Im currently using Django 2.0.5 and IIS 9 Im using the basic django website to try to upload the website... im using python 3.4. I was using the fastCGI method to upload it, but it wasn't working and i was getting the error.. Any Suggestions on what I'm supposed to do to get it running without using fastCGI? Thanks in Advance! please feel free to comment if you want any more information... -
Calling javascript function using python function in django
I have a website built using the django framework that takes in an input csv folder to do some data processing. I would like to use a html text box as a console log to let the users know that the data processing is underway. The data processing is done using a python function. It is possible for me to change/add text inputs into the text box at certain intervals using my python function? Sorry if i am not specific enough with my question, still learning how to use these tools! -
How can I render ForeignKey fields into template using Django
I am new to Django I have two models are user and address, here user having two foreign key fields are 'localaddress', 'permanentaddress' Address model: class Address(models.Model): fulladdress = models.CharField(max_length=1000, null=True, blank=True) additional_address = models.CharField(max_length=1000, null=True, blank=True) street_address = models.CharField(max_length=150, null=True, blank=True) route = models.CharField(max_length=150, null=True, blank=True) city = models.CharField(max_length=100, null=True, blank=True) state = models.CharField(max_length=100, null=True, blank=True) country = models.CharField(max_length=100, null=True, blank=True) pincode = models.IntegerField(null=True, blank=True) class Meta: db_table = 'address' User model: from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.contrib.auth.models import AbstractUser class User(AbstractUser): localaddress = models.ForeignKey(Address, on_delete=models.CASCADE, related_name="localaddress", null=True, blank=True) permanentaddress = models.ForeignKey(Address, on_delete=models.CASCADE, related_name="permanentaddress", null=True, blank=True) class Meta: db_table = 'user' settings.py: AUTH_USER_MODEL = 'student.User'# changes built-in user model to ours here both localaddress and permanentaddress having same foreign key (Address model only) forms.py: class AddressForm(forms.ModelForm): localaddress = forms.CharField(required=False) permanentaddress = forms.CharField(required=False) def __init__(self, *args, **kwargs): super(AddressForm, self).__init__(*args, **kwargs) class Meta: model = User fields = ['localaddress', 'permanentaddress'] def save(self, commit=True): user = super(AddressForm, self).save(commit=False) user.localaddress = self.cleaned_data['localaddress'] user.permanentaddress = self.cleaned_data['permanentaddress'] if commit: user.save() return user views.py: def address_form(request): if request.method == 'POST': form = AddressForm(request.POST, instance=request.user) if form.is_valid(): form.save() args = {'form': form} return render(request, 'student/addressform.html', args) else: args = … -
How to parse multiple files in multipart form-data with django rest framework?
I am receiving an array with a few files. My request.data looks like this: <QueryDict: {'image': [<TemporaryUploadedFile: image_1.png (image/png)>, <TemporaryUploadedFile: image_2.png (image/png)>] However, if I try to parse images like this: request.data['image'] I only can see the last image, and django rest framework recognize it as a file object, not a list. If I try to iterate over it all I can see is bytes. I am using a ModelViewset and added this parsers parser_classes = (MultiPartParser, FormParser) -
Ipython unable to run `manage.py`
When I try to issue command to run Django shell with ipython, it prompt to type for help: $ ipython manage.py shell Type 'manage.py help <subcommand>' for help on a specific subcommand. Available subcommands: [auth] changepassword createsuperuser [contenttypes] remove_stale_contenttypes However, I'm aware ipython is capable to run a module cat experience.py print("run it with ipython") ipython experience.py run it with ipython What's the reason ipython unable to run manage.py? -
Using url in Django Templates
I have the following django 1.9 endpoint: url(r'^(?P<pk>\d+)/members/(?P<status>active|deactivated)?$', gym.GymUserListView.as_view(), name='user-list') Using the above, a valid url would be like like /1/members/active or /1/members/deactivated I am trying use the url in one of my templates like: {% url 'user_list' pk=gym.id status=active %} This throws the following error: django.core.urlresolvers.NoReverseMatch: Reverse for 'user-list' with arguments '(1, 'active')' and keyword arguments '{}' not found. 0 pattern(s) tried: [] I have also tried with quoting like status='active' but in vain. What could be wrong? -
'ContentFile' object has no attribute 'upper' while trying to resize image in django
I have an ImageField in models.py and I need to resize the image when the user uploads it using PIL, here is my code : views.py def dress_add(request): all_name = Name.objects.all() current_user = request.user all_good = Item.objects.all().filter(dress_special=True) if request.method == "POST": add_dress_form = AddDressForm(request.POST, request.FILES) if add_dress_form.is_valid(): model_instance = add_dress_form.save(commit=False) model_instance.created_by = current_user.first_name model_instance.created_username = current_user.username if model_instance.dress_image1: model_instance.dress_image1 = Image.open(model_instance.dress_image1) model_instance.dress_image1.resize((1000, 1000), Image.ANTIALIAS) thumb_io = BytesIO() model_instance.dress_image1.save(thumb_io, model_instance.dress_image1.format, quality=60 ) model_instance.dress_image1.save(model_instance.dress_image1.filename, ContentFile(thumb_io.getvalue()), save=False) model_instance.save() return redirect('dress_confirm') else: add_dress_form = AddDressForm() context = { 'add_dress_form':add_dress_form, 'current_user':current_user, 'all_name':all_name, 'all_good':all_good, } return render(request, 'fostan/dress_add.html', context) ERROR 'ContentFile' object has no attribute 'upper' Also is it right to use ImageField in this case or I should be using FileField -
Inheriting the Django admin header
I have my own HTML page "stat.html" which shows some graphs, this is hyperlinked from a custom index page that I made using this method answer3. How do I just inherit the Django admin header in this stat.html page and have my own title, some links to static js pages and some content in it? My current admin/custom_admin.html page looks like this {% extends "admin/index.html" %} {% block content %} {{block.super}} <div class="module"> <table style="width:100%"> <caption> <a class="section">Statistics </a> </caption> <tbody> <th scope="row"> <a href="/myapp/statpage" class="model">Stats Page</a> </th> </tbody> </table> </div> {% endblock %} -
In Django admin , how to propose a filter form by updated date
In django admin I see the link when you click on a model defined as following in index.html : <th scope="row"><a href="{{ model.admin_url }}">{{ model.name}}</a></th> I see the url for the filter: /admin/MyApp/MyModel/?updated__gte=2018-05-18+00%3A00%3A00%2B00%3A00&updated_It=2018-05-19+00%3A00%3A00%2B00%3A00 Is it possible for me to define extra action from the index.html like provide the filter view with pass paremeter? -
Display specific product against its barcode number after searching by barcode
I implement search feature which search by barcode and display the product of that barcode in a div. But i am facing the problem that when i type a barcode number in input field then it stores in ajax method and from that method it goes to view function search and i am passing that variable's value from this view to another view by using session and then render it to the my desired template but the issue is that it updates the value only in search view function real time but no change in my 2nd view and when i refresh the page then it change/replace value in my 2nd view function. That means "it shows me product against previously entered barcode value every time". Now I want to know what is the solution of this problem. Is there any way to dirct pass ajax variable to my html code as a vaiable so that i can put a condition likie {% if search_text == {{product.barcode}} %} or how to update variable real time while passing it from one view to another view. Thanks in Advance! Here's my views.py! @login_required def search(request): if request.method == "POST": search_text = request.POST['search_text'] … -
autocomplete-python unable to find python binary
I am working with python and django in Atom editor, however I get this error when I want to runserver. enter image description here I change the path several times but nothing changed. Any help would be most grateful. -
Which is the best development/production environment for Django projects?
A bit of background I work for a little company as Django developer. The previous developer left the company and I am the only developer (that is the reason they were looking for a Django developer). The company has a simple web application that needs to be mantained and scaled. It seems that the company is getting sales and incomes are increasing. There is a possibility to hire another developer in the short or mid-term. Right now I am analizing possible improvements. This is my first professional job as Django developer, but I achieved to deploy some little personal projects in the past. As you can imagine I am not an expert at all. The issue We use a Ubuntu VPS for development, using Django's integrated web server. And another Ubuntu VPS for production, using Nginx+Gunicorn. We use git for version control. The only user we use (for everything) in both VPS is root. I don't work locally in my computer, but connected via ssh to the servers. These are my insights about the structure: Use of root is unsafe. No doubt about it and we should change this. What if another developer is hired? Could we work together in … -
Django UpdateView generic class
How can i access the object passed by the user inside a Generic view Class? In template, when the user clicks the link: <td><a href="{% url 'update_peon' pk=item.pk %}"><button class="btn btn-warning">Edit</button></a></td> this goes to urls.py: url(r'^update_peon/(?P<pk>\d+)$', views.UpdatePeon.as_view(), name='update_peon'), and my view: class UpdatePeon(generic.UpdateView): login_required = True template_name = 'appform/Peons/peon_form.html' model = Person form_class = PersonForm success_url = reverse_lazy('view_peons') I would like to access the item.attr1 or at least item.pk inside the class so i could change the model and form accordingly, something like: class UpdatePeon(generic.UpdateView): login_required = True template_name = 'appform/Peons/peon_form.html' if item['attr1'] == "Attribute1": model = model1 form = model1Form else: etc success_url = reverse_lazy('view_peons') I know how to do it in a normal function based class or even if i rewrite a class based view from scratch but i don't want to do that -
Check if a relation already exist between two entities/models having 2 lists/querysets of them
I have 3 models: A, B and C. A has a type that defines if B or C can connect to it B has a OnetoOneRelation to A C has a OnetoOne relation to A `class A(models.Model): type = models.SmallIntegerField(choices=A_TYPE_CHOICES, default=ACCOUNT_TYPE_B) class B(models.Model): a = A.objects.filter(type=A_TYPE_B) class C(models.Model): a = A.objects.filter(type=A_TYPE_C)` What I need: get all accounts that are type B but a B Objects is not related same as 1 for C So, I have: a_type_b = Account.objects.filter(type=ACCOUNT_TYPE_B) There are any was to check if B model/object is already attached/related instead of looping thru all accounts and check ?, because this can take a lot of time and queries and is not efficient Do no let C connect to a type_B account and vice-versa on model create/update. -
Django: how to query a form, and use results to populate another form
I have two Django forms. The first is to search for an experiment, which I validate to find it in the database. The second form is to obtain samples that were on that experiment. I am struggling to pass the information I require to the second form, without it being a problem when I try to validate it down the line. First Form and view: RunSearchForm: class RunSearchForm(forms.ModelForm): experiment_name = forms.CharField( required=True, label='Experiment_name:' ) choice = forms.ChoiceField( required=True, label='Primary or repeat samples?', widget=forms.RadioSelect, choices=( ('primary', 'Primary',), ('repeats', 'Repeats',)) ) class Meta: model = Run fields = ('experiment_name', 'choice',) def __init__(self, *args, **kwargs): super(RunSearchForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.layout = Layout( Field('experiment_name', css_class='search-row',), HTML('<br>'), Field('choice', css_class="search-form-label"), Submit('submit', 'Search experiment', css_class='upload-btn') ) self.helper.form_method = 'POST' clean(self): .....cleaning.... Views: class Search(View): runsearchform = RunSearchForm template_name = 'results/search_form.html' def get(self, request, *args, **kwargs): context = { 'sample_form': self.samplesearchform(), 'run_form': self.runsearchform(), } return render(request, self.template_name, context) def post(self, request, *args, **kwargs): context = {'run_form': self.runsearchform(),} run_form = self.runsearchform(request.POST) if run_form.is_valid(): run_obj = run_form.cleaned_data['experiment_name'] choice = run_form.cleaned_data['choice'] return HttpResponseRedirect( reverse('results:search_sample_run', kwargs={'run_id': run_obj.id, 'choice': choice, } )) else: context['run_form'] = run_form return render(request, self.template_name, context) So I search for an experiment, and it validates my form … -
Which front end framework to use with the Django Rest API Framework?
I have the Django Rest API project ready. Now I want to develop the Website which can access the Django Rest API for display the data or save the data to the database. So I want to develop the website which can be converted to the Desktop App (Using Electron) and to the Mobile App (Using PhoneGap). So which framework is good choice. Django APP Angular JS React JS Knockout JS or anything else. -
Rename apps for a minimal project
I'd like to rename myapp from block to article change the app directory name from block to article amend the installed apps in setting.py amend it in app.py delete migrations and make new When I try to login admin site, it report ModuleNotFoundError: No module named 'article' I found multiple answer to this question, but they are complicated than I simply re-start a new project. Is it possible a straight-forwards solution. -
how to match string with dataframe in python
I have one list as below listvalue = ["POS 541919XXXXXX5316 WWW PAYTM COM POS DEBIT","POS 541919XXXXXX5316 HASBRO CLOTHING POS DEBIT","Salary for the month of April 2018"] I have one dataframe as below variable value 0 ATM Cash withdrawal 8 Auto & Fuel fuel 16 Expense fees 17 Expense goods 18 Expense stationery 19 Expense purchase 20 Expense material 21 Expense telephone 24 Food/Restaurent food 25 Food/Restaurent catering 32 General others 40 Groceries big bazar 48 Income salary 49 Income deposit 50 Income rewards 56 Medical dr 57 Medical doctor 58 Medical dr. 59 Medical nursing 60 Medical pharmacist 61 Medical physician 62 Medical hospital 63 Medical medicine 64 Mobile recharge airtel 72 Payment tranfer 73 Payment payment 80 Shopping cloths 81 Shopping clothing 88 Travel travel I have to compare each listvalue in value dataframe. If any word of value from dataframe in listvalue, i want to print variable of that value