Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Creating Files dynamically with django
i m have 2 models Uploades and File one for an image and one for the OCR result of the image, so whenever i upload an image a file with the result is generated, when working on the admin panel and with DRF api root it works fine but when i try Postman i get 500 sever error and the image is submitted by no file is created, i don't really know what the reason is so i would appreciate some help. These are my models class Uploads(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) title=models.CharField(max_length=100,default='none') image=models.ImageField(upload_to='media',unique=True) created_at = models.DateTimeField(auto_now_add=True) this part is to create the file super(Uploads, self).save(*args, **kwargs) if self.id : File.objects.create( file=(ContentFile(Create_Pdf(self.image),name='file.txt') )) The Create_Pdf function is simply running pytesseract this is my File model: class File(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=True) label=models.CharField(max_length=100, default='none') title=models.CharField(max_length=200,default='test') file=models.FileField(upload_to='files') created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.id) -
How to calculate the amount with property price and get remaining balance in Django?
info I am trying to create a monthly installment app using Django. I don't know how I could calculate Property' price with amount. I want to calculate the property price with the Payment amount and get the remaining price and save it to database. Customer has multiple payments so every month i get new payment from single customer and compare with remaining amount and get new remaining amount. i don't know how can i do that? models.py class Property(models.Model): area = models.CharField(max_length=255) price = models.IntegerField(default=0) class Customer(models.Model): name = models.CharField(max_length=255) prop_select = models.ForeignKey(Property, on_delete=models.SET_NULL, null=True) class Payment(models.Model): customer = models.ForeignKey(Customer, null=True, on_delete=models.SET_NULL, blank=True, related_name='payment') amount = models.IntegerField(default=0) remaining = models.IntegerField(default=0) -
ModuleNotFoundError("'kafka' is not a valid name. Did you mean one of aiokafka, kafka?")
I am using Celery and Kafka to run some jobs in order to push data to Kafka. I also use Faust to connect the workers. But unfortunately, I got an error after running faust -A project.streams.app worker -l info in order to run the pipeline. I wonder if anyone can help me. /home/admin/.local/lib/python3.6/site-packages/faust/fixups/django.py:71: UserWarning: Using settings.DEBUG leads to a memory leak, never use this setting in production environments! warnings.warn(WARN_DEBUG_ENABLED) Command raised exception: ModuleNotFoundError("'kafka' is not a valid name. Did you mean one of aiokafka, kafka?",) File "/home/admin/.local/lib/python3.6/site-packages/mode/worker.py", line 67, in exiting yield File "/home/admin/.local/lib/python3.6/site-packages/faust/cli/base.py", line 528, in _inner cmd() File "/home/admin/.local/lib/python3.6/site-packages/faust/cli/base.py", line 611, in __call__ self.run_using_worker(*args, **kwargs) File "/home/admin/.local/lib/python3.6/site-packages/faust/cli/base.py", line 620, in run_using_worker self.on_worker_created(worker) File "/home/admin/.local/lib/python3.6/site-packages/faust/cli/worker.py", line 57, in on_worker_created self.say(self.banner(worker)) File "/home/admin/.local/lib/python3.6/site-packages/faust/cli/worker.py", line 97, in banner self._banner_data(worker)) File "/home/admin/.local/lib/python3.6/site-packages/faust/cli/worker.py", line 127, in _banner_data (' transport', app.transport.driver_version), File "/home/admin/.local/lib/python3.6/site-packages/faust/app/base.py", line 1831, in transport self._transport = self._new_transport() File "/home/admin/.local/lib/python3.6/site-packages/faust/app/base.py", line 1686, in _new_transport return transport.by_url(self.conf.broker_consumer[0])( File "/home/admin/.local/lib/python3.6/site-packages/mode/utils/imports.py", line 101, in by_url return self.by_name(URL(url).scheme) File "/home/admin/.local/lib/python3.6/site-packages/mode/utils/imports.py", line 115, in by_name f'{name!r} is not a valid name. {alt}') from exc -
My problem is Invalid password format or unknown hashing algorithm
I try to do sign up and login form using Modelform. I have form to sign up user but it can't set password becouse in admin panel in user lap in password field I have "Invalid password format or unknown hashing algorithm." Can anyone help me? My form succesful submit form. Please help me solve this problem. view def sign_up(request): context ={} who ={"teacher": Teacher, "student": Student} form = UserSignUpForm(request.POST or None) if request.method == "POST": if form.is_valid() and request.POST.get("who"): user = form.save() person = who[request.POST.get("who")] person(user=user).save() return render(request, 'school/index.html') context['form'] = form return render(request, 'registration/sign_up.html', context) form class UserSignUpForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(UserSignUpForm, self).__init__(*args, **kwargs) self.fields['first_name'].required = True self.fields['last_name'].required = True who = forms.ChoiceField( choices=[('student', 'Student'), ('teacher', 'Teacher')], label="", required=True, widget=forms.RadioSelect( attrs={'style':'max-width: 20em; ', 'autocomplete':'off', }) ) password = forms.CharField( label="Password", validators=[MinLengthValidator(8, message="Minimum 8 characters")], widget=forms.PasswordInput(attrs={'autocomplete':'off'})) confirm_password = forms.CharField( label="Confirm password", validators=[MinLengthValidator(8, message="Minimum 8 characters"), ], widget=forms.PasswordInput(attrs={'autocomplete':'off'})) class Meta: model = User fields = ('who', "username", 'first_name', 'last_name', "password", ) help_texts = {"username": None} widgets = { 'username': forms.TextInput(attrs={}), 'first_name': forms.TextInput(attrs={}), 'last_name': forms.TextInput(attrs={}), } def clean(self): cleaned_data = super(UserSignUpForm, self).clean() password = cleaned_data.get("password") confirm_password = cleaned_data.get("confirm_password") if password != confirm_password: msg = _(f'Password and confirm password does not … -
Why is this Django view failing to run a Powershell script via subprocess.call?
The following tests.py works correctly and executes a Powershell script via subprocess.call: import subprocess subprocess.call(["C:\\WINDOWS\\system32\\WindowsPowerShell\\v1.0\\powershell.exe", ". \"./testers.ps1\";", "&Foo(10)"]) Trying to execute the same call from within a Django/REST view, fails to do so: import subprocess from rest_framework.response import Response from rest_framework import status from rest_framework.decorators import api_view @api_view(['POST']) def bar(request): if request.method == 'POST': subprocess.call([f"C:\\WINDOWS\\system32\\WindowsPowerShell\\v1.0\\powershell.exe", ". \"./testers.ps1\";", "&Foo({request.data})"]) return Response(request.data, status=status.HTTP_201_CREATED) else: return Response(request.errors, status=status.HTTP_400_BAD_REQUEST) Error: [09/Jul/2021 08:31:52] "POST /profile-eraser/ HTTP/1.1" 201 5646 . : The term './testers.ps1' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:3 + . "./testers.ps1"; &Foo({request.data}) + ~~~~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (./testers.ps1:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException & : The term 'Foo' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:21 + . "./testers.ps1"; &Foo({request.data}) + ~~~~~ + CategoryInfo : ObjectNotFound: (hello:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException PS Script: Function Foo($intIN) { … -
how to filter images from a list of files in django-rest-framework
I have a Django rest server which server a list of files to react frontend. I would like to know if I can filter those files by images and display only images to my react frontend. I have searched a lot but cannot find anything useful. Please help me. Thank you in advance. class FileListView(generics.ListAPIView): serializer_class = ListFileSerializer permission_classes = (permissions.IsAuthenticated,) def get_queryset(self): owner = self.request.user.username return File_Uploader.objects.filter(owner=owner) -
Exception Type: TemplateDoesNotExist login templete doesn't exist
TemplateDoesNotExist at /login/ login.html Request Method: GET Request URL: http://localhost:8000/login/ Django Version: 3.2.5 Exception Type: TemplateDoesNotExist Exception Value: login.html Exception Location: C:\Users\LISHITHA\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\loader.py, line 19, in get_template Python Executable: C:\Users\LISHITHA\AppData\Local\Programs\Python\Python37-32\python.exe Python Version: 3.7.0 Python Path: ['C:\Users\LISHITHA\virl\logp', 'C:\Users\LISHITHA\AppData\Local\Programs\Python\Python37-32\python37.zip', 'C:\Users\LISHITHA\AppData\Local\Programs\Python\Python37-32\DLLs', 'C:\Users\LISHITHA\AppData\Local\Programs\Python\Python37-32\lib', 'C:\Users\LISHITHA\AppData\Local\Programs\Python\Python37-32', 'C:\Users\LISHITHA\AppData\Local\Programs\Python\Python37-32\lib\site-packages'] Server time: Sat, 10 Jul 2021 18:20:58 +0000 Template-loader postmortem Django tried loading these templates, in this order: Using engine django: django.template.loaders.filesystem.Loader: C:\Users\LISHITHA\virl\logp\templates\login.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\Users\LISHITHA\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\contrib\admin\templates\login.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\Users\LISHITHA\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\contrib\auth\templates\login.html (Source does not exist) """"' from django.urls import path from . import views urlpatterns=[ path('',views.home,name='home'), path('register/',views.register,name='register'), path('login/',views.login,name='login'), ] from django.shortcuts import render from django.http import HttpResponse,JsonResponse from django.urls import path def home(request): return HttpResponse('welcome home') def register(request): return render(request,'register.html') def login(request): return render(request,'login.html') 'DIRS': [os.path.join(BASE_DIR, 'templates')], and declared login templetes in that empty pasted starter templete """ http://localhost:8000/login/# -
How to display JavaScript alert in Django?
I am creating a simple website in Django. I have a form, and when it is submitted, the user is redirected to a new page. I want to display a javascript alert (example bellow) on the new page when the form is submited. I have looked and gotten the django messages way to work, but I do not want to use messages, I want a javascript alert. Can someone please help me? Javascript Alert -
How to configure Scrapy, ScrapyD, Django and Docker together?
I am building a scraping backend based on the libs mentioned in the title. I want Django to receive a URL, schedule scraping using ScrapyD, handle scraping by Scrapy (it persists the data into DB). I am currently using Docker and it looks this way: version: '3.1' volumes: init-db: data-db: services: mongo: image: mongo restart: always environment: MONGO_INITDB_ROOT_USERNAME: name MONGO_INITDB_ROOT_PASSWORD: password ports: - 27021:27021 command: mongod --quiet --logpath /dev/null scrapyd: image: zwilson/scrapyd build: . ports: - 6800:6800 volumes: - ./data:/home/scrapyd/data - ./scrapyd.conf:/usr/src/app/scrapyd.conf entrypoint: scrapyd splash: image: scrapinghub/splash ports: - "8050:8050" restart: always redis: image: "redis:alpine" ports: - "6379:6379" web: build: . restart: unless-stopped command: > bash -c "pip install -r requirements.txt && python manage.py makemigrations && python manage.py migrate && python manage.py runserver 0.0.0.0:8001" tty: true volumes: - .:/usr/src/app ports: - 8001:8001 depends_on: - mongo And I initialize the scrapyd connection this way: from scrapyd_api import ScrapydAPI scrapyd = ScrapydAPI('http://0.0.0.0:6800') Now inside my views when I try use the scrapyd service through: crapyd.schedule(project="default", spider="BookSpider", url=url) I get the following error: web_1 | DEBUG: Waiter future is already done <Future cancelled> web_1 | ERROR: Exception inside application: HTTPConnectionPool(host='0.0.0.0', port=6800): Max retries exceeded with url: /schedule.json (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7f330c1c42e0>: … -
Django REST get nested data in request
I'm new usigng django and drf . I have an issue with request a model with a foreig key. I have this 3 models : class Order(models.Model): id = models.BigAutoField(primary_key=True) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="user") fecha = models.DateTimeField(auto_now=True) def __str__(self): return f"Orden : {self.id}" class Product(models.Model): id = models.BigIntegerField(primary_key=True) name = models.CharField(max_length=100) def __str__(self): return self.name class OrderDetail(models.Model): order = models.ForeignKey(Order, related_name="orders", on_delete=models.CASCADE) product = models.ForeignKey(Product, related_name="products", on_delete=models.CASCADE) I want to retrieve all order data with its products from detail: Example : { id : 1 , user : 1 , fecha : 01/02/2021, products : [ { id : 1 , name : "product1" } { id : 2 , name : "prodcut2" } } My serializers are : class ProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = ["id", "name"] class OrderDetailSerializer(serializers.ModelSerializer): class Meta: model = OrderDetail fields = ['order' ,'product'] class OrderSerializer(serializers.ModelSerializer): products = OrderDetailSerializer(many=True) class Meta: model = Order fields = ['id', 'user', 'fecha' ,'products'] But I'm getting this error : AttributeError: Got AttributeError when attempting to get a value for field 'products' on serializer 'OrderSerializer'. The serializer field might be named incorrectly and not match any attribute or key on the 'Order' instance. Original exception text … -
DRY-rest-permissions somehow does not check my object permissions except global permissions
I have recently started implementing dry-rest-permissions, but I can't seem to get it to check the has_object_permissions, it appears that only the global permissions work for me. I am fairly new to implementing permissions and this is my first time implementing DRY-rest-permissions and have only recently started coding in django rest framework, so apologies for the lack of knowledge in advance. At the moment I am trying to delete a company object by simply having a user call a URL, that URL then gets the current user's active_company and then deletes it only if the current user is the active_company's company_owner. But what I discovered, is that I somehow can't get has_object_permissions to work anywhere? I have noticed that if I delete has_write_permission(request), and hit the company_delete URL it gives me the following error: '<class 'company.models.Company'>' does not have 'has_write_permission' or 'has_company_delete_permission' defined. This means that it doesn't even look for the has_object_company_delete_permission. Meaning it only checks the global permissions rather than any of the object permissions, what am I possibly doing wrong here? My model: class Company(models.Model): company_name = models.CharField(max_length=100) company_orders = models.IntegerField(blank=True, null=True) company_icon = models.ImageField( upload_to='media/company_icon', blank=True) company_owner = models.ForeignKey( User, on_delete=models.SET_NULL, blank=True, null=True) company_employees = models.ManyToManyField( … -
error while binding html with mysql database using django
from django.shortcuts import render from Insertemp.models import EmpInsert from django.contrib import messages #from django.http import HttpResponse def Insertrecord(request): if request.method=='POST': if request.POST.get('epname')and request.POST.get('email')and request.POST.get('country'): saverecord=EmpInsert() saverecord.empname=request.POST.get('empname') saverecord.email=request.POST.get('email') saverecord.country=request.POST.get('country') saverecord.save() message.success(request,'Record Saved Successfully...!') return render(request,'Index.html') else: return render(request,'Index.html') [views.py file][1] when binding HTML form with MySQL database by django after submiting submit button from html form I get error ValueError at / The view Insertemp.views.Insertrecord didn't return an HttpResponse object. It returned None instead. Request Method: POST -
raise TypeError( TypeError: Direct assignment to the forward side of a many-to-many set is prohibited. Use child_tag.set() instead
when i am tring to send post request to add blog-post in my database. i am getting this error. raise TypeError( TypeError: Direct assignment to the forward side of a many-to-many set is prohibited. Use child_tag.set() instead. i want to create blog-post with minimum data like title. i want to save blog-post with at least title so that i can edit later. here is my post request img my model class Post(models.Model): title = models.CharField(max_length=200, unique=False) slug = models.SlugField(max_length=300, unique=True, null=True, blank=True) author = models.ForeignKey("users.NewUser", on_delete= models.CASCADE) tag = models.ForeignKey(MainTag,to_field='tag_name', blank=True, null=True, on_delete=models.SET_NULL) child_tag = models.ManyToManyField(ChildTag, blank=True, null=True) def save(self, *args, **kwargs): self.slug = slugify(self.title) + "-" + str(self.id) super(Post, self).save(*args, **kwargs) self.slug = slugify(self.title) + "-" + str(self.id) super(Post, self).save(*args, **kwargs) my post request class BlogpageView(APIView): def post(self, request, *args, **kwargs): new_data = request.data.copy() new_data.update({'author':request.user.id}) serializer = PostSerializer(data=new_data) if serializer.is_valid(raise_exception=True): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST ) serializer class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = '__all__' def create(self, validated_data): return Post.objects.create(**validated_data) def validate(self, data): if hasattr(self, 'initial_data'): unknown_keys = set(self.initial_data.keys()) - set(self.fields.keys()) if unknown_keys: raise ValidationError("Got unknown fields: {}".format(unknown_keys)) return data -
How it is filtering unique fields of email?
Whats is the difference between email and self.email def is_exists(self): if SignUp.objects.filter(email=self.email): return True return False``` -
Browse files from django template page
is there any way how to browse files in specific local folder with django template. I made an application that backup routers configuration every 3 days ans save these backuped configuration files into django server. I want to let users to browse these file in case they need to go back to old config file. files now are stored into ROOT/config_backup directory I want users to be able to browse only from that folder -
Django + JavaScript(jQuery) dynamic removal of dropdown option?
I am working on a backend Django project which uses a Bootstrap selectpicker. I am working on an edit view, and having trouble removing certain dropdown select options, based on the users previous saved information. I have tried using jQuerys .remove() .hide() and plenty other options but all select options still show. The dropdown provides a list using a django context proocessor <div class="form-group"> <label>Job Type</label> <div class="select-panel"> <select class="selectpicker" name="job_type" id="edit_job_type"> <option value="">Select</option> {% for obj in job_type %} <option value="{{ obj.name }}" second_job_cat="{{ obj.second_job_cat }}">{{ obj.name }}</option> {% endfor %} </select> </div> </div> And then in the JS popup modal GET request, that provides the popup modal form with the users existing data. // grab from the django view the users previous job type. let select_job_type = data['edit_job_type']; // set the value to previous value $("#edit_job_type").selectpicker('val', select_job_type); $("#edit_job_type").selectpicker('refresh'); This is the function I am trying to use to remove the values I do not want. let second_job_cat = document.getElementById('edit_job_type'[sel].dataset.secondJobCat; $("#edit_job_type > option").each(function() { if (second_job_cat !== this.dataset.secondJobCat){ console.log($(this).val()) $(this).remove() // also tried $(this).val().remove() } }); When I console.log the $(this).val() it does log all of the option values I do not want, which should be a good sign? … -
Database querying
I'm having an issue here that I want clarification with, see, I'm making a program that does analysis of data. I wanted to query data from different users, the data is numerical by the way, whenever I'd get subject marks from a user, I want the system to return the name of the user who has those marks. It was all working fine until I tried querying the users with the same marks, and all I could get was an error analyzer.models.ResultsALevel.MultipleObjectsReturned: get() returned more than one ResultsALevel -- it returned 4! So I was trying to find a way to still query and return the name of users with that subject mark, even if they have the same marks. I believe that should be possible since the users have different id's and stuff, help would be much appreciated! Here's my views.py biology_marks = [] for student in ResultsALevel.objects.all(): biology_marks.append(student.advanced_biology_1) value_1_biology = ResultsALevel.objects.get(advanced_biology_1=biology_marks[-1]).student_name.last_name value_2_biology = ResultsALevel.objects.get(advanced_biology_1=biology_marks[-2]).student_name.last_name value_3_biology = ResultsALevel.objects.get(advanced_biology_1=biology_marks[-3]).student_name.last_name value_4_biology = ResultsALevel.objects.get(advanced_biology_1=biology_marks[-4]).student_name.last_name -
Avoid invocation of a business logic by looking up a table column value without race-condtion
Is the possible to to effectively block invocation of a function by looking a database table column value. I've a model(LookupTable) as follows, In my app(Django + Postgres) There is a chance that 'my_function' is called in two ways 1. by a third party(via API call) after a particular event happened and 2. by my own job ( call after some fixed time after particular event happened) I want to make sure 'my_function' is called either by third party or by my own job for a 'unique_id'. My plan is to look the 'LookupTable' status column and to determine whether to continue the execution of 'my_function'. Once any of the process invoked the function mark the status from 'I' to 'U'. I use the following strategy to make sure, if both the process start work at the same time LookupTable(models.Model): some_unique_id = models.CharField(max_length=256) status = models.CharField(choices=(('I', 'Initiated'), ('U', 'Updated'))) @transaction.atomic def my_function(unique_id): # The following call is invoked only if status is 'Initiated'. lookup = LookupTable.objects.select_for_update.filter(some_unique_id=unique_id, status='I'). # only one record per unique_id if not lookup: return lookup.update(state='U') # My business logic which create/update some records in some other table ---------- ---------- I've used 'select_for_update' and transaction to block other … -
Django and Bootstrap: prevent warning box from appearing if there is an empty string
I'm using Django templates and Bootstrap to render a red alert box if there is a message. The code is: views.py else: return render(request, 'auctions/listing.html', { 'listing': listing, 'form': BidForm(), 'message': '', 'comments': listing.comments.all() }) listing.html <div> <p>Starting Bid: {{ listing.starting_bid}}</p> <p>Current Bid: {{ listing.price }}</p> <div class="alert alert-danger" role="alert" style="display: inline-block;"> {{ message }} </div> </div> The red warning box renders if there is no message (i.e. an empty string), which seems sensible and intuitive. However, when I remove message from views.py altogether, the red warning box still renders. else: return render(request, 'auctions/listing.html', { 'listing': listing, 'form': BidForm(), # 'message': '', 'comments': listing.comments.all() }) What am I doing wrong here? Thanks! -
authenticate had None value
In form to I try login user but I have message like below 'AnonymousUser' object has no attribute '_meta' In view sign_in my user had also None value, my username and password is correct I am sure.Where is a problem? In view sign_in my user had also None value, my username and password is correct I am sure.Where is a problem? forms from django import forms from django.contrib.auth.models import User from django.core.validators import MinLengthValidator from django.utils.translation import gettext_lazy as _ from crispy_forms.helper import FormHelper from crispy_forms.layout import Layout, Div, Submit, HTML, Button, Row, Field, Column from crispy_forms.bootstrap import AppendedText, PrependedText, FormActions class UserSignUpForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(UserSignUpForm, self).__init__(*args, **kwargs) self.fields['first_name'].required = True self.fields['last_name'].required = True who = forms.ChoiceField( choices=[('student', 'Student'), ('teacher', 'Teacher')], label="", required=True, widget=forms.RadioSelect( attrs={'style':'max-width: 20em; ', 'autocomplete':'off', }) ) password = forms.CharField( label="Password", validators=[MinLengthValidator(8, message="Minimum 8 characters")], widget=forms.PasswordInput(attrs={'autocomplete':'off'})) confirm_password = forms.CharField( label="Confirm password", validators=[MinLengthValidator(8, message="Minimum 8 characters"), ], widget=forms.PasswordInput(attrs={'autocomplete':'off'})) class Meta: model = User fields = ('who', "username", 'first_name', 'last_name', "password", ) help_texts = {"username": None} widgets = { 'username': forms.TextInput(attrs={}), 'first_name': forms.TextInput(attrs={}), 'last_name': forms.TextInput(attrs={}), } def clean(self): cleaned_data = super(UserSignUpForm, self).clean() password = cleaned_data.get("password") confirm_password = cleaned_data.get("confirm_password") if password != confirm_password: msg = _(f'Password and confirm … -
Error loading psycopg2 module in aws with django
I am trying to put my django's webpage to AWS. However, I receive a problem. It says to me that It can't find psycopg2 library. Jul 9 17:09:09 ip-172-31-44-212 web: raise ImproperlyConfigured("Error loading psycopg2 module: %s" % e) Jul 9 17:09:09 ip-172-31-44-212 web: django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: No module named 'psycopg2' Using pip list I can see what things are instaled in my virtual env. And it's clear that I have installed psycopg2. (eb-virt) PS C:\Users\ANDRES\Desktop\GlobalcodigoTfg\project> pip list Package Version ---------------------- --------- APScheduler 3.7.0 asgiref 3.3.4 astroid 2.5.6 attrs 20.3.0 Automat 20.2.0 aws-psycopg2 1.2.1 backcall 0.2.0 beautifulsoup4 4.9.3 certifi 2020.12.5 cffi 1.14.5 chardet 4.0.0 click 7.1.2 colorama 0.4.4 constantly 15.1.0 cryptography 3.4.6 cssselect 1.1.0 cycler 0.10.0 decorator 4.4.2 dj-database-url 0.5.0 dj-places 4.0.0 Django 3.2.3 django-apscheduler 0.5.2 django-decouple 2.1 django-durationwidget 1.0.5 django-extensions 3.1.3 django-location-field 2.1.0 docopt 0.6.2 future 0.18.2 geocoder 1.38.1 geographiclib 1.52 geonames 0.1.3 geopy 2.1.0 googlemaps 4.4.5 graphviz 0.16 gunicorn 20.1.0 humanfriendly 9.1 hyperlink 21.0.0 idna 2.10 incremental 21.3.0 ipykernel 5.5.5 ipython 7.24.1 ipython-genutils 0.2.0 isort 5.7.0 itemadapter 0.2.0 itemloaders 1.0.4 jedi 0.18.0 jmespath 0.10.0 jupyter-client 6.1.12 jupyter-core 4.7.1 kiwisolver 1.3.1 lazy-object-proxy 1.5.2 llvmlite 0.36.0 lxml 4.6.2 Mako 1.1.4 MarkupSafe 2.0.1 matplotlib 3.4.2 matplotlib-inline 0.1.2 mccabe 0.6.1 mysql-connector-python … -
Unexpexted atribute error 'UserProfileView' object has no attribute 'get'
I tried so hard to fix issues but I keep getting a issue after issue I hope someone can help me. Traceback: AttributeError at /profile_page/post.profile 'UserProfileView' object has no attribute 'get' models.py: class UserProfileView(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) bio = models.TextField() profile_pic = models.ImageField(null=True, blank=True, upload_to='images/profile/') website_url = models.CharField(max_length=255, null=True, blank=True) facebook_url = models.CharField(max_length=255, null=True, blank=True) pinterest_utl = models.CharField(max_length=255, null=True, blank=True) instagram_url = models.CharField(max_length=255, null=True, blank=True) twitter_url = models.CharField(max_length=255, null=True, blank=True) def __str__(self): return self.name def get_absolute_url(self): return reverse('article-detail', args=[str(self.id)]) home.html: <a href="{% url 'profile_page' pk %}"> urls.py: path('profile_page/<str:pk>', UserProfileView, name='profile_page'), -
Deleting posts via Django command doesn't work
Deleting posts via Django command does not work. I do not know what to do, I am at a dead end. I hope you can help me... delnc.py File command class Command(BaseCommand): help = 'Командa для удаления всех постов из категории' requires_migrations_checks = True missing_args_message = 'Недостаточно аргументов' def add_arguments(self, parser): parser.add_argument('category_name', type=str) def handle(self, *args, **options): print('Мастер код: 7548') answer = input('Введите Мастер код для удаления: ') if answer == '7548': try: category = str(options['category_name']) Post.objects.filter(postCategory__category_name=category).delete() Post.save() self.stdout.write(self.style.SUCCESS(f'Успешно. Все новости категории {category} удалены!')) except Post.DoesNotExist: self.stdout.write(self.style.ERROR('Нет такой категории! Отказано!')) else: self.stdout.write(self.style.ERROR('В доступе отказано!')) models.py class Category(models.Model): category_name = models.CharField(max_length=64, unique=True) subscribers = models.ManyToManyField(User, blank=True, null=True) class Meta: verbose_name = 'Категория' verbose_name_plural = 'Категории' def __str__(self): return self.category_name class Post(models.Model): PostAuthor = models.ForeignKey(Author, on_delete=models.CASCADE, verbose_name='Автор поста') PostNews = 'PN' PostArticle = 'PA' # «статья» или «новость» POSITIONS = [ (PostArticle, 'Статья'), (PostNews, 'Новость'), ] postCategory = models.ManyToManyField(Category, verbose_name='Категория поста', through='PostCategory') title = models.CharField(max_length=50, verbose_name='Название') positions = models.CharField(max_length=2, choices=POSITIONS, default=PostArticle, verbose_name='Тип поста') category_id = models.ForeignKey(Category, verbose_name='Категория', null=True, on_delete=models.CASCADE, related_name='category_id') data = models.DateTimeField(auto_now_add=True, verbose_name='Дата создания') data_update = models.DateTimeField(auto_now=True, verbose_name='Дата редактирования') photo = models.ImageField(upload_to='photos/%Y/%m/%d/', verbose_name='Фото', blank=True, default='/photos/def/1.jpg/') previewName = models.CharField(max_length=128, verbose_name='Превью поста') text = models.TextField(verbose_name='Текст поста') rating = models.SmallIntegerField(default=0, verbose_name='Рейтинг') public = models.BooleanField(default=True, … -
how to partially display information from django database?
I want to partially display information from django database. For example: There is a phone number in the database - +33547895132. In html i want to display - +3354*****2 -
In my blogging website i want to delete a user and all its associated blogs and comments
I deletes a user then all the associated blogs were also deleted but the associated comments are not deleted why comments model is indirectly related to User model using foreign key. Can anyone give me the answer models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class blogpost(models.Model): created_by=models.ForeignKey(User,on_delete=models.CASCADE) topic=models.CharField(max_length=122,null=True,blank=False) title=models.CharField(max_length=250,blank=False) post=models.TextField() likes=models.ManyToManyField(User, related_name='blog_posts') date=models.DateTimeField(auto_now_add=True ) def __str__(self): return ' (' +str(self.created_by)+') Title- '+self.title class Meta: ordering=['-date'] class CommentModel(models.Model): post = models.ForeignKey(blogpost ,related_name='comments', on_delete=models.CASCADE) name = models.CharField(max_length = 100) body = models.TextField() date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return '%s - %s' %(self.post.title, self.name) class Meta: ordering=['-date_added'] views.py def comment_view(request, pk): if request.method=='POST' and 'comment_button' in request.POST: body=request.POST.get('comment_text') post=blogpost.objects.get(pk=pk) obj=CommentModel(body=body) obj.name=request.user obj.post=post obj.save() return HttpResponseRedirect(reverse('detaildata',args=[str(pk)]))