Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django website with dynamic side navigation menu
Can someone please advise if it is posaible to build a website using django that has a dynamic menu that can be managed from the admin area? I want to be able to add menu items with urls that it should render when selected. If yes, Can you please share some insights interms of what libraries can be used with some samples. This seems to be challenging one but I am hoping that there might some super expert who might have cracked a solution for this requirement. Please advise. Thank you. -
Need solution to display media files in template when debug == false
My Django project is displaying media in templates if debug == True no problem at all but the problem arises when I set debug to False Django fails to load them if debug == False( There are some solutions out there but I am not able to wrap my head around them as I am new to Django ). Can someone please tell me what is the best and easiest way to solve this issue? Note: I want to host my website on my local wifi (not on pythonanywhere or any other web hosting service) Thanks in advance. -
Unable to get images on excel sheet using OPENPYXL package Django
I am creating an api to get images from django model to excel sheet.I am using openpyxl package.But bY GET operation on postman getting only the url of the image. models.py class Task(models.Model): Id=models.IntegerField() Name=models.CharField(max_length=50,null=False,blank=True) Image1=models.FileField(blank=True, default="", upload_to="media/images",null=True) Image2=models.FileField(blank=True, default="", upload_to="media/images",null=True) Date=models.DateField(null=True,blank=True) def __str__(self): return str(self.Name) view.py class TaskViewSet(viewsets.ViewSet): def list(self,request): try: queryset=Task.objects.all() response = HttpResponse(content_type='application/ms-excel') response['Content-Disposition']='attachment; filename="users.xls"' wb=openpyxl.Workbook() ws=wb.active row_num=0 columns=['Id','Name','Image1','Image2','Date'] for col_num in range(len(columns)): c = ws.cell(row=row_num + 1, column=col_num + 1) c.value = columns[col_num] for obj in queryset: row_num+=1 row = [ obj.Id, obj.Name, obj.Image1.url, obj.Image2.url, str(obj.Date), ] for col_num in range(len(row)): c = ws.cell(row=row_num + 1, column=col_num + 1) print(c) c.value = row[col_num] print(c.value) wb.save(response) return response except Exception as error: traceback.print_exc() return Response({"message": str(error), "success": False}, status=status.HTTP_200_OK) -
How to test a named CheckConstraint or ValidationError is raised in unittests?
I am unittesting validations and checkconstraints on my model: class MyModel(models.Model): title = models.CharField() class Meta: models.CheckConstraint( check=~Q(title='Word'), name='title_cannot_be_word' ), def clean(self): error_dict = {} if self.title == 'Word': error_dict['title'] = 'Title can not be Word' if error_dict: raise ValidationError(error_dict) In my tests.py: def test_validation(self): with self.assertRaises(ValidationError): m = MyModel(title='Word') m.clean() def test_constraint(self): with self.assertRaises(Integrity): m = MyModel.objects.create(title='Word') This all works fine, however in practice I have multiple CheckConstraints and ValidationErrors for different fields, so I want to be able to test that the correct error has been raised. How can I test a named CheckConstraint like title_cannot_be_word is raised, or a named ValidationError like error_dict['title'] is raised? -
Cannot Fetch Data in React Form to Django
I encountered this problem when I was trying to pass data in a form to the Django server. First of all, the alert message (defined in the login js file) said that both username and password is undefined. The react framework used is ant design. Here is the code: login.js (comment markers are provided along the way) import React from "react"; import ReactDOM from "react-dom"; import "antd/dist/antd.css"; import { Form, Input, Button, Checkbox, Row, Col } from "antd"; import { UserOutlined, LockOutlined } from "@ant-design/icons"; import jQuery from 'jquery'; function getCookie(name) { let cookieValue = null; if (document.cookie && document.cookie !== '') { let cookies = document.cookie.split(';'); for (let i = 0; i < cookies.length; i++) { let cookie = jQuery.trim(cookies[i]); if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } class NormalLoginForm extends React.Component { constructor(props) { super(props); this.state = {username: '', password: ''}; // <-- initial states this.handleUsernameChange = this.handleUsernameChange.bind(this); this.handlePasswordChange = this.handlePasswordChange.bind(this); this.handleSubmit = this.handleSubmit.bind(this); } handleUsernameChange(event) { this.setState({username: event.target.username}); } handlePasswordChange(event) { this.setState({password: event.target.password}); } handleSubmit(event) { alert('A name was submitted: ' + this.state.username); // <-- here are the alerts alert('Password is: ' + … -
global variable not defined in django
I have a problem with this code in django I have defined two global variables But Django does not identify them my view: global phone,rand_num def phone_login(request): if request.method == 'POST': form = PhoneLoginForm(request.POST) if form.is_valid(): phone = f"0{form.cleaned_data['phone']}" rand_num = randint(1000, 9999) api = KavenegarAPI('mytoken!') params = { 'sender' : '', 'receptor': phone , 'message' : rand_num } api.sms_send(params) return redirect('account:verify') else : form = PhoneLoginForm() return render(request,'account/phone_login.html',{'form':form}) def verify(request): if request.method == "POST": form = VerifyCodeForm(request.POST) if form.is_valid(): if rand_num == form.cleaned_data['code']: profile = get_object_or_404(Profile, phone = phone) user = get_object_or_404(User,profile__id = profile.id) login(request,user) messages.success(request,'logged in successfully' , 'success') return redirect('popasssts:all_posts') else: messages.error(request,'your code is wrong','warning') else: form = VerifyCodeForm() return render(request,'account/verify.html',{'form' : form}) my urls : path('verify/',views.verify,name='verify'), i have this error : NameError at /account/verify/ name 'rand_num' is not defined Request Method: POST Request URL: http://127.0.0.1:8000/account/verify/ Django Version: 3.0.7 Exception Type: NameError Exception Value: name 'rand_num' is not defined I want the user to enter the site after entering the SMS code. -
Module not found when deploying Django App to Digitalocean after change of project name
I am currently trying to deploy my Django Blog to Digitalocean. Fingers crossed, I had to change my project name from finsphere to stocksphere, so I refactored the associated folders, imports and related settings. However, when running python manage.py makemigrations on the server, it now throws the below error and I can't figure out in which file the error is raised or what might cause it at all: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/home/jonas/blog/env/lib/python3.6/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/home/jonas/blog/env/lib/python3.6/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/jonas/blog/env/lib/python3.6/site-packages/django/core/management/base.py", line 341, in run_from_argv connections.close_all() File "/home/jonas/blog/env/lib/python3.6/site-packages/django/db/utils.py", line 225, in close_all for alias in self: File "/home/jonas/blog/env/lib/python3.6/site-packages/django/db/utils.py", line 219, in __iter__ return iter(self.databases) File "/home/jonas/blog/env/lib/python3.6/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/jonas/blog/env/lib/python3.6/site-packages/django/db/utils.py", line 153, in databases self._databases = settings.DATABASES File "/home/jonas/blog/env/lib/python3.6/site-packages/django/conf/__init__.py", line 76, in __getattr__ self._setup(name) File "/home/jonas/blog/env/lib/python3.6/site-packages/django/conf/__init__.py", line 63, in _setup self._wrapped = Settings(settings_module) File "/home/jonas/blog/env/lib/python3.6/site-packages/django/conf/__init__.py", line 142, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 941, … -
how to deserilize geojson format in django rest framework serializer class
I want to deserialize geoJson format in Django rest serializer JSON like below "type": "Feature", "geometry": { "type": "Point", "coordinates": [125.6, 10.1] }, "properties": { "name": "Dinagat Islands" } } thanks -
Is there a way to count the sorted queryset using count instead of length?
I am working on search part of my project. On one of my filter, I have to use sorted() function. Code:- posts = Post.objects.filter(title__icontains=query) posts = sorted(posts, key=lambda obj: obj.titleFilter()) But, in other filters in the project, I don't have to use sorted as it can be done with django annotate and so on. So, in the template I usually have to do posts.count except for the title filter. My template, code:- <div>{{ posts.count }} results found.</div> I know, I can use if cases in template to work and apply length function like: <div> {% if title_filter %} {{ posts|length }} {% else %} {{ posts.count }} {% endif %} results found. </div> Also, I am not sure if length should be fine as there were some article not to use length for querysets. Thank you!!! Feel free to ask. -
I am trying to solve a circular import error,I spent hours in vain
I get this error: The included URLconf 'liskerproject.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. liskerproject is the root directory and contains the root "urls.py". Lisk is another directory that contains "url.py" This is how my root urls look like: from django.contrib import admin from django.contrib.auth import views as auth_views from django.urls import path,include from users import views as user_views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('edit/',user_views.edit,name='edit'), path('',include('Lisk.url')), path('register/',user_views.register,name='register'), path('login/',auth_views.LoginView.as_view(template_name='user_templates/login.html'),name='login'), path('logout/',auth_views.LogoutView.as_view(template_name='user_templates/logout.html'),name='logout') ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) This is how Lisk.url looks like: from django.urls import path from .views import Politics_topic,Questionpolitics,Updatepolitics,Politics_post_details,Deletepoliticspost,Profile,home from . import views urlpatterns = [ path('',home,name='home'), path('about/',views.about,name = 'about Lisk'), path('interests/',views.interests,name='interests'), path('profile/',Profile.as_view(template_name='lisk_templates/profile.html'),name = 'profile'), path('politics_topic/', Politics_topic.as_view(template_name='lisk_templates/politics_topic_template.html'), name='Politics_topic'), path('ask_politics/', Questionpolitics.as_view(template_name='lisk_templates/ask_politics_template.html'), name='ask_politics'), path('politicspost/<int:pk>/',Politics_post_details.as_view(template_name='lisk_templates/politics_post_details.html'), name='politics_post_details'), path('politicspost/<int:pk>/update/',Updatepolitics.as_view(template_name='lisk_templates/ask_politics_template.html'), name='updatepoliticspost'), path('politicspost/<int:pk>/delete/',Deletepoliticspost.as_view(template_name='lisk_templates/delete_politics_confirmation.html'),name ='deletepoliticspost') ] This how Lisk.views look like: from django.shortcuts import render from django.http import HttpResponse from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView from .models import Post, PoliticsPost from django.contrib.auth.decorators import login_required from django.urls import reverse_lazy from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin def home(request): return render(request, 'lisk_templates/home_template.html') def about(request): return render(request, 'lisk_templates/about_template.html') @login_required def interests(request): … -
how to count up and show database table entries Django
I am using chartsjs to generate charts. i have set my chart labels to: Index.py labels: [ {% for number in the_numbers_from_Floating %} "week " + {{ number.pk }}, {% endfor %} ], Views.py def index(request): the_numbers_from_Floating = Floating.objects.all() return render(request, "index.html", { 'the_numbers_from_Floating': the_numbers_from_Floating, }) my problem is that i am setting my label to the pk of my database table. If entries are deleted and new entries are added then the pk value rises. hence throwing off my labels seen below in the pictures. to fix this i should set it so that i am iterating up to the count() of my table. but how can i do that? -
AttributeError at /product/ Got AttributeError when attempting to get a value for field `quantity` on serializer `ProductStockSerializer`
I got an error while trying to use serializermethod field, please help AttributeError at /product/ Got AttributeError when attempting to get a value for field quantity on serializer ProductStockSerializer. The serializer field might be named incorrectly and not match any attribute or key on the QuerySet instance. Original exception text was: 'QuerySet' object has no attribute 'quantity'. class ProductSerializer(serializers.ModelSerializer): category = serializers.StringRelatedField() productstock = serializers.SerializerMethodField() class Meta: model = Product fields = [ 'pk', 'name', 'category', 'productstock' ] def get_productstock(self,obj): quantity=obj.productstock.filter(quantity=100) return ProductStockSerializer(quantity).data -
Django Web Development
I am a beginner in python and django and im practicing making a website for selling stuff. I am in the part where I am supposed to edit a card from bootstrap with the attributes from my models.py that is also in the views.py as a function. This is the html: (the 'base.html' is the starting template from bootstrap) {% extends 'base.html' %} {% block content %} <h1>Products</h1> <div class="row"> {% for product in products_dict %} <div class="col"> <div class="card" style="width: 18rem;"> <img class="card-img-top" src="{{ product.image_url }}" alt="Card image cap"> <div class="card-body"> <h5 class="card-title">{{ product.name }}</h5> <p class="card-text">{{ product.price }}</p> <a href="#" class="btn btn-primary">Add to cart</a> </div> </div> </div> {% endfor %} </div> {% endblock %} This is the result that i get: [As you can see the product.image_url is not showing and the cards just keep on stacking to the right and decrease in size, it does not come down.] Can anyone help me with this? Please tell if I need to share more info on this. -
Pinax , npm install error. i dont know what npm is , i just wanted to use this django framework . heard it makes development even faster
i hope this post finds u in the best of health . i hope your having an amazing day . you are awesome . i cant stop thanking you enough . dude your the best .Were no strangers to love . u know the rules so do i. .now can some one please look into the below error stack i was trying to setup pinax. im having such a hard time. (venv) C:\Users\ZinonYT\PycharmProjects\ReadyMade\mysite>npm install npm WARN deprecated chokidar@1.7.0: Chokidar 2 will break on node v14+. Upgrade to chokidar 3 with 15x less dependencies. npm WARN deprecated browserslist@2.11.3: Browserslist 2 could fail on reading Browserslist >3.0 config used in other tools. npm WARN deprecated request@2.79.0: request has been deprecated, see https://github.com/request/request/issues/3142 npm WARN deprecated request@2.88.2: request has been deprecated, see https://github.com/request/request/issues/3142 npm WARN deprecated left-pad@1.3.0: use String.prototype.padStart() npm WARN deprecated browserslist@1.7.7: Browserslist 2 could fail on reading Browserslist >3.0 config used in other tools. npm WARN deprecated mkdirp@0.5.1: Legacy versions of mkdirp are no longer supported. Please update to mkdirp 1.x. (Note that the API surface has changed to use Promises in 1.x.) npm WARN deprecated fsevents@1.2.13: fsevents 1 will break on node v14+ and could be using insecure binaries. Upgrade … -
Django: Checking if static file exists
Hope you're doing well. I've got a django view that needs to check to see if a static file with a known path exists. I'm currently trying to use os.path.isfile(), but I have a feeling this is the wrong approach. views.py: import os def knighthood_ceremony(warrior): narration_path = static("polls/narrations/{}/{}.mp3".format(queen_name,warrior.name)) is_to_play_narration = os.path.isfile(narration_path) settings.py: STATIC_URL = '/static/' Structure: mysite mysite settings.py polls static polls narrations 5 1.mp3 views.py otherproject This gives local vars: narration_path = '/static/polls/narrations/5/1.mp3' is_to_play_narration = False But, there is a file at: C:\Users\{USER}\mysite\polls\static\polls\narrations\5\1.mp3 Why can't os.path.isfile see it? Any advice will be greatly appreciated! -
How to fetch data from database django
I have created a CustomerRegistration model and I want that if the phone no exists in the database, then all the details of the customer will display automatically in form. here is my models.py class CustomerRegistration(models.Model): name = models.CharField(max_length=254, null=False) email = models.EmailField(max_length=254, null=False) date_of_birth = models.DateTimeField(null=False) country_id = models.ForeignKey('accounts.Country', null=False, on_delete=models.CASCADE, related_name='Country') state_id = models.ForeignKey('accounts.State', null=False, on_delete=models.CASCADE, related_name='State') cities_id = models.ForeignKey('accounts.City', null=False, on_delete=models.CASCADE, related_name='city') address = models.CharField(max_length=254, null=False) refernce_by_person_name = models.CharField(max_length=254, null=False) refernce_by_person_contact_no = models.IntegerField(null=True) phone_no = models.IntegerField(null=False, primary_key=True) alternate_no = models.IntegerField(null=False) hobbies = models.CharField(max_length=254) def __str__(self): return self.name -
Disconnect() method of Django Channels WebSocketConsumer not being called
I have the following class which is inheriting from the WebSocketConsumer: from channels.generic.websocket import WebsocketConsumer from channels.exceptions import StopConsumer class MyConsumer(WebsocketConsumer): def connect(self): self.accept() def receive(self, text_data=None, bytes_data=None): data = json.loads(text_data) n = data["number"] for i in range(n): self.send(json.dumps({"number":i})) def disconnect(): raise StopConsumer The input JSON contains only a single parameter called number. I am testing this code using a chrome plugin. When I open the connection and close it without sending any message, the disconnect method is executed as expected. When the number is for example 100 and the loop inside the receive method is not yet finished and I disconnect in between, the disconnect method is not called and I get the following error: ERROR - server - Exception inside application: Attempt to send on a closed protocol. File "MyConsumer.py", line 2, in receive self.send File "python3.6/site-packages/channels/generic/websocket.py", line 69, in send {"type": "websocket.send", "text": text_data}, File "python3.6/site-packages/channels/consumer.py", line 107, in send self.base_send(message) File "python3.6/site-packages/asgiref/sync.py", line 64, in __call__ return call_result.result() File "/usr/local/var/pyenv/versions/3.6.10/lib/python3.6/concurrent/futures/_base.py", line 432, in result return self.__get_result() File "/usr/local/var/pyenv/versions/3.6.10/lib/python3.6/concurrent/futures/_base.py", line 384, in __get_result raise self._exception File "python3.6/site-packages/asgiref/sync.py", line 78, in main_wrap result = await self.awaitable(*args, **kwargs) File "python3.6/site-packages/channels/sessions.py", line 220, in send return await self.real_send(message) File "python3.6/site-packages/daphne/server.py", … -
How could I search a tag to get a page instances by API?
**I want to search a tag like below** search_query = request.GET.get('query', None) # via this method, I can get some page instances which title or intro contain search_query keyword search_results = ProductionPage.objects.live().search(search_query) is there any ways to get result where search_query equal to a tag? -
Use the same file object for all notification instances
In my admin panel I have separate page with form when on submit I create Notification objects for all users. In this form I have an image field which I want to attach to all created Notification instances. We use the S3 servers and S3BotoStorage accordingly. My goal is to upload file from form ONCE and then bind it to all Notification objects. The issue that I have that on model save file is uploaded once again, which is undesirable, because in the end I will have a lot of duplicate images on mu S3 server. File field in my model Notification is declared like this: file = SVGImageModelField( verbose_name=_("icon"), upload_to=get_file_upload_path, null=True, validators=[ImageSizeValidator(100, 100, 500, 500, square=True)], ) And I handle file uploading like this: filename = form.upload_image_and_get_url()[0] # this method uploads file via default storage for user in users_to_send_notification.iterator(): notification = deepcopy(base_notification) file = default_storage.open(filename) notification.file = file notification.receiver = user notifications_to_users.append(notification) notifications = Notification.objects.bulk_create(notifications_to_users) In the debugger session I can see that the model in initialized with correct file, but after save it has different URL. (Pdb) notification.file <ImageFieldFile: 9638e20f-d213-47a0-8407-392d9922fd03.jpg> (Pdb) filename '9638e20f-d213-47a0-8407-392d9922fd03.jpg' (Pdb) n > /app/curerate/apps/cures/admin_views.py(106)send_notification() -> notifications_to_users.append(notification) (Pdb) notification.save() (Pdb) notification.file <ImageFieldFile: notification/20/07/e4a1f3fad0a047cea49b58114069a8cb.jpg> Is there a … -
Get the URL of the file I just uploaded via form in Django
I have this model with a FileField class Attachment(models.Model): file = models.FileField(upload_to='%Y/%m/%d/') timestamp = models.DateTimeField(default=timezone.now) Uploading is done with this form class AttachmentForm(ModelForm): class Meta: model = Attachment fields = ['file'] and this js function upload(event) { event.preventDefault() var data = new FormData($('#attachment_form').get(0)) $.ajax({ url: $(this).attr('action'), type: $(this).attr('method'), data: data, cache: false, processData: false, contentType: false, }) $('#id_file').val('') // send message to server chatSocket.send( JSON.stringify({ command: 'send', room: currentRoom, // message: ?? }) ) return false } $(function () { $('#attachment_form').submit(upload) }) I am using this form inside a real-time chat application. What I want is the following: the user uploads a file, then the javascript will send a message to the websocket containing the URL of the newly uploaded file, so the server can broadcast the attachment to other users. How do I get the URL of the file I just uploaded? Keep in mind I can't just construct it with MEDIA_ROOT + whatever the upload_to field says + filename, as for example if two files with the same name are uploaded, Django will fill the second one with a few characters at the end of the name. -
Write an explicit `.update()` method for serializer
How can i update my user profile using serializer, I got this error when i update my user profile: Write an explicit .update() method for serializer accounts.serializers.AccountProfileSerializer, or set read_only=True on dotted-source serializer fields. class AccountProfileSerializer(serializers.ModelSerializer): gender = serializers.CharField(source='accountprofile.gender') phone = serializers.CharField(source='accountprofile.phone') location = serializers.CharField(source='accountprofile.location') birth_date = serializers.CharField(source='accountprofile.birth_date') biodata = serializers.CharField(source='accountprofile.biodata') class Meta: model = User fields = ('first_name', 'last_name', 'email', 'last_login', 'date_joined', 'gender', 'phone', 'location', 'birth_date', 'biodata') class AccountProfileViewSet(APIView): permission_classes = [ permissions.IsAuthenticated, ] def get(self, request, format=None): profile = User.objects.get(pk=self.request.user.pk) serializer = AccountProfileSerializer(profile, many=False) return Response(serializer.data) def put(self, request): profile = User.objects.get(pk=self.request.user.pk) serializer = AccountProfileSerializer(profile, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_200_OK) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
When I try to edit a file with .write() it adds a lot of blank new lines
I am trying to change the content of a file with this code. When I edit the file it works, but it also adds a lot of additional blank new lines. def edit(request,name): if request.method=="GET": content=util.get_entry(name) return render(request,"encyclopedia/edit.html",{ "content":content, "name": name }) else: entry = open(f"./entries/{name}.md","w+") entry.write(request.POST["content"]) entry.close() return redirect(f"/wiki/{name}") This is the file # Python Python is a programming language that can be used both for writing **command-line scripts** or building **web applications**. -
Change int value to .00 format
I have a dataframe - year month type amount 0 2019 9 Not Applicable 8000.00 1 2019 10 Not Applicable 7500.00 2 2019 11 Goods & Services 14000.35 3 2019 11 Not Applicable 7500.00 4 2019 12 Goods & Services 10499.00 5 2019 12 Not Applicable 9801.00 I have column amount fully round of but I want to convert another column month to this format like this - year month type amount 0 2019 9.00 Not Applicable 8000.00 1 2019 10.00 Not Applicable 7500.00 2 2019 11.00 Goods & Services 14000.35 3 2019 11.00 Not Applicable 7500.00 4 2019 12.00 Goods & Services 10499.00 5 2019 12.00 Not Applicable 9801.00 How can I achieve this thing. -
Is there a way to create as many image fields i as the number of integer field's input in Django [closed]
ex) in Django's model.py class Page(model.Model): count = models.PositiveIntegerField() ..... If I enter 5 in the count, I want to code so that there are 5 image fields. -
Converting recovered file to .cs
I just recovered files I deleted by mistake from Visual Studio and the type of the file recovered is File. How can I convert them to .cs files in order to add them to my classlib in my project?