Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Static files not found - Site works but not pulling through static files - 404 console message
I am receiving a 404 for my static files, pages load but when inspect the console it relays the following errors, i've been sratching my head for while on this one. Would someone be able to point me in the right direction, it would be massively appreciated!: 127.0.0.1/:10 GET http://127.0.0.1:8000/static/css/all.css net::ERR_ABORTED 404 (Not Found) 127.0.0.1/:12 GET http://127.0.0.1:8000/static/css/bootstrap.css net::ERR_ABORTED 404 (Not Found) 127.0.0.1/:14 GET http://127.0.0.1:8000/static/css/style.css net::ERR_ABORTED 404 (Not Found) 127.0.0.1/:16 GET http://127.0.0.1:8000/static/css/lightbox.min.css net::ERR_ABORTED 404 (Not Found) 127.0.0.1/:26 GET http://127.0.0.1:8000/static/js/jquery-3.3.1.min.js net::ERR_ABORTED 404 (Not Found) 127.0.0.1/:28 GET http://127.0.0.1:8000/static/js/lightbox.min.js net::ERR_ABORTED 404 (Not Found) 127.0.0.1/:27 GET http://127.0.0.1:8000/static/js/bootstrap.bundle.min.js net::ERR_ABORTED 404 (Not Found) 127.0.0.1/:29 GET http://127.0.0.1:8000/static/js/main.js net::ERR_ABORTED 404 (Not Found) 127.0.0.1/:28 GET http://127.0.0.1:8000/static/js/lightbox.min.js net::ERR_ABORTED 404 (Not Found) 127.0.0.1/:29 GET http://127.0.0.1:8000/static/js/main.js net::ERR_ABORTED 404 (Not Found) Here's some of the code from the settings.py file: DEBUG = True TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] STATIC_ROOT= os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' STATICFILES_DIR =[ os.path.join(BASE_DIR, '/btre/static/') ] Here's the base.html file: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- Font Awesome --> <link rel="stylesheet" href="{% static 'css/all.css' %}"> <!-- Bootstrap --> <link rel="stylesheet" href="{% static 'css/bootstrap.css' … -
RuntimeError: There is no current event loop in thread 'Dummy-2' - Running a Django API with mod_wsgi
I have a Django API connected with mod_wsgi (python3.8) in the Ubuntu-20.4 ec2 instance. When I'm running this using the Public DNS of the Ec2 instance, I'm getting this error. How to resolve this Error: There is no current event loop in thread 'Dummy-2'. Django Version: 3.1.4 Exception Type: RuntimeError Exception Value: There is no current event loop in thread 'Dummy-2'. Exception Location: /usr/lib/python3.8/asyncio/events.py, line 642, in get_event_loop Python Executable: /home/ubuntu/django_project/env/bin/python3 Python Version: 3.8.5 Python Path: ['/home/ubuntu/django_project', '/usr/lib/python38.zip', '/usr/lib/python3.8', '/usr/lib/python3.8/lib-dynload', '/home/ubuntu/django_project/env/lib/python3.8/site-packages'] Server time: Sun, 20 Dec 2020 14:40:28 +0000 Events.py def get_event_loop(self): """Get the event loop for the current context. Returns an instance of EventLoop or raises an exception. """ if (self._local._loop is None and not self._local._set_called and isinstance(threading.current_thread(), threading._MainThread)): self.set_event_loop(self.new_event_loop()) if self._local._loop is None: raise RuntimeError('There is no current event loop in thread %r.' % threading.current_thread().name) return self._local._loop -
django SITE_ID by query
I have a django app. I'm adding a second site. So now I need to set SITE_ID correctly. This is easy enough, except that since it is the primary key id in the Site table, this means the value is dependent on the order in which sites have been added (and, eventually, deleted). That's fragile, without even discussing how developers will sort this if they've done any scratch work in that table. Much better to set it by query. SITE_ID = Site.objects.get(name='my_site_name').id But the settings_myapp.py file, which sets WSGI_APPLICATION, is pretty much the only one that might know which app I'm running. I could try modifying settings in that site-specific settings file, but importing settings at that point leads to an error that SECRET_KEY is not yet defined. Is there a robust way to do this? -
Django Model Form is not saving data to database, but object is created
I'm using a model form and a class based view and I'm trying to save user post model to db. The problem is that UserPost object is created (I've printed it in console and it has all the data and every time when I create new it has new id, so it seems it works) but nothing is saved to database. I'm not sure where the problem might be. Do you have any idea? views.py class CompletePost(View) def get(self, request, *args, **kwargs): post_form=myForms.UploadPostForm() return render(request,'shop/create_post.html',{'post_form':post_form}) def post(self, request, *args, **kwargs): post_form=myForms.UploadPostForm(request.POST) print(request.user.id) if post_form.is_valid(): user_post_v=post_form.save() transaction.commit() models.py class UserPost(models.Model): user_id=models.ForeignKey(Account,on_delete=models.CASCADE) title=models.CharField(max_length=255) text=models.TextField(null=True) category=models.ForeignKey(Category,null=True,on_delete=models.SET_NULL) is_used=models.BooleanField(default=False) price=models.IntegerField(default=0) created_at = models.DateField(auto_now_add=True) updated_at = models.DateField(auto_now=True) is_active = models.BooleanField(default=True) def __unicode__(self): return self.id def get_absolute_url(self,**kwargs): return reverse_lazy('index') -
How to slice items generated from a forloop with conditionals in django
I have a list of products, and I filter through them to get those with a specific category name , how can I slice the resulting items to limit the number shown {% for product in products %} {% if product.category.name == 'specified category' %} <div>{{ product.name }}</div> {% endif %} {% endfor %} -
What is the easiest way to load JSON data from API to Django Template with minimum JavaScript usage
I am looking for the easiest way to load JSON data from API in Django Template without page refresh. I really like to stick with the Django style of Coding and I am new to JavaScript. I have several views in my project that read data from JSON APIs and I am reading them in my views.py and passing the results to templates. Currently, I am refreshing my pages every 10 seconds to show the latest data. But I need to do this without the complete page refresh. Is there any way to achieve this without re-writing everything in JavaScript? If not what is the closest alternative solution? I have read several answers about Ajax calls and also this detailed answer about django-channels. But all of them involve a lot of JavaScript. I would appreciate any suggestion that will make my work easier than these. Below is my example view. (Please note that this is only an example and I have several similar views in my project. That is also the reason why I want to avoid writing custom JavaScript for each view) # views.py import requests class MyView(TemplateView): def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['data'] = requests.get('https://url_to_my_json').json() return context … -
How to create a Django group and assign the group to certain models?
I would like to know how to create groups in django and assign the group to certain models. How can I do this? -
How can i use nested serializer inside the same serializer?
class UserViewSerializer(DynamicFieldsMixin,serializers.ModelSerializer): followers_set = UserViewSerializer(required=False,many=True) class Meta: model = User fields = ('id','email','username','password','followers_set') depth = 2 is there anyway i can use this function without getting this error? followers_set = UserViewSerializer(source='follows',required=False,many=True) NameError: name 'UserViewSerializer' is not defined i tried SerializerMethodField but then i can't use depth option there following_set = serializers.SerializerMethodField() def get_following_set(self, user): return UserViewSerializer(User.objects.filter(follows__author=user), many=True).data using SerializerMethodField gives me error of: RecursionError at /api/users/ maximum recursion depth exceeded Can somebody help me please? -
django channel CancelledError
I'm using the docker to run the django project on server. But, for somehow this error below found after I added new function check_docker_container_status to check the container. This is the error that come from sentry, and I have no error log on my django. But, the problem is for somehow our server also down because this CancelledError. CancelledError: null File "channels/http.py", line 192, in __call__ await self.handle(body_stream) File "asgiref/sync.py", line 304, in __call__ ret = await asyncio.wait_for(future, timeout=None) File "asyncio/tasks.py", line 414, in wait_for return await fut Trying to create the docker ssh connection. from channels.generic.websocket import WebsocketConsumer class DockerSSH(WebsocketConsumer): def connect(self): self.accept() .... try: self.client.inspect_image(full_image_name) except docker.errors.ImageNotFound: pull_docker_image(self.client, full_image_name) container_id, container_is_running = check_docker_container_status(self.client, container_name) def close(self, close_code): logger.debug("### onclose triggered") self.disconnect(1) def disconnect(self, close_code): # Close Thread self.stop_thread = True # Close Socket if self.tls: self.socket.sendall('stop\r\n'.encode('utf-8')) else: self.socket._sock.send('stop\r\n'.encode('utf-8')) logger.debug("### Closing the socket and containers") # socket close self.socket.close() # Clean up the container self.client.stop(self.container_id) self.client.wait(self.container_id) self.client.remove_container(self.container_id) logger.info("## Stopped the container: " + str(self.container_id.encode('utf-8'))) # Close the client connection self.client.close() which is the function of check_docker_container_status is: def check_docker_container_status(client, container_name): # print(dir(client)) """ ['__attrs__', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__enter__', '__eq__', '__exit__', '__format__', '__ge__', '__getattribute__', '__getstate__', '__gt__', '__hash__', '__init__', … -
Configuring Gunicorn with nginx - nginx displaying 500 Internal Server Error when running on port 8000
I'm having issues while setting up nginx and Gunicorn on my local computer (not the server). I have a Django project and I want to be able to access it via http://localhost:8000/. Before my nginx was functional, my Gunicorn server was able to start successfully. However, once I got my nginx server configured, now my Gunicorn server won't start because nginx is already running on my localhost on port 8000. When I visit http://localhost:8000/ I get 500 - Internal Server Error. When I visit http://localhost:80/, however, I get Welcome to nginx! web page. To configure nginx and Gunicorn, I followed this guide, skipping steps 5 to 7 (inclusive). I have to note that in my /etc/nginx the sites-available and sites-enabled directories didn't exist, so I had to make them. I have only two files in my /etc/nginx/sites-available directory - default and mydjangoproject. Both have the same contents and both have their symbolic links in /etc/nginx/sites-enabled. Their contents are: server { listen 8000; server_name 127.0.0.1; location = /favicon.ico { access_log off; log_not_found off; } location /production_static/ { root /home/john/Documents/Django_projects/mydjangoproject/Version_2/mydjangoproject; } location / { proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_pass http://127.0.0.1:8000; } } Here are … -
Generate video requests to a server running at an IP and Port
I have a simple question that can I generate traffic (or not) on a (self-created and accessible) video server that is running on port 8000? I want to generate the traffic for a specific process, not on an IP (what most of the tools provide). So far, I am unable to find any tools that allow us to generate traffic on a specific port. If there is any, please inform me about the options that are available. Actually, I want to observer/analyze the traffic statistics using any monitoring tools. The video server is written in python3 created under Django Framework. -
local variable 'final_result' referenced before assignment I am making an django calculator web app and i got stuck with this error
Currently, I am building a django powered UI Caculator app and I got stuck with this error.. I can't able to debug it. Whatever I'm to trying is not working at all. I mean i don't why it is telling me final result referenced before it gets assgined while i have already assigned final_result and then i have reference final_result Views.py def index(request): if request.method=="POST": values=request.POST['values'] #string having whole ques print(values) vals=re.findall(r"(\d+)",values) #extrect values operators=['+','x','÷','-','%'] opr=[] for v in values: for o in operators: if v==o: opr.append(o) print(opr) #extrect operators print(re.findall(r"(\d+)",values)) for o in opr: if o=='÷': i=opr.index(o) res=float(vals[i])/float(vals[i+1]) vals.remove(vals[i+1]) opr.remove(opr[i]) vals[i]=str(res) print(vals) print(opr) elif o=='x': i=opr.index(o) res=float(vals[i])*float(vals[i+1]) vals.remove(vals[i+1]) opr.remove(opr[i]) vals[i]=str(res) print(vals) print(opr) elif o=='+': i=opr.index(o) res=float(vals[i])+float(vals[i+1]) vals.remove(vals[i+1]) opr.remove(opr[i]) vals[i]=str(res) print(vals) print(opr) else: i=opr.index(o) res=float(vals[i])-float(vals[i+1]) vals.remove(vals[i+1]) opr.remove(opr[i]) vals[i]=str(res) print(vals) print(opr) if(len(opr)!=0): if opr[0]=='÷': result = float(vals[0])/float(vals[1]) elif opr[0]=='x': result = float(vals[0])*float(vals[1]) elif opr[0]=='+': result = float(vals[0])+float(vals[1]) else : result = float(vals[0])-float(vals[1]) final_result=result print(final_result) res=render(request,'index.html'{'result':final_result,'values':values}) return res -
Django migrate - django.db.utils.OperationalError: attempt to write a readonly database
I have read the answers to similar (same) questions and the solutions have not worked for me. I have a django application running with Apache2 webserver, and the user is set to the default www-data. Currently, www-data has full access to the db. This was working fine until couple of commits ago and I'm clueless at exactly what went wrong (Since I didn't touch the database at all during the period). Another thing to note is that makemigrations work perfectly fine, and the database is editable without errors in the django admin console. Currently, this is my permission settings for the db: The error message is: Any help would be appreciated thanks! -
"Invalid password format or unknown hashing algorithm." Django - new user
I am trying to create a new user for my application. I am able to create a new user but the on opening django admin page the password is shown as "Invalid password format or unknown hashing algorithm." I have seen similar questions where the answer was to set account.set_password(password) I have tried this but it did not work for me. Here is my code Serializer.py class RegistraionSerialzer(serializers.ModelSerializer): password2 = serializers.CharField(style={'input_type':'password'},read_only=True) class Meta: model = User fields = ('phone','name','password','password2','user_type','email') extra_kwargs = { 'password': {'write_only' : True}, } def save(self): print('here') account = User( phone = self.self.validated_data['phone'], email = self.self.validated_data['email'] ) account.create_user() password = self.validated_data['password'] password2 = self.validated_data['password2'] if password != password2: print(password) return serializers.ValidationError({'password':'password mismatch'}) print(password) account.set_password(password) account.save() Views.py @api_view(['POST']) def Registraion(request): serializer = RegistraionSerialzer(data=request.data) data = {} print('reg vie') if serializer.is_valid(): account = serializer.save() data['response'] = "Successfully registered " data['name'] = account.name data['password'] = account.password print(data) else: print(serializer.errors) return Response(data) -
Django query for matching 'cousin' objects (with same grandparent)
I am trying to write some validations on form input and need to check that the instance being created doesn't already exist under the same grandparent. The field I am validating against isn't a primary key as it can exist outside the 'family'. I can't seem to think of an appropriate query for this but so far I have the following which works: existing_parents = Parent.objects.filter(grandparent=active_parent.grandparent) for parent in existing_parents: existing_children = parent.children.all() for children in existing_children if existing_children.identifier == identifier: self._errors["form_field"] = self.error_class( ["That child already exists"] ) else: pass Just wondered if there was a lookup I can do that simplifies it? -
Django - How to pass multiple parameters to URL
I have created a Listings Page where all listings can be searched. From there, a user can click on any particular listing to see further detail. When I go to individual listing page, I am displaying Breadcrumb to provide an option to go back to Search results (which was previous Listings page). The issue is I am not able to pass 2 parameters (one containing the previous URL so that I can use that for Breadcrumb back to search results) while calling individual listing page from listings page. Please see main code: views.py def listing(request, listing_id, query): listing = get_object_or_404(Listing, pk=listing_id) context = { 'listing': listing, 'query':query } return render(request, 'listings/listing.html', context) HTML template {% url 'listing' listing_id=listing.id path=12 %} I tried using {{ request.get_full_path }} to find path and then add to parameter but its not working. Any suggestions on how to capture URL will be appreciated. -
How to auto increment a model field in django admin form by having add another on the side?
I have this model: class BlogPost(models.Model): author = models.CharField(max_length=64, default='Admin') image = models.ImageField(blank=True, null=True) title = models.CharField(max_length=255) caption = models.CharField(max_length=500) content = RichTextUploadingField() # todo support for tags tags = models.CharField(max_length=255, default='travel') #todo date_created = models.DateField() Now in tags field, I want to give multiple strings like #tips, #travel, etc on the same field. What I want is there should be like an add or increment tag, which when I click will show another tag field appears on the admin form and the user can adder another tag. My backend is not on the regular HTML page. I have customized the default Django admin page for the backend using the material package. That is I cant use button tag and all. How can I achieve this?? I have an image attached which explains better. Image here -
Permissions in DRF + Vue
I working on a project that has these models Instructor, Student, Review, Class. only a Student that has a Class with Instructor can send a Review. In the backend, I have a custom permission IsStrudentOfInstructor to determine a user can send a Review to an Instructor or not! and it works fine! Question: How the frontend developer can determine to show the review form to the requested user or not? Do I need to do any more work for that as a backend developer? The frontend framework is Vue and the backend framework is Django Rest -
NameError: name 'Order' is not defined
I Just Can't Access 'Order' in views.py's Function. i tried also "order=Order()" for creating object but it's Dosen't Work. Can anyone help me Please. models.py class Order(models.Model): r_name = models.ForeignKey(Restaurant, on_delete=models.CASCADE) f_name = models.ForeignKey(Food, on_delete=models.CASCADE) price = models.IntegerField(default=0) qauntity = models.IntegerField(default=0) total = models.IntegerField(default=0) def __str__(self): return str(self.r_name) views.py def order(request, id): f_detail = Food.objects.get(id=id) if request.method == 'POST': r_name = request.POST['r_name'] f_name = request.POST['f_name'] price = request.POST['price'] qauntity = request.POST['qauntity'] total = int(price) * int(qauntity) addOrder = Order(r_name=r_name, f_name=f_name, price=price, qauntity=qauntity, total=total,) addOrder.save() messages.success(request, 'Your Order is recorded!') return redirect('order') else: context = { 'f_detail' : f_detail, } return render(request, 'pages/order.html',context) return render(request,'pages/order.html') -
when i want post a tweet on my tweet page, it returns undefined instead of the actuall tweet content
i'm following a Create a (Twitter-like App with Python Django JavaScript and React)toturial. yesterday when i save the code and close the VS code the home page was like this enter image description here and today when i run the code i realize that all of my tweets were changed and now it shows me this enter image description here and the code thath handle tweets in templetes: enter c{% extends 'tweets\base.html' %} {% block head_title %} what a nice concept! {% endblock head_title %} {% block content %} <div class='row text-center'> <div class='col'> <h1>Welcom to Tweet</h1> </div> </div> <div class='row mb-3'> <div class='col-md-4 mx-auto col-10'> <form class='form' id='tweet-create-form' method='POST' action='/create-tweet'> {% csrf_token %} <input type='hidden' value='/' name='next' /> <textarea class='form-cntrol' name='content' placeholder="Your tweet..." ></textarea> <button type='submit' class='btn btn-primary'>Tweet</button>> </form> </div> </div> <div class='row' id='tweets'> Loading... </div> <script> function handleTweetCreateFormDidSubmit(event){ event.preventDefault() const myForm = event.target const myFormData = new FormData(myForm) const url = myForm.getAttribute("action") const method = myForm.getAttribute("method") const xhr = new XMLHttpRequest() const responseType = "json" xhr.responseType = responseType xhr.open(method, url) xhr.setRequestHeader("HTTP_X_REQUESTED_WITH", "XMLHttpRequest") xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest") xhr.onload = function() { if (xhr.status === 201) { const newTweetJson = xhr.response console.log(newTweetJson.likes) const newTweetElement = formatTweetElement(newTweetJson) console.log(newTweetElement) tweetsContainerElement.prepend(newTweetElement) } } xhr.send(myFormData) } … -
How to get my image gallery into my product.html in Django with Class based view DetailView
I am using model Product and Images. my goal is to display in my singe item page a gallery of item related pictures coming from model "Images" How can i change the following code to filter by item slug and only show gallery specific to the slug. class ProductDetailView(DetailView): model = Item template_name = 'product.html' context_object_name = 'item' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['image_gallery'] = Images.objects.all() return context -
File in django admin ( forms.py ) is not editing after edit
I accidentally edit the django's Lib/site-packages/django/contrib/auth/forms.py. The problem Then it showed me error then i noticed error and i fixed it after edit, It is still showing that error in the same line , same error syntax ( I have edited it ). When i delete every single word from that file ( forms.py ) , it still shows that error at the same line. What have i tried 1). I have tried --python manage.py makemigrations-- , --python manage.py migrate--. 2). I have also restarted the server. Help me in this. I will really appreciate your Help. Thank you in advance !! -
Element function fails to execute using external js
I just started learning JS and I keep failing to make a function successfully run via external javascript. I have no idea what is wrong. The thing is that it works when using inline javascript, but not external one. Here's the following code: {% load static %} <!DOCTYPE html> <html> <head> <link rel="stylesheet" href="{% static 'css/main.css' %}"> <title id='title'> Home </title> </head> <body> <input type="button" id="btn" value="testas" onclick="myFunction()" /> <address> Written by <a href="mailto:webmaster@example.com">Jon Doe</a> </address> <script src="{% static 'javascript/js.js' %}"></script> </body> </html> JS: function ChangeTitle() { document.getElementById("title").innerHTML = 'Homepage'; } I want to change the title of "Home" to "Homepage" but it doesn't work on external JS. -
How to send manytomany field to Django rest framework using HTTP request in flutter
I have a back end system that needs to device a list of ids to fit a manytomany field made by django. Here are my files : model class field(models.Model): # Fields name = models.CharField(max_length=30) created = models.DateTimeField(auto_now_add=True, editable=False) last_updated = models.DateTimeField(auto_now=True, editable=False) class Lawyer(models.Model): # Relationships fields = models.ManyToManyField("mohamena_app.field") # << -- this is the targeted field city = models.ForeignKey("mohamena_app.City", on_delete=models.PROTECT) # Fields last_updated = models.DateTimeField(auto_now=True, editable=False) bio = models.CharField(max_length=4000) mobile = models.CharField(max_length=14, unique=True) lawyer_id = models.ImageField(upload_to="upload/images/") full_name = models.CharField(max_length=30) is_active = models.BooleanField(default=False) image = models.ImageField(upload_to="upload/images/") created = models.DateTimeField(auto_now_add=True, editable=False) is_phone_active = models.BooleanField(default=False) activation_code = models.PositiveIntegerField(default='0000') Serializer class LawyerSerializer(serializers.ModelSerializer): class Meta: model = models.Lawyer fields = [ "last_updated", "bio", "lawyer_id", "full_name", "fields", "city", "is_active", "image", "mobile", "created", ] And here is how i tried to send the request in my flutter app : Future lawyerRegister(LawyerRegisterModel lawyerRegisterModel) async { Client client = Client(); String theUrl = '${baseURL}Lawyer/'; var uri = Uri.parse(theUrl); List fieldsList = []; for (FieldModel item in lawyerRegisterModel.fields){ fieldsList.add(item.id); // Creates a list of IDS } Map<String, String> headers = { 'Authorization': 'Token $theToken', }; var theRequest = MultipartRequest('POST', uri); theRequest.headers.addAll(headers); theRequest.fields['fields'] = '$fieldsList'; // Here is the error causing line theRequest.fields['city'] = '${lawyerRegisterModel.cityID}'; theRequest.fields['bio'] = '${lawyerRegisterModel.bio}'; theRequest.fields['full_name'] … -
Need suggestions to upload a huge amount of dataset
I'm looking for a solution to upload a huge excel data in Postgresql with a django rest api, the size of file is around 700mb while the number of rows are in millions. The options i'm looking for are: My question is how should i manage such a huge upload and how possibly show the status of uploaded data? Should i upload file in backend the parse and upload in tables? Should i parse data in frontend and upload on backend? Answer any suggestions you, what's the best practice that is used in real world apps?