Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I cannot supmit the comments for multi posts in Django
I have a feed and in this feed have posts and each post have comments, Now I can submit a comment for just the first post but when I try to come to the second or third post and submit comment this error rais ValueError: The view videos.views.add_comment_post didn't return an HttpResponse object. It returned None instead. I thought that the problem with the posts id conflict with each other so I passed all the comment fields to the template and the same error still happen. "this problem happen with any post except the first one" My comments view comment_form = PostCommentForm(request.POST ) if comment_form.is_valid(): user_comment = comment_form.save(commit=False) user_comment.author = request.user user_comment.save() result = comment_form.cleaned_data.get('content') user = request.user.username return JsonResponse({'result': result, 'user': user}) My Post model class Post(models.Model): author = models.ForeignKey(Account, on_delete=models.CASCADE) article = models.TextField(null=True, blank=True) photo_article = models.ImageField(max_length=255, upload_to=get_poster_filepath) created_date = models.DateTimeField(auto_now_add=True) My comments model class PostCommentIDE(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='ide_com') author = models.ForeignKey(Account, on_delete=models.CASCADE) content = models.TextField() created_date = models.DateTimeField(auto_now_add=True) My comments Form class PostCommentForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) class Meta: model = PostCommentIDF fields = {'post', 'content'} widgets = { 'content': forms.Textarea(attrs={'class': 'rounded-0 form-control', 'rows': '1', 'placeholder': 'Comment', 'required': 'True', }) } def save(self, … -
PLACES API Error with API key integrated in Django
I am trying to use Places API , but the error rate for Places API in concole ois 100%, The error is : This page doesnt load Maps, Javascript console error is Billing is not enabled , but i have enabled the billing and also enabled all the specified APIS , still faceing the same issue I am using the API key in my Django Projects For search results -
Docker-compose, django and pipfile.lock - docker can't install packages from pipfile.lock
After some searches in the internet, I come to ask for your help. I would like to create a server with django in the backend and react in the frontend. Although I do not have any problems with the frontend, I cannot properly initialise the backend with docker-compose. Here is my docker-compose file : version: "3.9" services: # Frontend and backend django_server: container_name: has_server_backend build: ./server depends_on: - mongo_db ports: - "8000:8000" volumes: - ./server:/has_server frontend: container_name: has_server_frontend build: ./frontend command: npm start ports: - "3000:3000" # Services associated mqtt: container_name: mqtt_broker image: eclipse-mosquitto volumes: - ./services/mosquitto/config:/mosquitto/config - ./services/mosquitto/data:/mosquitto/data - ./services/mosquitto/logs:/mosquitto/logs mongo_db: container_name: has_server_mongodb image: mongo restart: always volumes: - ./services/mongo-db/db:/data/db environment: MONGO_INITDB_ROOT_USERNAME: root MONGO_INITDB_ROOT_PASSWORD: mongoadmin MONGO_INITDB_DATABASE: has_server ports: - 27017:27017 mongo-express: image: mongo-express restart: always ports: - 8081:8081 environment: ME_CONFIG_MONGODB_ADMIN_USERNAME: root ME_CONFIG_MONGODB_ADMIN_USERNAME: my_password Here is the docker file for the backend : FROM python:3.8 ENV PYTHONUNBUFFERED 1 COPY . has_server/ WORKDIR /has_server RUN ls -al RUN pip install pipenv RUN pipenv install COPY . ./ EXPOSE 8000 CMD [ "python", "manage.py", "runserver", "0.0.0.0:8000"] Here is my Pipfile.lock: { "_meta": { "hash": { "sha256": "4c26f7511ec3af2303f9a21d47b0a6dc919fcf2a0a32862c85f2e4a23fc694ea" }, "pipfile-spec": 6, "requires": { "python_version": "3.8" }, "sources": [ { "name": "pypi", "url": "https://pypi.python.org/simple", … -
Django make dynamic Q object by list elements
I want to make dynamic q objects by given list. tag_list = ["t1"] # tag list element length is 1 result_list = [] q_objs_list = [] # In this case, I want to make list like below.. # some def needed to do below q_objs = Q() q_objs &= Q(tag="1") result_list.append(q_objs) q_objs_list.append(1) #because positive q_objs is only when tag "1" 1case. q_objs = Q() q_objs &= ~Q(tag="1") result_list.append(q_objs) q_objs_list.append(0) #because positive q_objs is nothing #>>> len(result_list) >>> 2 # In this case, list length is 2 and I want to get 4 results list. tag_list = ["1", "2"] result_list = [] q_objs_list = [] # some def needed to do below q_objs = Q() q_objs &= Q(tag="1") q_objs &= Q(tag="2") result_list.append(q_objs) q_objs_list.append(2) #because positive q_objs is only when tag "1", "2" 2cases. q_objs = Q() q_objs &= Q(tag="1") q_objs &= ~Q(tag="2") result_list.append(q_objs) q_objs_list.append(1) #1 positive case q_objs = Q() q_objs &= ~Q(tag="1") q_objs &= Q(tag="2") result_list.append(q_objs) q_objs_list.append(1) #1 positive case q_objs = Q() q_objs &= ~Q(tag="1") q_objs &= ~Q(tag="2") result_list.append(q_objs) q_objs_list.append(0) # no positive case #>>> len(result_list) >>> 2 * 2 In my case, I don't know what tag_list will be given to me. It could be ["t1", "t2", "t3", … -
Django Rest framework, retrieve data from database with no related model
I am trying to create a REST API for a database that already exists. The problem is that the data on the database are refreshed from a bash script every hour, so there is no related model for these data. So I am working on creating a GET request on Django so to be able to retrieve the data. Currently I am using an APIView like this: class RetrieveData(APIView): def get(self, request): conn = psycopg2.connect(host=..., database=..., user=..., password=..., port=...) cur = conn.cursor() cur.execute(f'Select * from ....') fetched_data = cur.fetchone() cur.close() res_list = [x for x in fetched_data] json_res_data = {"id": res_list[0], "date": res_list[1], "data": res_list[2]} conn.close() The problem that I have is that connecting on the database every time so to retrieve the data and then return the response is quite slow ~ 2sec/request. Also I am afraid in case of many requests made at the same time, how is that going to work. So the question that I have is if there is any suggestions or any solutions that you propose. -
I am getting a 'permission denied' error when I try to upload files directly to my Django app on Elastic beanstalk with a newly attached volume
I recently deployed a django app to AWS elastic beanstalk. I have used boto3 to enable storing my videos to the s3 bucket. But i need to convert the video files on the local storage before storing it on S3. I use moviepy and ffmpeg to convert the videos. But when I try to upload the files, I get an error "[errno 32] broken pipe moviepy error: ffmpeg encountered the following error while writing file /home/ec2-user/mount_point/u3files/temp_files/21editedtemp_mpy_wvf_snd.mp3: /home/ec2-user/mount_point/u3files/temp_files/21editedtemp_mpy_wvf_snd.mp3: permission denied". I have already chmod 777 on the root folder of the volume and 'u3files' folder inside the local storage. Is there anything I am missing? How do I solve this? I am new to AWS beanstalk and any help would be appreciated. Thanks. -
how to prefetch directly unrelated fields in graphene django
I started using graphene and there are some thing I have not yet understood well for instance, when using nodes the I have this query { orders { edges { node { id fromUser { id username userprofile{ image id } } toUser { id username userprofile{ image id } } } } } } it is very nice because it allows me to fetch profile and get image for a given profile that is related to a user even though user is foreign key in profile, however it is expensive in terms of queries that has to be done in order to get profile for every user my models looks like this class Order(models.Model): from_user = models.ForeignKey(User, on_delete=models.PROTECT, related_name="from_user") to_user = models.ForeignKey(User, on_delete=models.PROTECT, related_name="to_user") .... class UserProfile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) image = models.ImageField(null=True) and my query as of now Order.objects.select_related('from_user','to_user').filter( Q(from_user=user) | Q(to_user=user) ).order_by("-id") return orders will appreciate if anyone could help me know how I can prefetch profile for both from_user and to_user in that case coz it really is expensive fetching the profile -
Check file extension in Django FileField
I need to run a different code depending on the extension of the file. This is a simplified version of the model: class SuplierList(models.Model): file = models.FileField(upload_to='fornecedores/') This is the part of the view that I have the problem: table = request.GET.get("table") ft = FornecedorTabela.objects.filter(id=table)[0] file = ft.file if re.match('.pdf$', ft.file.name): I don't know how I should write this last condition above. With this version above, I get the error: The 'python' engine cannot iterate through this file buffer. How show I write this condition? -
Bootstrap only works for the home page of my website, but no other html page. Why?
I am a newbie and trying to create a ecommerce website with Django. I am using Bootstrap 5. Bootstrap is only working on the home page of my website, but not on the other pages... Why is that ? main.html <!DOCTYPE html> {% load static %} <html lang="fr"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link href="static/css/main.css" rel="stylesheet"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css"> <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script> <style> /*PAYPAL BUTTONS STYLE*/ /* Media query for mobile viewport */ @media screen and (max-width: 400px) { #paypal-button-container { width: 100%; } } /* Media query for desktop viewport */ @media screen and (min-width: 400px) { #paypal-button-container { width: 250px; } } </style> <title> {% block title %} {% endblock title %} </title> </head> <body> <header> <nav class="navbar navbar-expand-lg navbar-light bg-light"> <div class="container-fluid"> <a class="navbar-brand" href="/">MONOÏ</a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarNav"> <ul class="navbar-nav"> <li class="nav-item"> <a class="nav-link active" aria-current="page" href="/">Home</a> </li> <li class="nav-item"> <a class="nav-link active" aria-current="page" href="/">La marque</a> </li> <li class="nav-item"> <a class="nav-link active" aria-current="page" href="{% url 'store:categories' %}">Catégories</a> </li> <li class="nav-item"> <a class="nav-link active" aria-current="page" href="/all_products/">Tous les produits</a> </li> <li class="nav-item"> <a class="nav-link active" aria-current="page" href="{% url 'contact:contact-form' %}">Contact</a> </li> <li class="nav-item"> … -
How to Implement this custom model manager in django?
am new to Django and I getting some difficulties and I'm confused about the correct way to use Django custom model managers: charities/models.py: from django.db import models from accounts.models import User class Benefactor(models.Model): Level = ((0, 'Beginner'), (1, 'Intermediate'), (2, 'Expert')) user = models.OneToOneField(User, on_delete=models.CASCADE) experience = models.SmallIntegerField(choices=Level, default=0) free_time_per_week = models.PositiveSmallIntegerField(default=0) class Charity(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) name = models.CharField(max_length=50) reg_number = models.CharField(max_length=10) class TaskManager(models.Manager): def related_tasks_to_charity(self, user): my_charity = str(Charity.objects.get(user = user)) return self.filter(charity = my_charity) def related_tasks_to_benefactor(self, user): my_bonefactor = str(Benefactor.objects.get(user = user)) return self.filter(assigned_benefactor = my_bonefactor) def all_related_tasks_to_user(self, user): return self.filter(state = "P") class Task(models.Model): gen_choice = (('F', 'Female'), ('M', 'Male')) sta_choice = (('P', 'Pending'), ('W', 'Waiting'), ('A', 'Assigned'), ('D', 'Done ')) # id = models.AutoField() !REMOVE id FIELDS assigned_benefactor = models.ForeignKey(Benefactor, null=True, on_delete=models.SET_NULL) charity = models.ForeignKey(Charity, on_delete=models.CASCADE, related_name='User_Charity') age_limit_from = models.IntegerField(blank=True, null=True) age_limit_to = models.IntegerField(blank=True, null=True) date = models.DateField(blank=True, null=True) description = models.TextField(blank=True, null=True) gender_limit = models.CharField(max_length=50, blank=True, null=True) state = models.CharField(max_length=50, choices=sta_choice, default='Pending') title = models.CharField(max_length=100) objects = TaskManager() my problem is here and these 3 defines: class TaskManager(models.Manager): def related_tasks_to_charity(self, user): my_charity = str(Charity.objects.get(user = user)) return self.filter(charity = my_charity) def related_tasks_to_benefactor(self, user): my_bonefactor = str(Benefactor.objects.get(user = user)) return self.filter(assigned_benefactor = my_bonefactor) def … -
django model for list aws iam users in admin page
hi iam new for django i am creating a application so that i can list IAM users, policies and also create IAM users I know how to transfer a doc from local machine to s3 bucket but i dont know how to list IAM user in the django application And i have a endpoint for a lambda function so that get the list of IAM user from this i want to create a module so that will list the IAM user Please help me with this... python import uuid from django.db import models from django.contrib.auth.models import User from django.contrib.auth import get_user_model class Docstos3(models.Model): uuid = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False, ) created_at = models.DateTimeField(auto_now_add=True) title = models.CharField(max_length=100) docs = models.FileField() i want to create a button in admin page so that i can get IAM user when i click that with the help of my Api endpoint -
Django + React Project Works On Local Server But Does Not Display On pythonanywhere.com . . . Do The React Paths Have To Be Defined In Django?
So my django/react project works find on my local machine but when I deploy it to pythonanywhere.com I get this message below when I try to go to any of the routes ("/", "/factors", "/chart"). I have seen some other posts on how to tell django where to go to if the url corresponds to the frontend React routes (since that is the only place the routes are defined) but I'm unsure what to put in the views. Is the only way to get this to work to load a generic html template with a django view and then call the React routes from there? Why does it work in development without doing this but the same url paths don't display anything on the live site? The /api route correctly displays the django api interface so at least I know some routes are working. Page not found (404) Request Method: GET Request URL: https://elledee.pythonanywhere.com/ Using the URLconf defined in factorsViewer.urls, Django tried these URL patterns, in this order: admin/ api/ The empty path didn’t match any of these. Here is my urls.py project file (I don't have a urls.py in the fv app). """time_factor URL Configuration The `urlpatterns` list routes … -
Why i am getting error "page not found" after after making the url dynamic in django
why i am getting this error.. "page not found" while trying to implement dynamic url in django...please see my code and advice me. it works fine when url is not dynamic.but as soon as the url is made dynamic it shows the error view.... def detail_post(request,my_id): return render(request, 'dynamic/showdetail.html') urlpatterns = [ path('detail/<my_id>/', views.detail_post, name="detail") ] it works absolutely fine before dynmic url is made -
list inside dictionary wont appear when sent to a put request
i have a dictionary that should look like this memberlist = [{"id":50,"firstName":"popo"}] data = {"member": memberlist, "len":1} a put request that looks like url = "http://192.168.100.246:8000/api/group/member/28" updategroup = requests.put(url,data = data) and this is the view of the url class SetMember(APIView): permission_classes=[AllowAny] def getObject(self,id): try: return Group.objects.get(id=id) except Group.DoesNotExist: return Response(status = status.HTTP_404_NOT_FOUND) def get(self,request, id): group = self.getObject(id) serializer = setMemberSerializer(group) return Response(serializer.data) def put(self,request,id, format='json'): group = self.getObject(id=id) serializer = setMemberSerializer(group, data=request.data) if serializer.is_valid(): # serializer.save() return Response(serializer.data) return Response ({'msg':request.data}, status = status.HTTP_400_BAD_REQUEST) well the api doesnt work, so i looked around it to see what was wrong by returning request.data as a response. turns out the data returned from the response looked like this {"msg":{"member":"firstName","len":"1"}} while i was expecting the data to look like this {"msg":[{"id":50,"firstName":"popo"}],"len":"1"}} HOWEVER, when i changed the data sent into something like (i added single quotes to the list and didnt use a variable anymore) data = {"member": '[{"id":50,"firstName":"popo"}]', "len":1} everything works fine! any help or tips appreciated would be nice -
upload all the images in a directory to django admin in name and image field respectively?
i am trying to upload a lot of images to the django database through models.py in django admin but am unable to do so. models.py class Category(models.Model): name = models.CharField(max_length=250, unique=True) slug = models.SlugField(max_length=250, unique=True) # description = models.TextField(blank=True) image = models.ImageField(upload_to='category', blank=True) class Meta: ordering = ('name',) verbose_name = 'category' verbose_name_plural = 'categories' def get_url(self): return reverse('products_by_category', args=[self.slug]) def __str__(self): return self.name path1 = "D:/downloads/mobiles/images/" fil = os.listdir(path1) for f in fil: Category.name.save(os.path.basename(os.path.join(path1, f))) Category.image.save(f, File(open(os.path.join(path1, f)), 'r')) this gives error AttributeError: 'DeferredAttribute' object has no attribute 'save' I can't seem understand why is this happening. Also feel free to suggest any other way of doing this. -
Dynamic site elements not displaying after Django database change
So I recently changed databases on a Django-based website from SQLite to MySQL. I did it via dumping the data from the SQLite into a json file and then migrating it to the new MySQL db. The site is hosted on pythonanywhere and the tranistion there went flawless, however, on the local copy of the project I have(used to test implementing new features and debug), the dynamic elements on the front page wont load. I have a dynamic js table with information for various cryptocurrencies. This is how the head of the table looks on the live site: And this is how it looks on the local copy of my machine, with my own hosted MySQL server: What I've tried: -Collectstatic -Running ContentType.objects.all().delete() in python manage.py shell I also did research on stackoverflow but I could not find a similar issue. I am also new to Django so it might be something obvious I'm missing -
Why does APPEND_SLASH not work in Django 3.2
I am creating this new django project (v3.2). However the APPEND_SLASH does not seem to work. If I dont add / at the end of the url it throws an error. I even tried manully adding APPEND_SLASH = True in settings.py file, but it still did'nt work. (Note : I have 'django.middleware.common.CommonMiddleware', in my settings.py file) So any of you has any idea that why does this not work. (I created a project a month ago on django 3.1.7 and there I did'nt face this problem) -
Celery custom task state is not recognized
I have a Celery task that creates a CSV file and during the process of creation I want to set a custom state to the task so I can display it on the frontend. Here is my task from tasks.py @app.task(bind=True) def make_csv_file(self, schema_id, rows): schema = SchemaModel.objects.get(id=schema_id) salt = str(uuid.uuid4()) print(f"salt is {salt}") try: columns = [ column for column in schema.column_in_schemas.all().order_by("order") ] path = os.path.join(settings.MEDIA_ROOT, f"schema-{schema.id}---{salt}.csv") f = open(path, "w") f.truncate() csv_writer = csv.writer(f) csv_writer.writerow([column.name for column in columns]) # writerow? for x in range(rows): row_to_write = list() for column in columns: row_to_write.append(" ".join(generate_csv_data(column.id).split())) csv_writer.writerow( row_to_write ) # the line bellow is supposed to set a custom state to the task # https://docs.celeryproject.org/en/latest/userguide/tasks.html#custom-states if not self.request.called_directly: self.update_state(state='PROGRESS', meta={'done': x, 'total': rows}) schema.files.create(file=path, status=SchemaModelStatusChoices.READY) print("created") except Exception as exc: print(exc) schema.files.create(file='', status=SchemaModelStatusChoices.FAILED) finally: schema.save() Here comes my views.py def view_schema(request, pk): schema = SchemaModel.objects.get(pk=pk) form = RowsForm(request.POST or None) context = { 'schema': schema, 'form': form, } if request.method == 'POST': rows = int(request.POST.get('rows')) job = make_csv_file.apply_async((schema.id, rows)) request.session['task_id'] = job.id # here I write the task id so that I can get it's state from the view below return redirect('schemas:view_schema', pk=pk) return render(request, 'schemas/view_schema.html', context) @csrf_exempt def poll_state(request): … -
How to serialize an array of objects in Django
I am working with Django and REST Framework and I am trying to create a get function for one of my Views and running into an error. The basic idea is that I am creating a market which can have multiple shops. For each shop there can be many products. So, I am trying to query all those products which exist in one shop. Once I get all those products I want to send it to my serializer which will finally return it as a JSON object. I have been able to make it work for one product but it does not work for an array of products. My Product model looks like this: '''Product model to store the details of all the products''' class Product(models.Model): # Define the fields of the product model name = models.CharField(max_length=100) price = models.IntegerField(default=0) quantity = models.IntegerField(default=0) description = models.CharField(max_length=200, default='', null=True, blank=True) image = models.ImageField(upload_to='uploads/images/products') category = models.ForeignKey(Category, on_delete=models.CASCADE, default=1) # Foriegn key with Category Model store = models.ForeignKey(Store, on_delete=models.CASCADE, default=1) ''' Filter functions for the product model ''' # Create a static method to retrieve all products from the database @staticmethod def get_all_products(): # Return all products return Product.objects.all() # Filter the … -
Django: How to retrieve all attributes from related models for GeoJSON serialization?
I have two Models Site and Cell, every site has multiple Cells. from django.db import models from django.contrib.gis.db.models import PointField class SiteManager(models.Model): def get_by_natural_key(self, name, state_code, location): return self.get(name=name, state_code=state_code, location=location) class Site(models.Model): name = models.CharField(max_length=10) state_code = models.PositiveSmallIntegerField() location = PointField() objects = SiteManager() class Meta: unique_together = [['name', 'state_code', 'location']] def natural_key(self): return (self.name, self.state_code, self.location) class Cell(models.Model): tech = models.CharField(max_length=5) azimuth = models.IntegerField() sector_id = models.CharField(max_length=10) frequency_band = models.CharField(max_length=15) power = models.DecimalField(decimal_places=2, max_digits=4) site = models.ForeignKey(Site, on_delete=models.CASCADE) def natural_key(self): return (self.tech, self.azimuth,) + self.site.natural_key() natural_key.dependencies = ['astmaps.site'] I want to retrieve the complete Cell attributes with the related attributes in the Site model, for me to Serialize the resultant Cell's, into GeoJson data, I can easily Serialize the Site model like: from django.core.serializers import serialize # GeoJSON Serializer sites = Site.objects.all() sitesData = serialize('geojson', sites, geometry_field='location', fields=('name', 'state_code')) which gives me a GeoJson featureCollection object like: { "type":"FeatureCollection", "crs":{ "type":"name", "properties":{ "name":"EPSG:4326" } }, "features":[ { "type":"Feature", "properties": { "name":"02101", "state_code":2 }, "geometry":{ "type":"Point", "coordinates":[ 1.34944, 36.1586 ] } } ] } But when It comes to the Cell model, I can't successfully get the geometry field from the related model always null. Since the Cell model … -
getting the the field value based on the other value you entered in a form django
two models: class Branch(models.Model): name = models.CharField(max_length=50) square = models.CharField(max_length=50) branch_id = models.CharField(max_length=5, blank=True) class Worker(models.Model): w_branch = models.ForeignKey(Branch, on_delete=models.SET_NULL, null=True, blank=True) Form class PayForm(forms.Form): branch = forms.ModelChoiceField(label='branch', queryset=Branch.objects.all()) worker = forms.ModelChoiceField(label='customer', queryset=Worker.objects.filter()) I dont know how to get queryset of workers based on branch choise whithin the form. And im not sure that it is possible...can you help? -
IntegrityError at /post/new/ NOT NULL constraint failed: blog_post.author_id
Iam trying to learn django but this thing is stoppin me from doing that this is my views.py from django.shortcuts import render from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin from django.http import HttpResponse from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView from .models import Post # Create your views here. def home(request): context = { 'posts' : Post.objects.all } return render(request,'blog/home.html',context) class PostListView(ListView): model = Post template_name = 'blog/home.html' context_object_name = 'posts' ordering = ['-date_posted'] # <app>/<model><viewtype>.html class PostDetailView(DetailView): model = Post class PostCreateView(LoginRequiredMixin,CreateView): model = Post fields = ['title','content'] class PostUpdateView(LoginRequiredMixin,UpdateView): model = Post fields = ['title','content'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) def test_func(self): post = self.get_object() if self.request.user == post.author: return True return False class PostDeleteView(LoginRequiredMixin, UserPassesTestMixin,CreateView): #LoginRequiredMixin, UserPassesTestMixin,DeleteView #LoginRequiredMixin, AuthorMixin, ListView model = Post success_url = '/' def test_func(self): post = self.get_object() if self.request.user == post.author: return True else: return False def about(request): return render(request,'blog/about.html',{'title':'About'}) This is my models.py: from django.db import models from django.contrib.auth.models import User from PIL import Image # Create your models here. class Profile(models.Model): user = models.OneToOneField(User, on_delete= models.CASCADE) image = models.ImageField(default='default.jpg',upload_to="profile_pics") def __str__(self): return f'{self.user.username} Profile' def save(self): super().save() img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size … -
Manually caching HTML pages in Django CMS
I'm trying o build an addon for Django CMS that would save a static copy of a site on disk. I have set up the addon and I have a button on the toolbar that triggers a view that goes through all the pages, renders them and saves them. The general setup seems to work fine, but when I check the static HTML files created, they are missing the content of the plugins in each page. My approach was to reuse the Django CMS details view, which is the one used to render the pages as a response to the browser's HTTP requests. I suspect the problem might have something to do with the request object passed to it, since the one I have available in my view is actually the admin page request, not the one I want to render. But I have tried to overwrite some of its values, I have also checked Django CMS GitHub to see how the request was used but I still can't manage to make the plugin's content show up. This is my view function: from django.contrib.auth.models import AnonymousUser from cms.views import details from cms.models.pagemodel import Page def create_html_files(request): cms_pages = Page.objects.filter(publication_date__isnull=False) request.user … -
ImproperlyConfigured: Error loading psycopg2 module: No module named 'psycopg2._psycopg' zappa
I am using zappa to deploy backend to the AWS Lambda. It worked well, until I decided to use PostgreSQL. I added it in the settings like this: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': config('DATABASE_NAME'), 'USER': config('DATABASE_USER'), 'PASSWORD': config('DATABASE_PASSWORD'), 'HOST': config('DATABASE_HOST'), 'PORT': '5432' } } I am using AWS RDS. I installed psycopg2-binary and also psycopg2 (versions 2.8.6), but the issue remains. The python version is 3.8. The full error log: [1621168086542] [ERROR] ImproperlyConfigured: Error loading psycopg2 module: No module named 'psycopg2._psycopg' Traceback (most recent call last): File "/var/task/handler.py", line 609, in lambda_handler return LambdaHandler.lambda_handler(event, context) File "/var/task/handler.py", line 240, in lambda_handler handler = cls() File "/var/task/handler.py", line 146, in __init__ wsgi_app_function = get_django_wsgi(self.settings.DJANGO_SETTINGS) File "/var/task/zappa/ext/django_zappa.py", line 20, in get_django_wsgi return get_wsgi_application() File "/var/task/django/core/wsgi.py", line 12, in get_wsgi_application django.setup(set_prefix=False) File "/var/task/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/var/task/django/apps/registry.py", line 114, in populate app_config.import_models() File "/var/task/django/apps/config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "/var/lang/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File … -
Getting this error when trying to execute "python manage.py runserver"
Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\yaswanth\AppData\Local\Programs\Python\Python39\lib\site-packages\django\urls\resolvers.py", line 600, in url_patterns iter(patterns) TypeError: 'module' object is not iterable The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\yaswanth\AppData\Local\Programs\Python\Python39\lib\threading.py", line 954, in _bootstrap_inner self.run() File "C:\Users\yaswanth\AppData\Local\Programs\Python\Python39\lib\threading.py", line 892, in run self._target(*self._args, **self._kwargs) File "C:\Users\yaswanth\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\yaswanth\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\commands\runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "C:\Users\yaswanth\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 419, in check all_issues = checks.run_checks( File "C:\Users\yaswanth\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\checks\registry.py", line 76, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Users\yaswanth\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\Users\yaswanth\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\yaswanth\AppData\Local\Programs\Python\Python39\lib\site-packages\django\urls\resolvers.py", line 413, in check messages.extend(check_resolver(pattern)) File "C:\Users\yaswanth\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\yaswanth\AppData\Local\Programs\Python\Python39\lib\site-packages\django\urls\resolvers.py", line 412, in check for pattern in self.url_patterns: File "C:\Users\yaswanth\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\functional.py", line 48, in get res = instance.dict[self.name] = self.func(instance) File "C:\Users\yaswanth\AppData\Local\Programs\Python\Python39\lib\site-packages\django\urls\resolvers.py", line 607, in url_patterns raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) from e django.core.exceptions.ImproperlyConfigured: The included URLconf '<module 'application.urls' from 'C:\Users\yaswanth\projects\calci\application\urls.py'>' 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.