Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Template - List not rendering properly
I have the following list which is sent to django template using render function: ["9.8 m/s", "9.9 m/s", "1.0 m/s"]. When the list is printed in javascript function, it shows as: ["9.8 m/s", "9.9 m/s", "1.0 m/s"] I have used the following to print the list: console.log("{{ options }}"); in javascript function. I have tried iterating over as {% for option in options %} console.log("{{ option }}"); {% endfor %} The above code displays single characters as opposed to printing list elements. Also tried JSON.parse and JSON.stringify functions in javascript. -
Django settings: sharing ORM with a standalone module
Introduction: I am learning Django as I develop my first project using PyCharm with Python 3.8 and Postgresql. I have a problem with the settings. Environment description: My aim is to have a Django project for a web site connected to a database (let's call it "web_db"), which is fed at regular intervals with data from an external source (another database, let's call it "source_db"). For this ETL process from one database to the other one, I am developing a Python module called "source2web". I read the content of source_db using psycopg2. I am developing everything inside one PyCharm project. Now, since I will be using Django ORM to access the content of web_db from the Django application server, I concluded I might as well use Django ORM in source2web to load my content into web_db. This means I am trying to share some code between the Django project and source2web: the ORM models of Django. source2web is simply launched as a python module ( python source2web.py). Inside my PyCharm project, I have a src folder inside which are all my python modules, with a tree like this (folders are noted with parenthesis) : (src) |--(project_name) |--(module1) | |--source2web.py | … -
'ViewSet' object has no attribute '_meta'
Please i need some help , i am working on a django project .. and i implemented a viewset , serializer and model class ... while i executed the python manage.py runserver 0.0.0.0:9000 command , and when i tryed to test my api i got this error : AttributeError at /api/v1/csr/ 'CsrViewSet' object has no attribute '_meta' Request Method: POST Request URL: http://192.168.56.108:18000/api/v1/csr/ Django Version: 3.0.4 Python Executable: /usr/local/bin/python Python Version: 3.6.10 Python Path: ['/code', '/usr/local/lib/python36.zip', '/usr/local/lib/python3.6', '/usr/local/lib/python3.6/lib-dynload', '/usr/local/lib/python3.6/site-packages'] Server time: Tue, 19 May 2020 17:11:42 +0000 Installed Applications: ['django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'drf_yasg', 'multiselectfield', 'BerryPki.api'] Installed Middleware: ['BerryPki.middlewares.request.MultipleProxyMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'BerryPki.auth.user.CustomHeaderMiddleware', 'corsheaders.middleware.CorsMiddleware'] Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/usr/local/lib/python3.6/site-packages/rest_framework/viewsets.py", line 114, in view return self.dispatch(request, *args, **kwargs) File "/usr/local/lib/python3.6/site-packages/rest_framework/views.py", line 505, in dispatch response = self.handle_exception(exc) File "/usr/local/lib/python3.6/site-packages/rest_framework/views.py", line 465, in handle_exception self.raise_uncaught_exception(exc) File "/usr/local/lib/python3.6/site-packages/rest_framework/views.py", line 476, in raise_uncaught_exception raise exc File "/usr/local/lib/python3.6/site-packages/rest_framework/views.py", line 502, in dispatch response = handler(request, *args, **kwargs) File "/usr/local/lib/python3.6/site-packages/rest_framework/mixins.py", line … -
Add profile picture to UserPostListView in Django
Im building a blog using Django, im very very new using this tool and i've been trying to figure out how to include the user's profile picture in the users posts view. Basicaly in the users posts view, i made a filter ---> www.site.com/user/"username", so you can see all the user posts by date posted. All is working, but im not getting the user profile picture. I really dont know if this is a problem of the queary_set or if im missing something. views.py from django.shortcuts import render, get_object_or_404 from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin from django.contrib.auth.models import User from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView from .models import Post class UserPostListView(ListView): model = Post template_name = 'blog/user_posts.html' context_object_name='posts' paginate_by = 15 def get_queryset(self): user = get_object_or_404(User, username=self.kwargs.get('username')) return Post.objects.filter(author=user).order_by('-date_posted') user_posts.html Im getting the username but not the user profile. <div class="col-auto"><img class="img-profile-st" src="{{ post.author.profile.image.url }}"></div> <h1 class="mb-3" style="text-align: center;">Posted by {{ view.kwargs.username }} ({{ page_obj.paginator.count }})</h1> models.py from django.db import models from django.contrib.auth.models import User from PIL import Image class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') -
Updating my GitHub repository from using 'git push' in MAC terminal doesnt work
anyone ever experienced dealing with this type of issue? When I finished updating my python code, I did the 'git push' to update my repository on GitHub. I checked my repository manually on GitHub to see if updated. However it didnt update. That's why I wasnt able to deploy code correctly for my live server after testing my staging-server - I still received two '.has-error' statements: (I am doing TDD book - chapter 17: https://www.obeythetestinggoat.com/book/chapter_deploying_validation.html) Your help/feedback would be so much appreciated! -
calculating area in geodjango
I'm new with django and i wanted to get the area of a polygon but when I use PolygonField to get a polygon the area command doesn't work. class Polygons(models.Model): name = models.CharField(max_length=40) objects = models.Manager() area_target = models.PolygonField(srid=4326,geography=True,null=True,blank=True) Area = area(geometry=area_target) I think the type of the area_target is the problem. It should be polygon but it isn't and i don't know how to change it. can you help me please? -
Server Error (500) not logging to nginx error.log with Django
BACKGROUND I'm using Django 2.2 and nginx as a webserver with gunicorn. I recently changed the name of my site. Every link is now working again: both http, and https redirecting properly from the old domain to the new one. But one view is giving me a 500 error after a redirect at the django app level. In this view, I always get a 500 error instead of the redirect it should give. Everything runs correctly except the redirect. And note that all of this stuff works fine on the local dev server without errors. def create(request, slug): .... if request.method == 'POST': if form.is_valid(): new_obj = form.save(commit=False) .... new_obj.save() return redirect(reverse('my_app:detail', args=[new_obj.category, new_obj.id, new_obj.created.year, new_obj.created.month, new_obj.created.day, new_obj.slug])) This creates an object correctly, it shows up in the database, and it shows on it's own detail page too. But the immediate response is always the 500 error instead of redirecting to the correct page. And to get to the new page, I have to open the list page and click on the new obj to go to it's detail page. And here is the relevant part of the view it goes to: def detail(request, category_slug, obj_id, year, month, day, slug): … -
Create an instance of a serializer from a seperate one
I have a Customer Serializer which takes in details of a customer including the email. I am hoping to create a user based on the email of the customer during customer registration. def post(self, request, *args, **kwargs): new_customer = CustomerSerializer(data=request.data) if new_customer.is_valid(raise_exception=True): customer_email = request.data.get('email') ***new_user = UserCreateSerializer.create(email=customer_email, is_active=False, user_type="COSTOMER")*** user_id = urlsafe_base64_encode(force_bytes(new_user.pk)) new_customer.user = new_user new_customer_saved = new_customer.save() new_user_saved = new_user.save() token = user_tokenizer.make_token(new_user) url = 'http://127.0.0.1:8000' + reverse('auth_cust', kwargs={'user_id': user_id, 'token': token}) send_mail( 'Django Survey Email Confirmation', url, EMAIL_HOST_USER, [new_customer.email], fail_silently=False, ) return Response({ 'Success': "'{}' has been successfully registered".format(new_customer_saved.get_full_name) }) this is my customer serializer class CustomerSerializer(serializers.ModelSerializer): class Meta: model = Customers fields = '__all__' User serializer class UserCreateSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['email',] but I am geting an error with the UserCreateSerializer.create method called in the view. -
Django "Python manage.py runserver" command gives an error and then freezes the command line
I'm learning django and i'm trying to run "Python manage.py runserver" it gives me a error that is too long but i took a screenshot I"m using python 3.8.2. -
No module named in Django error migration
I am using the command on MacOS to migrate database (myenv) (base) Elenas-MacBook-Air:myenv elenaorlova$ python3 manage.py migrate But as a result getting an error 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 "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked ModuleNotFoundError: No module named 'changers.app' Could you please let me know if you have an idea why is that happening? Thank you! -
How to add comments on django
I am trying to add a comment system to my project, all the code looks fine but I am getting this error "ValueError at / The QuerySet value for an exact lookup must be limited to one result using slicing". I dont know what is wrong but the error might be on the views.py file. views.py def imagelist(request): images = Post.objects.all() comments = Comment.objects.filter(post=images) if request.method == 'POST': comment_form = CommentForm(request.POST or None) if comment_form.is_valid(): contentt = request.POST.get('content') comment = Comment.objects.create(post=images, user=request.user, content=content) comment.save() return HttpResponseRedirect(post.get_absolute_url()) else: comment_form = CommentForm() context2 = { "images": images, "comments": comments, "comment_form": comment_form, } return render(request, 'imagelist.html', context2) models.py class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) content = models.TextField(max_length=160) timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return '{}-{}'.format(self.post.title.str(self.user.username)) forms.py class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ('content',) -
django tables2 create extra column with hyperlink
I am using django-table2 and wanted to get an extra column Edit for each row. Here I am getting only a dash(-) instead of any link. Could you please help. tables.py class computertable(tables.Table): Edit = tables.LinkColumn("computer_edit", args=[A("int:id")]) class Meta: model = Computer fields = ['computer_name','Edit'] urls.py urlpatterns = [ path('', views.computer_list, name='djform-home'), path('computer_edit/<int:id>/', views.computer_edit, name='computer_edit'),] -
Django - Load images from project folder and manage them
I've extracted multiple images from the document that user uploads and saved them in the project folder using ... for i in range(len(allImages)): allimagesdata.save("static/img%s.png" %(i+1)) ... image = [""]*len(allImages) for i in range(len(allImages)): image[i] = "img%s.png" %(i+1) ... return render(request, "fileinfo.html", {'image':image}) in views.py, images being named like img6.png etc. I want these images to load on my HTML page, but these images are not loaded. I've to use the command python manage.py collectstatic to load them. fileinfo.html {% load static %} {% static "" as baseURL %} ... {% for i in image%} <img src="{{baseURL}}{{i}}"><br> {% endfor %} ... Currently, I'm facing multiple problems : I want these images to load automatically. These images should be deleted once they are of no use. When multiple users access this, it would create clashes among images and files. (There is no login required, anyone can access) How can I solve all of these problems? -
Preview form data before submission
Are there any tools for previewing a Django form as the user provides input? I've checked around S/O and don't see anything other than using the built-in preview function after submission. That seems antiquated. I know you can do it using Jquery for simple text fields (like this: http://volter9.github.io/Form-Preview/) but I'd like to do it with a wysiwyg editor like TinyMCE. Any tips would be appreciated -
Why is my image not being loaded into the background of my Jumbotron?
So I'm not sure what I'm doing wrong here. I've tried a couple different ways as shown below to get my image to be the background of my Jumbotron but none of them are working. I know it's not an issue with loading static or anything like that because doing img src= straight into the Jumbotron section works but it it's not actually the background of Jumbotron. So what am I doing wrong here? home.html/styles .JumboHeaderImg{ background-image: url("/Users/papichulo/Documents/DatingAppCustom/dating_app/static/images/jumbo.jpg"); } .JumboHeaderImg{ background-image: "{% static 'images/jumbo.jpg' %}"; <div class="jumbotron JumboHeaderImg"> style.css .jumbotron{ background-image: url('{% static "images/jumbo.jpg"%}'); } -
Django and BeautifulSoup - Run views.py on each pageload?
I am completely new to Django, so sorry for the maybe very basic question, but I couldn't come up with an asnwer yet. I've installed Django on Ubuntu and Virtualenv. I also installed BeautifulSoup and Requests. So I started an app called scrape and imported Requests and BeautifulSoup in my views.py from django.shortcuts import render import requests from bs4 import BeautifulSoup r = requests.get("https://www.krone.at") soup = BeautifulSoup(r.content, 'html.parser') headings = soup.find_all('div', {"class":"item"}) headings = headings[0: 10] news = [] for items in headings: news.append(items.text.strip()) def scrape_view(request): return render(request, 'scrape.html', {'news': news}) my template (scrape.html) looks like this: {% extends 'base.html' %} {% block content %} <h2>Krone (Newsticker)</h2> {% for item in news %} <span class="krone headline">{{ forloop.counter }} - {{ item }}</span><br /> {% endfor %} {% endblock content %} So basically, this works just fine. I scrape with Requests and BeautifulSoup the first 10 headlines of an Austrian newspaper. Then I pass it to the template and run a for loop which gives me all the headlines. BUT, when I refresh the page, I'll always get the same headlines, even if they have been changed already on the website I am scraping from. When I then kill the Server … -
How to name the fields of a custom form in django?
I am creating a custom from in django. class MeasurementsForm(forms.ModelForm): d_value=forms.IntegerField(help_text="insert the diabetes") class Meta: model=Measurements fields=('d_value',) In the fields=('d_value',), do I need match the name of the fields with the name of fields of the model? Whenever I ran this I got form name as D value instead of d_value. What is the problem? What is the function of this line d_value=forms.IntegerField(help_text="insert the diabetes"). Is it mandatory to use it? -
Update function deletes one image from formset when updating texts in Django
I have this post with a form for title and tags and a modelformset for images with postimages model which has a foreign key relation to Post Model. I am able to update images and edit posts, but the problem is whenever I try to edit the title, one of the images gets deleted and it creates a duplicate of another image in the formset. Please have a look the views. I am not able to figure it out. views def update_post(request, slug): context = {} post = get_object_or_404(Post, slug=slug) ImageFormSet = modelformset_factory(PostImage, fields=('image',), extra=5, max_num=5) tags = Tag.objects.filter(post=post) if post.user != request.user: return redirect('posts:myhome') if request.POST: form = UpdatePostForm(request.POST or None, instance=post) formset = ImageFormSet(request.POST or None, request.FILES or None) if form.is_valid() and formset.is_valid(): obj = form.save(commit=False) obj.save() post = obj data = PostImage.objects.filter(post=post) for index, f in enumerate(formset): if f.cleaned_data: if f.cleaned_data['id'] is None: photo = PostImage(post=post, image=f.cleaned_data.get('image')) photo.save() else: photo = PostImage(post=post, image=f.cleaned_data.get('image')) d = PostImage.objects.get(id=data[index].id) d.image = photo.image d.save() context['success_message'] = "Updated" return redirect('posts:myhome') form = UpdatePostForm( initial = { 'title': post.title, 'tags':post.tags, 'visibility':post.visibility, } ) formset = ImageFormSet(queryset=PostImage.objects.filter(post=post)) context['form'] = form context['formset'] = formset return render(request, 'posts/update_post.html', context) Thanks in advance! -
Django register view of many to many connection table in Admin
I have a Django model, and two model classes with many to many relationships between them. class A(models.Model): a = models.ManyToManyField(B, related_name='a') class B(models.Model): id = models.CharField(primary_key=True, unique=True, max_length=10) Inside the database, I know, ORM creates the connection table between database A and B: A_B I would like to create an Admin class out of this connection table. @admin.register(A_B) class ConnectionAdmin(admin.ModelAdmin): .... Is there a way to do it? P.S. I know that I could do the Inline field in the B admin or "normal" field in A admin class, but this is not what I am looking for. -
How do I fix this error? I have no idea what is causing it
[pid 30498] AH01574: module wsgi_module is already loaded, skipping httpd (no pid file) not running Waiting for HTTP to exit -
Running huey in production with Django
I am working on a Django project which has been deployed on a Windows server using Apache (WAMP). I have integrated Huey with the Django application to run some asynchronous tasks. I am running the consumer using the python manage.py run_huey command. Is there any way to run this command as a service in the background? -
Django reset user-password
I'm trying of using default functionality of resetting password with custom form but its not working.I even add path in main app but still getting error page not found after entering email for sending link. -
docker-compose issue - Celery container not able to access DB container
Regards I have been working on a Django Application, that runs on Redis, PostgreSQL, Celery, RabbitMQ. I have written a docker-compose to run all of these services in their separate containers. Here's my docker-compose.yml version: "3.2" services: app: build: context: . image: &app app ports: - "8000:8000" env_file: &envfile - env.env volumes: - ./app:/app environment: - DB_HOST=db command: > sh -c "python manage.py wait_for_db && python manage.py migrate && python manage.py runserver 0.0.0.0:8000" depends_on: - db - redis - broker redis: restart: always image: redis:latest ports: - "6379:6379" db: image: postgres:12-alpine environment: - "POSTGRES_HOST_AUTH_METHOD=trust" worker: build: . image: *app restart: always env_file: *envfile command: ["celery", "worker", "--app=worker.worker.app", "--concurrency=1", "--hostname=worker@%h", "--loglevel=INFO"] volumes: - ./app:/app depends_on: - broker - redis - db broker: image: rabbitmq:3 env_file: *envfile ports: - 5672:5672 flower: image: zoomeranalytics/flower:0.9.1-4.0.2 restart: "no" env_file: *envfile ports: - "5555:5555" depends_on: - broker My application is working just fine, and the containers seems to be working, the problem arises when I push an Async job to the worker container. The worker container picks up the job, and start processing, I am trying to access the DB in the worker, but it's giving me the following error - Task [640127f3-7769-4757-8c33-8de9052ca92c] raised unexpected: OperationalError('could … -
Interactive Histogram, where the user can plot histogram via drag and drop
Just wanted to know if there is a possibility that a User Interface can be created where a user is allowed to draw histograms himself, provided a colour pallet also? By himself I mean,he/she can drag and drop? Then as he/she draws a bar, the x and y values on the plot can be stored? If yes, please suggest something. I have used some random tags that came to mind. Hopefully, it reaches the right audience. Thanks! -
Django allauth Facebook login error "Invalid App ID The provided app ID does not look like a valid app ID"
Background I have built an app with Django. Its using AllAuth with facebook to allow users to log in using their facebook profile. I have updated my allauth settings in my localhost/admin 'Social Applications' to reflect the information that is displayed within my app on the 'Facebook for developers' site (see below). I have made my allauth 'Client id' = to the facebook developer 'App ID' and my allauth 'Secret key' = facebook developer 'App Secret'. Django Admin: Facebook for developers: The problem When I click on sign in using facebook, the page redirects to facebook and displays the error "Invalid App ID The provided app ID does not look like a valid app ID." I have triple checked that all the information is correct from the Client ID and Secret Key. Could somebody point me in the right direction as to what might be going wrong here?