Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
TypeError : object of type 'bool' has no len()
I have the following code: store_id = 1 acc_id = str(store_id) print("type of acc_id is ", type(acc_id)) x = len(acc_id) print(x) if len(acc_id == 1): acc_id += '000' + acc_id # Results: # type of acc_id is <class 'str'> # 1 # ... # TypeError: object of type 'bool' has no len() Why am I getting this error when acc_id is clearly a string? -
django-filter searching on multiple fields and models
I'm looking for a way to filter two inputs(name and place) from two models (Photographer and Location); but, MultipleChoiceFilter seems like it doesn't work for me because I need to add more complex logic which performs in my custom filter as below. class SearchResultFilter(filters.FilterSet): name = filters.CharFilter('Photographer') place = filters.CharFilter(method='location_filter', distinct=True) class Meta: model = models.Photographer fields = ('name') def location_filter(self, queryset, name, value): """My complex logic""" . . . model = models.Location.filter(Q(location__icontains=value)) return model The question is " Is there a way I can put name input field in my location_filter, so that I can filter two inputs (name and place) in this function and return a wanted querySet from here". I tried to use self.name in location_filter; however, an error log produced. I guess "name" here is not an class variable -
What's the best approach to develop a creativity test application?
I'm going to develop an application for an Institute for School Development Research. The application will be used to test school childrens creativity in multiple ways. The layout should be like an examen with different exercises. It should also offer exercises where you can listen to a song and add sounds by pushing buttons, so that in a certain way you create a new song or audio trace. This trace and all the other results of the exercises in the end should be saved and the audio file should be reproducable, which means I want it to be saved in a way, so that I can listen to the created "song" afterwards. Finally the application will be developed in Python. Now my question: What is the best approach to develop such an application? Would you recommend a web based ot desktop based application? If desktop based, would you recommend using tkinter or sth different? And since I'm using the free Community Edition of Pycharm, I can't use webbframeworks like Django or flask, so creating a web app would be difficult, is that right? If I want to create a Web App, should I change my Development Environment to one, which … -
Selective images not showing up on Django app deployed on Heroku
I had 5 images on the team page of my project. I updated 3 of them. Now whenever I run the app on a localhost port, using python migrate.py, all updated images on the page are shown. As soon as I deploy the app on Heroku, 3 out of 5 images aren't updated. They still show a previous version. I tried deleting my browser cache, but to no avail. I thought maybe the URLs were pointing to a wrong directory, but the updated versions of 2 images are shown. I can't identify what the problem is. Project Structure - reviewer/team_page.html [ Image URL - "../static/team/xyz.png" ] static/team/ [contains images] -
how to make modal for a specific field not entire form django
i'm working on a project which it has inlineformset , i need to make a field in the child form modal not entire form class MobileCustomer(models.Model): customer = models.CharField(max_length=30) mobile = models.ManyToManyField(Mobile,through='SelectMobileCustomer') class SelectMobileCustomer(models.Model): mobile = models.ForeignKey(Mobile,on_delete=models.CASCADE,verbose_name='موبایل') item = models.ForeignKey(MobileCustomer,on_delete=models.CASCADE) quantity = models.PositiveIntegerField(default=1) price = models.PositiveIntegerField() imei = models.ManyToManyField(Imei) class Imei(models.Model): imei = models.CharField(max_length=50,verbose_name='IMEI',unique=True) mobile = models.ForeignKey(Mobile,on_delete=models.CASCADE) for example if quantity in SelectMobileCustomer equal to 4 then i should select 4 imei , i want to make imei field in SelectMobileCustomer as pop up input field (modal)? and my forms.py class MobileCustomerForm(forms.ModelForm): class Meta: model = MobileCustomer fields = ['customer'] class SelectMobileCustomerForm(forms.ModelForm): mobile = forms.ModelChoiceField(queryset=MobileStorage.objects.all()) imei = forms.ModelMultipleChoiceField(queryset=Imei.objects.all()) class Meta: model = SelectMobileCustomer fields = ['mobile','quantity','price''imei'] and this is my inlineformset MobileCustomerInlineFormSet = inlineformset_factory( MobileCustomer,SelectMobileCustomer,form=SelectMobileCustomerForm,fields=('mobile','quantity','price','imei'),extra=1) my templates look like this <form method="POST">{% csrf_token %} {{mobile_form.management_form}} <div class="col-6 inp text-center" style="border-radius: 10px !important;"> {{form.customer'}} </div> </div> </div> <!-- order --> <div class="col-12 p-0 border-top border-light "> <table class="customeTable col-12 table-responsive-sm info text-center table1 mx-auto mb-2 "> <!--Table head--> <thead> <tr > <th>some headers</th> </tr> </thead> <!--Table body--> <tbody class="tbody tb1 "> {% for mobile in mobile_form.forms %} <tr class="p-0 col-12"> <td class=""> {{mobile.imei | add_class:'col-12 text-center' }} </td> </div> </td> <td … -
Pass values from Django Template for-loop to views in Django
I have following products in the database: Html code for the above image: {% for crops_ordered_names,crops_ordered_images,crops_ordered_cost,crops_ava in total %} <tbody> <tr> <td data-th="Product"> <div class="row"> <div class="col-sm-2 hidden-xs"><img src="http://placehold.it/100x100" alt="..." class="img-responsive"/></div> <div class="col-sm-10"> <h4 class="nomargin">{{crops_ordered_names}}</h4> <p>Available amount: {{crops_ava}}</p> </div> </div> </td> <td data-th="Price" data-type="price">{{crops_ordered_cost}}</td> <td data-th="Quantity"> <input type="number" class="form-control text-center" data-type="quan" min="1" max="{{crops_ava}}" > </td> <td data-th="Subtotal" class="text-center" data-type="subtotal"></td> <td class="actions" data-th=""> <a href="{% url 'shopping_cart:delete_item' crops_ordered_names%}"> <button class="btn btn-danger btn-sm"><i class="fa fa-trash-o"></i></button> </a> </td> </tr> </tbody> How can I send the value quantity of each item to the django views to store quantity of each item to the respective product when I submit the form after entering all the quantities. I need to get value of quantity from the HTML code: <input type="number" class="form-control text-center" data-type="quan" min="1" max="{{crops_ava}}" > -
Can't fix Django SQLite3 database on Heroku
I am attempting to deploy my Django app to Heroku. It works fine on my computer, but when I push it to Heroku and try to go to the site I get a ProgrammingError. He is the error itself: relation "graph_mygraph" does not exist LINE 1: ...r"."product_ids", "graph_mygraph"."mix_id" FROM "graph_myg... Here is what I have tried so far: Deleting the heroku app and re-creating it Deleting the sqlite3 database running `./manage.py makemigrations' then './manage.py migrate' on my computer (works fine) running ./manage.py migrate on Heroku (I also get the error while doing this) Other information: I am using django_heroku This was working fine before, but my latest push seems to have broken it and I don't know why Thanks in advance. -
unknown url typ,'media/photo/ashu.jpg' Django
I am creating an api to get some details on excel sheet,while doing so i have added detais and images through admin panned,while fetching details using postman i am getting above error in related to image url. models.py class Task(models.Model): Name=models.CharField(max_length=50,null=False,blank=True) Image1=models.FileField(blank=True, default="", upload_to="media/images",null=True) views.py class TaskViewSet(viewsets.ViewSet): def list(self,request): try: output = io.BytesIO() workbook=xlsxwriter.Workbook(output) worksheet=workbook.add_worksheet() product=Task.objects.all() for pro in product: url=pro.Image1.url image_data=BytesIO(urlopen(url).read()) worksheet.insert_image(1,1,url,{'image_data',image_data}) workbook.close() output.seek(0) response = HttpResponse(output.read(),content_type='application/ms-excel') response['Content-Disposition']='attachment; filename="users.xls"' return response except Exception as error: traceback.print_exc() return Response({"message": str(error), "success": False}, status=status.HTTP_200_OK) -
django.db.utils.IntegrityError: NOT NULL constraint failed: new__basic_event.tag_id
class Tag(models.Model): name = models.CharField(max_length=100,null=True) def __str__(self): return self.name class Event(models.Model): EVENT_PURPOSE = ( ('Birthday','Birthday'), ('Meet Up','Meet Up'), ('Anniversary','Anniversary'), ('Festival','Festival'), ('General','General') ) tag = models.OneToOneField(Tag,blank=True,null=True,on_delete=models.CASCADE) event_id = models.AutoField(primary_key=True) organizer = models.ForeignKey(Host,null=True, on_delete=models.SET_NULL) event_date_time =models.DateTimeField(null=False,unique=True) event_purpose = models.CharField(max_length=12,choices=EVENT_PURPOSE) error: return Database.Cursor.execute(self, query, params) django.db.utils.IntegrityError: NOT NULL constraint failed: new__basic_event.tag_id -
Session ID and User Isolation not working in Django
I'm building a simple user registration and user log in web app. An important security feature Is to isolate users and supply them with separate Session ID's, so they cant see each others dashboard information. However, currently, when I log in with two separate users in two different windows, I get to see the dashboard of the last user that logged In. In the login view, I supply the SID in this way: request.session.create() Then I pass this SID with other account information to a class which I can access from the dashboard view In order to identify the user. After that, In the dashboard view, I check to see If the current SID is equal to the SID that I passed to the class in the login view. It looks like this: if request.session.session_key == Credentials.session_id: However, It seems like Django Is not isolating users and It's serving them the latest Information that was filled in the Class. How can I solve this and If possible for someone to provide some technical explanation, that would be great. -
make bootstrap tab refresh link when clicking on a tab
I am using Bootstrap4.4.5 and trying to implement tabs as below: <nav> <div class="nav nav-tabs" id="nav-tab" role="tablist"> <a class="nav-item nav-link active" id="nav-home-tab" data-toggle="tab" href="/home" role="tab" aria-controls="nav-home" aria-selected="true">Home</a> <a class="nav-item nav-link" id="nav-profile-tab" data-toggle="tab" href="/profile" role="tab" aria-controls="nav-profile" aria-selected="false">Profile</a> <a class="nav-item nav-link" id="nav-contact-tab" data-toggle="tab" href="/contacts" role="tab" aria-controls="nav-contact" aria-selected="false">Contact</a> </div> </nav> <div class="tab-content" id="nav-tabContent"> <div class="tab-pane fade show active" id="nav-home" role="tabpanel" aria-labelledby="nav-home-tab">...</div> <div class="tab-pane fade" id="nav-profile" role="tabpanel" aria-labelledby="nav-profile-tab">... </div> <div class="tab-pane fade" id="nav-contact" role="tabpanel" aria-labelledby="nav-contact-tab">... </div> </div> Please notice that the href is pointing to a specified url in my project. Indeed, I am using django and capturing that url to call a handler and do some work. But it does not work. Bootstrap does not change my url I tried to delete the attribute data-toggle="tab" but in that case, I see the url changing in the address field of my browser (for example becoming www.mysite.com/profile when I click the second tab), but the first tab stays active -
PermissionError: [Errno 1] Operation not permitted: '/Users/<local_path>/venv/pyvenv.cfg'
I am running a Django application with a few cron tasks. Whenever I run python manage.py crontab add to register the cron tasks, I get a "mail" in the Terminal showing the following traceback: Traceback (most recent call last): File "/Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.7/lib/python3.7/site.py", line 609, in <module> main() File "/Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.7/lib/python3.7/site.py", line 592, in main known_paths = venv(known_paths) File "/Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.7/lib/python3.7/site.py", line 510, in venv with open(virtual_conf, encoding='utf-8') as f: PermissionError: [Errno 1] Operation not permitted: '/Users/<local_path>/venv/pyvenv.cfg' I am running on macOS Catalina, python 3.7.3 in a virtual environment venv. I have tried giving full disk permission to bash, crontab, terminal, xcode and pycharm. I have also tried installing python versions 3.7.8 and 3.8.3 -
my scrapy save url of images but not file. UnidentifiedImageError
I use django, scrapy. I tried to scrape images from sites using spider. But I cant download. and I couldnt find out what's wrong. #error code 2020-07-13 21:36:58 [scrapy.pipelines.files] ERROR: File (unknown-error): Error processing file from <GET https://somesites.com.jpg> referred in <None> Traceback (most recent call last): File "/home/hong/.local/lib/python3.8/site-packages/scrapy/pipelines/files.py", line 496, in media_downloaded checksum = self.file_downloaded(response, request, info) File "/home/hong/.local/lib/python3.8/site-packages/scrapy/pipelines/images.py", line 108, in file_downloaded return self.image_downloaded(response, request, info) File "/home/hong/.local/lib/python3.8/site-packages/scrapy/pipelines/images.py", line 112, in image_downloaded for path, image, buf in self.get_images(response, request, info): File "/home/hong/.local/lib/python3.8/site-packages/scrapy/pipelines/images.py", line 125, in get_images orig_image = Image.open(BytesIO(response.body)) File "/usr/lib/python3/dist-packages/PIL/Image.py", line 2861, in open raise UnidentifiedImageError( PIL.UnidentifiedImageError: cannot identify image file <_io.BytesIO object at 0x7f74c3e1b040> #part of spider custom_settings = { 'ITEM_PIPELINES': { 'scraper.pipelines.MyItemPipeline': 999, 'scraper.pipelines.MyImagesPipeline': 999, } } item['image_urls'] = [response.xpath('//*[@id="main"]/ul/li[' + strver_of_number + ']//@src').extract()[1]] #part of django settings BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) MEDIA_ROOT = os.path.join(BASE_DIR, 'media') # for server path to store files in the computer MEDIA_URL = '/media/' # the reference URL for browser to access the files over Http #part of pipelines from fashion.models import ItemList class MyItemPipeline(ItemPipeline): ... , item_image=item['images'] ) class MyImagesPipeline(ImagesPipeline): def get_media_requests(self, item, info): for image_url in item['image_urls']: yield scrapy.Request(image_url) def item_completed(self, results, item, info): image_paths = [x['path'] for ok, x … -
How to call JS script from html as part of Python Django application
Using a Django/Python environment, I have a form being displayed and added a "Calculate" button which I want to use values from the form, do some calculations, and re-displays the new values on the form. The user can continue to do this until they are satisfied with the numbers, then they click the "Submit" button to save the data to the db. I have the form and submit working well. It's the calculate button I can't get to call the JS Script which is just a "Hello Alert" for now. Here are some code snippets of what I have and I need to know what goes in the URLs.py file and the views.py file. JS File (myjavascript.js) in the Static folder... function calculate() { alert("Hello World!"); } HTML File (registration.html). It's the "calculate_form" which is the form of concern ... {% extends "basic_app/base.html" %} {% load static %} {% block body_block %} <div class="jumbotron"> {% if registered %} <h1>Thank you for registering!</h1> {% else %} <h1>Register Here!</h1> <h3>Fill out the form:</h3> <form method="post" > {% csrf_token %} {{ user_form.as_p }} {{ profile_form.as_p }} {{ calculate_form.as_p }} {# these get passed in from views.py file as context dictionary #} <script type="text/javascript" … -
I want to show you my login view from my Django project; would like you to help in correcting it if any
Apparently the login view in my views.py does not show any error but it does not redirect to the homepage class Login(TemplateView): form_class = UserLoginForm model_name = AccountInfo template_name = "BudgetApp/login.html" template_name1 = "BudgetApp/Home.html" def get(self, request, *args, **kwargs): context = {} context["form"] = self.form_class return render(request,self.template_name,context) def post(self, request, *args, **kwargs): form = self.form_class(request.POST) if form.is_valid(): username = form.cleaned_data.get("username") password = form.cleaned_data.get("password") qs = AccountInfo.objects.get(username=username) print("query set",qs.isActive) if((qs.username==username) & (qs.password==password)): request.session["username"] = username context = {} context["qs"] = qs return render(request, self.template_name1, context) else: return redirect("login_user") else: return render(request, self.template_name,{"form":form}) Please look into this and tell me where do I have to rectify here. Thanks -
Django multy forms page with modal form
how to submit popup modal form values to session without other fields/forms validations? multi forms page: {% bootstrap_field bi.climatic_conditions class="mdb-select" layout='outline' size='sm' %} Add own weather conditions Click me* <div class="modal fade" id="costomWC" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header text-center"> <h4>Custom Weather Conditions</h4> <button type="button" class="close" data-dismiss="modal"> &times;</button> </div> <div class="modal-body"> {% include 'calculator/custom_weather.html' %} </div> <div class="modal-footer"> <a href="{% url 'custom_weather' %}"> <button type='button'>TEST</button> </a> </div> </div> </div> </div> -
Undefined In Console JQuery
I am working on a website using Django, i am a beginner in Jquery and i am trying to display an image using JQuery, when form is submitted. Image do not display and i am getting an error in console "Undefined". JQuery: var chatHolder = $('#chat-items') // below is the message I am receiving socket.onmessage = function(e) { var chatDataMsg = JSON.parse(e.data) var profile_pic = $('#avatarImg').attr("src"); console.log(profile_pic); chatHolder.append("<div class='media w-50 mb-3'>" + "<img src=" + profile_pic + " width='30' height='30' class='rounded-circle mt-1'/>" + "<div class='media-body ml-2'>" + "<div class='bg-light rounded py-2 px-3 mb-2'>" + "<p class='text-small mb-0 text-black'>" + chatDataMsg.message + "</p>" + "</div>" + "<p class='small text-muted'>" + newMonth + newDate + "<i class='fa fa-ellipsis-h float-right'></i>" + "</p>" + "</div>" + "</div>") } Template: <div class="px-4 py-3 chat-box bg-white" id='chat-items' style="height:435px;"> {% for chat in object.chatmessage_set.all %} {% if request.user != chat.user %} <!-- Sender Message--> <div class="media w-50 mb-3"> <img src="{{ chat.user.profile.profile_pic.url }}" id="avatarImg" width="30" height="30" class="rounded-circle mt-1"> <div class="media-body ml-2"> <div class="bg-light rounded py-2 px-3 mb-2"> <p class="text-small mb-0 text-black">{{ chat.message|emoticons }}</p> </div> <p class="small text-muted"> {{ chat.timestamp|date:'M j, Y, g:i a' }} <i class="fa fa-ellipsis-h float-right"></i> </p> </div> </div> {% endif %} {% endfor %} <form … -
Graphene GraphiQL does not work in browsers, but Insomnia client works just fine
I'm a beginner in GraphQL and have been doing some tutorials and simple projects with it. Today I was following a new tutorial and ran into something odd. The GraphiQL interface from graphene_django will not return anything in browsers. I get a different error in every browser: (Chrome) Cannot read property '1' of null (Firefox) match is null (Safari) null is not an object (evaluating 'match[1]') However, in Insomnia, everything works just fine. I would guess my code works fine since I am getting a response in Insomnia, but my browser just won't let me play. Does anyone know what this could be? -
(Django) How do I make the 'selected' option valid after altering a foreign key drop-down?
I have a model whose fields are a date and a foreign key to another model's text field: # models.py class Publications(models.Model): """A class for daily article publications""" date = models.DateField( help_text="date for this article to be published" ) headline = models.ForeignKey( Articles, help_text='The article to be published, represented by its headline' ) On the Admin 'Add' page for that model, I've added Javascript so that when I select a date from the calendar selector widget for date, the drop-down selector for the Articles FK is automatically restricted to the subset of Articles ready for publication on that day. This is accomplished by clearing the drop-down selector and then re-filling it with the results of an AJAX call to a backend view: // Javascript for Publications "Add" admin page // Grab the Article <select> element let artSelect = document.getElementById("id_headline"); // Clear it artSelect.innerHTML = ''; // Fill it with new <option> elements from 'data', a list of Article // headlines retrieved via AJAX for (var i=0; i<data.length; i++) { var opt = document.createElement('option'); opt.value = i; opt.innerHTML = data[i]; // If it's the first option, make it 'selected' if (i == 0) { opt.setAttribute("selected", ""); } artSelect.appendChild(opt); } If, after … -
How to send an "Access-Control-Allow-Origin" header using Django 3?
I'm new to server-side programming and I'm trying to get some information from the backend through the frontend. The backend, as indicated in the header, is written in Django. The frontend is written in React, if it's important. There is a view function on the backend, which only returns plain string: HttpResponse("Some useful information.") This string is available at: "http://localhost:8000/info/". I checked through the browser, it really works. So, I'm trying to get this string from the frontend, using axios library: axios.get("http://localhost:8000/info/").then(res => { console.log(res.data); }) An error occurs, when I'm trying to send request. It sounds like this: Access to XMLHttpRequest at 'http://localhost:8000/info/' from origin 'http://localhost:3006' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. There are no errors on the server side. It returns code 200. As far as I understand, the data are received on the frontend, but the browser blocks access to it, because the server must additionally attach an 'Access-Control-Allow-Origin' header. How can I send this header from the server? Should I configure something in the settings.py or modify the view function? Or maybe there is another solution? -
AzureDevOps Pipeline fails on creating database in Djano test
I have been trying to build an Azure DevOps Pipeline for CI/CD for my Django project. The code is being pulled from a github repo (and is actually deployed already on Azure app service). However, when I run the test on the Pipeline I get the following error when it runs python manage.py test: Creating test database for alias 'default'... pyodbc.OperationalError: ('HYT00', '[HYT00] [Microsoft][ODBC Driver 17 for SQL Server]Login timeout expired (0) (SQLDriverConnect)') ##[error]Bash exited with code '1'. I tried extensively to whitelist Azure DevOps but the error has persisted. How can I resolve this so that the Pipeline can run tests for CI/CD? -
Check if any object of a queryset is present in a m2m field
I have the following model : class SalesProject(models.Model): activeCustomer = models.ManyToManyField( 'CustomerInformation', through='ProjectActiveCustomer', related_name='activeCustomer') inactiveCustomer = models.ManyToManyField( 'CustomerInformation', through='ProjectInactiveCustomer', related_name='inactiveCustomer') Within my views , i wish to apply the following business logic: When adding new customerInformation to activeCustomer m2m relation , check if the instance that im adding exists in inactiveCustomer If true , Remove the customerInformation from the inactiveCustomer m2m relation The data which enters my view comes in the form of a queryset , therefore , the algo that decides this should be able to take in a queryset and check if any of the object in this queryset matches the objects in the inactiveCustomer m2m relation -
Why my email error It is not shown in my website page?
it does not work my email error in django i wanna make email error, when user fill the email form Instead to gmail. but It is not shown in my website page my django fill email eroor -
When I enter aws-acess-id and aws-secret-key /: "ERROR: NotAuthorizedError - Operation Denied. The security token included in the request is invalid:"
When I enter aws-acess-id and aws-secret-key I tried different aws keys too generated from "labs.vocareum.com" It throws errors: "ERROR: NotAuthorizedError - Operation Denied. The security token included in the request is invalid:" Error C:\Users>eb init -p python port-aws You have not yet set up your credentials or your credentials are incorrect You must provide your credentials. (aws-access-id): ------(enter key from aws account)------- (aws-secret-key): --------(enter key from aws account)---- ERROR: NotAuthorizedError - Operation Denied. The security token included in the request is invalid. ReEnter C:\Users>eb init -p python port-aws ERROR: The current user does not have the correct permissions. Reason: Operation Denied. The security token included in the request is invalid. ERROR: The current user does not have the correct permissions. Reason: Operation Denied. The security token included in the request is invalid. You have not yet set up your credentials or your credentials are incorrect You must provide your credentials. (aws-access-id): ------(enter key from aws account)------- (aws-secret-key): ------(enter key from aws account)------- ERROR: NotAuthorizedError - Operation Denied. The security token included in the request is invalid. -
Django-rest-framework + CSV Export and Import
What's the best approch to use in order to export csv files ? I tried the export method in utils.py and the export in views.py and usinga route but didn't work for me and the api shutdown. def export(self, request, *args, **kwargs): response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="model.csv"' serializer = self.get_serializer( Model.objects.all(), many=True ) header = ModelSerializer.Meta.fields writer = csv.DictWriter(response, fieldnames=header) writer.writeheader() for row in serializer.data: writer.writerow(row) return response