Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
FileNotFoundError on fresh install ubuntu 22 when running Pyest
I got a weird error when running pytest in a newly installed ubuntu 22. Google chrome was installed and running fine. However, when I run some tests in my Django project, pytest will yell that a file has not found error. I'm using pytest-django==4.5.2 and pytest==7.2.0 FileNotFoundError: [Errno 2] No such file or directory: '/home/me/.config/google-chrome/SingletonLock' Here is the test that currently causing pytest to fail import pytest from django.urls import reverse @pytest.mark.django_db def test_home_view(client): """ ensure our default home view is accessable and working""" url = reverse('packages') response = client.get(url) print(f" response {response}") assert response.status_code == 200 In another test file, pytest just running it without errors def test_DEBUG_env_var_exists(): if int(DEBUG) > 0: # debug is set to true in localhost pytest.skip("database misconfigured, test skip") assert os.environ.get('DEBUG') is not None Any idea why I got FileNotFound error and how to fix it? Regards -
This field is required error in django default image
I set my imagefield as NONE but when i tried to enter data without image from django admin panel it is showing that This field is required. this is my urls.py ` class dish(models.Model): dish_id = models.AutoField dish_name = models.CharField(max_length=255) dish_size = models.CharField(max_length=7) dish_price = models.IntegerField() dish_description = models.CharField(max_length=255) dish_image = models.ImageField(upload_to="", default=None) dish_date = models.DateField() def __str__(self): return self.dish_name ` How to set it as none if user not select any image -
paginate related queryset in django
I have two models named Card and Comment, both are related with a foreign key class Card(models.Model): image = models.CharField(max_length=100, default="") email = models.EmailField(unique=True, max_length=30, null = False, blank=False, default="") mobile = models.CharField(unique=True, max_length=12, null = False, blank=False, default="") uploaded_time = models.DateTimeField(auto_now_add=True) name = models.CharField(unique=True, max_length=30, null = False, blank=False, default="") active = models.BooleanField(default=True) def __str__(self): return self.name class Comment(models.Model): image = models.ForeignKey(Card, on_delete=models.CASCADE, related_name="comments") comment = models.CharField(max_length=100, blank=False, null=False) valid = models.BooleanField(default=False) I want to access card along with limited (comment size say 5) comments with select_related or prefetch_related query I have a load more button for comments, so when ever i press load more i want 5 more comments to be fetched someone pls answer, thnks:) -
What is the main purpose of using GraphQL with MVC web frameworks, when currently built-in MVC framework controllers do not make sense then?
What is the main purpose of using GraphQL with MVC web frameworks (Laravel, Django, etc.), when currently built-in MVC framework controllers do not make sense then? Is there any simpler way/framework with just that purpose and is the reason for that just love for Laravel, Django and other MVC frameworks? If there is nothing monolithic(server-side), similar and simpler, could we build something good and open-source just for that purpose, taking into account the increasing popularity of using that architecture and logic with GraphQL? After a lot of experience with backend and frontend technologies, that question comes to me logically. -
'Profile' object is not callable
TypeError at /accounts/signup/ 'Profile' object is not callable views.py def signup(request): if request.user.is_authenticated: return redirect("review:index") if request.method == "POST": signup_form = CustomUserCreationForm(request.POST) profile_form = ProfileForm(request.POST) if signup_form.is_valid() and profile_form.is_valid(): user = signup_form.save() profile = profile_form.save(commit=False) Profile.objects.create( user=user, nickname=profile.nickname, ) auth_login( request, user, ) return redirect("review:index") else: signup_form = CustomUserCreationForm() profile_form = ProfileForm() context = { "signup_form": signup_form, "profile_form": profile_form, } return render(request, "accounts/signup.html", context) models.py class User(AbstractUser): ..... class Profile(models.Model): nickname = models.CharField(max_length=8, unique=True, null=True) ....... forms.py class CustomUserCreationForm(UserCreationForm): class Meta: model = get_user_model() fields = [ "username", "password1", "password2", ] class ProfileForm(forms.ModelForm): class Meta: model = Profile() fields = [ "nickname", ........ ] In the process of filling out the signup form, I wanted to put the nickname data in profile.nickname. But 'Profile' object is not callable. A TypeError is raised. -
celery scheduled aws upload_file timeout
python def upload_file_to_aws(file_name): """Upload a file to an S3 bucket :param file_name: File to upload :return: True if file was uploaded, else False """ bucket = get_bucket() # If S3 object_name was not specified, use file_name object_name = file_name.split("/")[-1] # Upload the file s3_client = boto3.client( "s3", aws_access_key_id=AWS_ACCESS_KEY_ID, aws_secret_access_key=AWS_SECRET_ACCESS_KEY ) ce_logger.info(f"s3_client:{s3_client}") try: s3_client.upload_file(file_name, bucket, object_name) except Exception as e: logger.info(e) return False return True When I'm running the above method properly, I upload the file to aws s3 normally, but when I put this task in celery schedule, use the s3_client.upload_file(file_name, bucket, object_name) method. It will timeout. celery log is displayed [the 2022-12-08 13:40:03, 205: INFO/ForkPoolWorker-1] project.invoice.tasks.download_gmail_attachment_create_invoice[14b98680-7f38-45fb-9dbe-283330c304b0]: s3_client: [13:45:11 2022-12-08, 162: INFO/ForkPoolWorker-1] project.invoice.tasks.download_gmail_attachment_create_invoice[14b98680-7f38-45fb-9dbe-283330c304b0]: Connect timeout on endpoint URL: "https://karbon-text.s3.ap-south-1.amazonaws.com/upload_aSZcLIM.pdf" Why does this happen I want to upload files to aws s3 successfully in the celery schedule -
How to add tags to links via form in django?
I am working on a business directory and i wanna make form like this. Some links can have dofollow tag, some links can have nofollow or sponsored. How can i do this via using form in django. -
Query to obtain objects where an attribute's Foreign Key's id is known in django?
Considering the below django models, how can I obtain a list that contains only Message objects where the foreign key of product (found in Message class) is equal to a Product object's (from Product class) id that I have. By a list I mean something like: 'Test':[for product in product.objects.all()] ] class Product(models.Model): product_name = models.CharField(max_length=30) class Message (models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) message_body = models.TextField(max_length=50) I have looked at the below SO post but was not able to find what I wanted. django : get object from foreign key -
Im try send data from client to server and i get error
Im try send data from client to server and i get errorm, i use django, python & react. name: 'AxiosError' code: "ERR_BAD_REQUEST" message: "Unsupported protocol localhost:" the error i have enter image description here the data i want to send enter image description here api enter image description here views enter image description here url enter image description here mosels enter image description here -
Django queryset StringAgg on arrayfield
I have some data which includes sizes, much like the model below. class Product(models.Model): width = models.CharField() height = models.CharField() length = models.CharField() Through annotation we have a field called at_size which produces data like: [None, None, None] ['200', '000', '210'] ['180', None, None] This was accomplished like so (thanks to: )https://stackoverflow.com/a/70266320/5731101: class Array(Func): template = '%(function)s[%(expressions)s]' function = 'ARRAY' out_format = ArrayField(CharField(max_length=200)) annotated_qs = Product.objects.all().annotate( at_size=Array(F('width'), F('height'), F('length'), output_field=out_format) ) I'm trying to get this to convert into: '' '200 x 000 x 210' '180' In code, this could a bit like ' x '.join([i for i in data if i]). But as I need to accomplish this with database functions it's a bit more challenging. I've been playing with StringAgg, but I can't seem to find a way to exclude the null values. How can I accomplish this? -
How to make Django forms.Textarea responsive?
I am having difficulties trying to understand how to change Textarea sizes so that my webpage is responsive. I currently have it set where the rows are 8 and cols is 60 which is perfect for viewing a webpage on a desktop. However, as i am trying to make my webpage responsive, i can not find a way to change the column value down to 30. I have thought about using css media query for this but can not understand how to change the values as they are currently set in the forms.py file as as shown below. I know users are able to resize the Textarea but i would like it if they can not resize the text area. So my question is if it is possible to make the Textarea responsive? forms.py: class UserSettings(ModeldForm): class Meta: model = Profile fields = ["name", "email", "profile_biography"] widgets = { 'profile_biography': forms.Textarea(attrs={ 'rows': 8, 'cols': 60, 'style':'resize:none'}), } -
How to NOT include another Django template by default while keeping the tag in the template?
I have the following in settings/base.py SOME_TEMPLATE = os.getenv("SOME_TEMPLATE", "something/template.html") TEMPLATES = [ { # i skip .... "OPTIONS": { "context_processors": [ # i skip... # for the project-specific context "core.context_processors.settings_values", ], }, }, ] then in core/context_processors.py from django.conf import settings def settings_values(request): """ Returns settings context variable. """ # pylint: disable=unused-argument return { "SOME_TEMPLATE": settings.SOME_TEMPLATE, } in the actual template {% include SOME_TEMPLATE %} Without changing or removing {% include SOME_TEMPLATE %} what can I do such that by default, the template is not included? Preferably at the settings level? I was thinking of using if tag but i felt it would be more verbose. Is there a way to be less verbose and still achieve the same outcome? -
how to install mysqlclient python library in linux?
I have a Django project and I want to deploy it on a server.But I'm unable to connect mysql. I have tried different alternatives but I can't fixed this problem.(I have kali linux operating system) This is the error I am receiving when installing mysqlclient: pip install mysqlclient==2.0.0 1 ⨯ Collecting mysqlclient==2.0.0 Downloading mysqlclient-2.0.0.tar.gz (87 kB) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 87.9/87.9 kB 1.4 MB/s eta 0:00:00 Preparing metadata (setup.py) ... error error: subprocess-exited-with-error × python setup.py egg_info did not run successfully. │ exit code: 1 ╰─> [13 lines of output] /bin/sh: 1: mysql_config: not found /bin/sh: 1: mariadb_config: not found /bin/sh: 1: mysql_config: not found Traceback (most recent call last): File "<string>", line 2, in <module> File "<pip-setuptools-caller>", line 34, in <module> File "/tmp/pip-install-go97vzkz/mysqlclient_85ab5f5ba17f42dcba9e2b66191c32e1/setup.py", line 15, in <module> metadata, options = get_config() File "/tmp/pip-install-go97vzkz/mysqlclient_85ab5f5ba17f42dcba9e2b66191c32e1/setup_posix.py", line 65, in get_config libs = mysql_config("libs") File "/tmp/pip-install-go97vzkz/mysqlclient_85ab5f5ba17f42dcba9e2b66191c32e1/setup_posix.py", line 31, in mysql_config raise OSError("{} not found".format(_mysql_config_path)) OSError: mysql_config not found [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. error: metadata-generation-failed × Encountered error while generating package metadata. ╰─> See above for output. note: This is an issue with the package mentioned above, not pip. hint: See above for … -
DRF generate html to pdf
Im trying to generate pdf from given html file but get_template function is not working i guess. from io import BytesIO from django.template.loader import get_template from xhtml2pdf import pisa def render_to_pdf(context_dict={}): try: template = get_template('invoice.html') html = template.render(context_dict) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result) if not pdf.err: return result.getvalue() return None except Exception as e: print('ERROR', e) The Except block returns None. -
Deploying Django on AWS removes characters from static file links
Pictures taken from my browser view source page: Localhost as server: AWS as server: I don't know why it would do this, the page shows up fine when I run locally but on AWS it is not loading any static resources. -
How to Send simple variable/Data to Django model field with pure Javascript/Ajax?
#I want to insert an integer to django class Field but when I click POST it fails # In more spesific there is a problem to send a post request to django server. When i click on the post Button i get the following error on the Terminal. I tried by changing the variables, Functions etc... File "/home/nick/Desktop/new_venv/lib/python3.8/site-packages/django/utils/datastructures.py", line 86, in getitem raise MultiValueDictKeyError(key) django.utils.datastructures.MultiValueDictKeyError: 'age' [08/Dec/2022 11:21:03] "POST /post/ HTTP/1.1" 500 72563` This is Ajax Script in plain Javascript/Ajax including the buttons and the Id's``` `Includes HTML Code + the script `<button id="get">Send GET Request</button><br> <button id="post">Send POST Request</button> <script> var csrftoken = '{{ csrf_token }}' document.getElementById('get').onclick = () => { const requestObj = new XMLHttpRequest() requestObj.onreadystatechange = function () { if (this.readyState == 4 && this.status == 200) { console.log(this.responseText) } } requestObj.open("GET", '/get/') requestObj.send() } ` `document.getElementById('post').onclick = () => { const requestObj = new XMLHttpRequest() requestObj.onreadystatechange = function () { if (this.readyState == 4 && this.status == 200) { console.log(this.responseText) } } requestObj.open("POST", '/post/') requestObj.setRequestHeader("X-CSRFToken", csrftoken) // const formdata = new FormData() // formdata.append('name', 'John') // formdata.append('age', '17') // requestObj.send(formdata) var age = 16; requestObj.send(age) }`` `</script>` `the Views.py File ` These are the routes functions … -
can i deploay django project use "Geodjango" in digitalocean "app"?
I want to build an app based mainly on maps, and I want to use GeoDjango, but I'm a bit worried about hosting, does it need devops? can i host it in digitalocean app ? -
ModuleNotFoundError: No module named 'authentication.wsgi'
I am trying to deploy my django project on production server but getting failure error while setting up the gunicorn. Any kind of help would be appreciated. Thanks in advance. Below is the command I am running getting the error gunicorn --bind 0.0.0.0:8000 authentication.wsgi authentication is the name of application Below is the error log [2022-12-08 14:52:29 +0530] [79282] [INFO] Starting gunicorn 20.1.0 [2022-12-08 14:52:29 +0530] [79282] [INFO] Listening at: http://0.0.0.0:8000 (79282) [2022-12-08 14:52:29 +0530] [79282] [INFO] Using worker: sync [2022-12-08 14:52:29 +0530] [79284] [INFO] Booting worker with pid: 79284 [2022-12-08 14:52:29 +0530] [79284] [ERROR] Exception in worker process Traceback (most recent call last): File "/home/web/.local/lib/python3.8/site-packages/gunicorn/arbiter.py", line 589, in spawn_worker worker.init_process() File "/home/web/.local/lib/python3.8/site-packages/gunicorn/workers/base.py", line 134, in init_process self.load_wsgi() File "/home/web/.local/lib/python3.8/site-packages/gunicorn/workers/base.py", line 146, in load_wsgi self.wsgi = self.app.wsgi() File "/home/web/.local/lib/python3.8/site-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() File "/home/web/.local/lib/python3.8/site-packages/gunicorn/app/wsgiapp.py", line 58, in load return self.load_wsgiapp() File "/home/web/.local/lib/python3.8/site-packages/gunicorn/app/wsgiapp.py", line 48, in load_wsgiapp return util.import_app(self.app_uri) File "/home/web/.local/lib/python3.8/site-packages/gunicorn/util.py", line 359, in import_app mod = importlib.import_module(module) File "/usr/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 973, in _find_and_load_unlocked **ModuleNotFoundError: No module named 'authentication.wsgi'** [2022-12-08 14:52:29 +0530] … -
A model field for storing an ordered list of ForeignKeys with duplicates
I have two models A and B, and B would like to keep an ordered list of As that can contain duplicates. class A(models.Model): ... class B(models.Model): As = models.OrderedOneToManyWithDuplicatesField(A) Where OrderedOneToManyWithDuplicatesField is mythical. I imagine that it might be a ManyToManyField with a custom through model that keeps a and ordering key, but am not sure if and how that would support the same A appearing more than ones in a given B.As. class A(models.Model): ... class B(models.Model): As = models.ManyToManyField(A, through=A_List) class A_List(models.Model): A = models.ForeignKey(A) B = models.ForeignKey(B) index = models.PositiveIntegerField() I guess I haven't found any documentation clearly stating this yet, nor made time to test it (which I will do), and I am wondering if anyone has experience to share in the interim. I guess the question boils down to whether A_list can can contain multiple rows that have the same A and B but a different index. Which in turn may boil down to: How Django keys that model (if it has an independent AutoField primary key, implicit or explicit) for example. That is, A and B are not together a unique key. Whether the manager(s) have any built-in premises about through table uniqueness … -
How do i save multiple files and prevent multiple entry to database
I am trying to save multiple files to a database. The problem however is that whenever I upload, two entries are created. Here is an example of what i am saying and models.py COLLECTION=( ("FICTION", "Fiction"), ("NON-FICTION", "Non-Fiction"), ("AUTOBIOGRAPHY", "Autobiography"), ("BIOGRAPHY", "Biography"), ) def validate_book_extension(value): import os from django.core.exceptions import ValidationError ext = os.path.splitext(value.name)[1] # [0] returns path+filename valid_extensions = [".pdf", ".epub"] if not ext.lower() in valid_extensions: raise ValidationError("Unsupported file extension.") class Books(models.Model): """ This is for models.py """ book_title = models.CharField(max_length=255, default="", primary_key=True) collection = models.CharField(max_length=255, choices=COLLECTION, default="") # book_author = models.CharField(max_length=255, default="") # publication_year = models.CharField(max_length=4, default="") # isbn = models.CharField(default="", max_length=25) book = models.FileField(default="", upload_to="media/books", validators=[validate_book_extension], verbose_name="book Name") class Meta: verbose_name_plural = "Books" def __str__(self): return self.book_title forms.py class Book(forms.ModelForm): class Meta: model = Books exclude = ["book_title"] widgets = { "book_title":forms.TextInput(attrs={"placeholder":"How"}), "book":forms.ClearableFileInput(attrs={"multiple":True}) } views.py def books(request): form = Book() if request.method == "POST": form = Book(request.POST, request.FILES) files = request.FILES.getlist("book") if form.is_valid(): for f in files: names = str(f) name = names.strip(".pdf") file = Books(book=f, book_title=name) file.save() form.save() return redirect(index) else: form = Book() return render(request, "books.html", {"form":form}) So basically, what i want to achieve is to be able to save a file without creating multiple … -
Django check if object in post method have specific value
I'm using DRF and have object with ManyToMany field. I'd like to check if object that user sent on server contains any pk in that field. Then i want to set boolean field to true in linked object to that ManyToMany. Models: class Parent(models.Model): child_link = models.ManyToManyField(child, related_name="child") class Child(models.Model): in_use = models.BooleanField(default=False) Views: class ParentView(viewsets.ModelViewSet): serializer_class = ParentSerializer authentication_classes = (SessionAuthentication, ) def get_queryset(self): user = self.request.user return Parent.objects.filter(user=user) class ChildView(viewsets.ModelViewSet): serializer_class = ChildSerializer authentication_classes = (SessionAuthentication, ) def get_queryset(self): user = self.request.user return Child.objects.filter(user=user) Serializers: class ParentSerializer(serializers.ModelSerializer): class Meta: model = Parent fields = __all__ class ChildSerializer(serializers.ModelSerializer): class Meta: model = Child fields = __all__ -
Export an html to PDF in Django application with charts
I have a Django application, and I want to provide 'export to pdf' functionality on all pages, (Note: all pages have images). I saw multiple tutorials on the topic, there are two ways: either write your pdf on your own or provide an HTML file path and context dictionary (which is difficult for me to provide). I need something like the following: button -> some_url -> some_view_function -> get all content from requesting page -> show the pdf content to the user in a separate window so the user can save it. -
Can't access images via web with Azure storage and Django
I want to access the path of the image/blog in the browser, I am using Django rest API and the package Azure storage, I tried to make the container storage public, but still had no luck in accessing the image, what could be wrong? This is an example of the image I want to access, it's there in the storage but can't access it : https://guiomentor-staging.azurewebsites.net/media/blog_images/images_3.jpeg -
How to send an Javascript object to be processed on a Django Backend
I had asked this question but I found out it was a bit complicated. I have simplified the question here. I am doing payment processing with a javascript API. I get the results, but I want to send it to a Django backend to be processed. I am not too familiar with this Javascript/Django interaction, hence my issue. The following are the files. Subscription.py It's a simple page that lets users choose their subscription. @csrf_exempt @login_required(login_url='login') def subscription(request): user = request.user user_organization = OrganizationUser.objects.get(user=user) company = Company.objects.filter(name = user_organization.organization.name).first() today = datetime.date.today() form = CompanyForm(request.POST) subscription = Subscription.objects.all() if user_organization.is_admin == True: context = {'user_organization': user_organization, 'form': form, 'subscription': subscription, 'company': company, 'today': today,} return render(request, 'registration/subscription.html', context) else: return HttpResponse('You are not authorised to view this page') Here is the corresponding Subscription.html {% block content %} <div class="columns is-centered"> <div class="column is-5 box"> {% if company.paid_till < today %} <form action="" method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="content"> <h1 class="title is-4"> <i class="fa fa-exclamation-triangle" aria-hidden="true"></i> Account is not active </h1> Your company <strong>{{user_organization.organization}}</strong> is not active. Please renew the subscription.<br> </div> {% else %} <p class="label">We have great subcription options for you. Choose from our list either for monthly … -
Can't get information from codeforces API in Django
in my project, I need to show the name of the contest site. I can't hardcode the name as I have to load the name & details of various websites as per user need. I need to show the Contest site name, contest name, contest date & time(found in UNIX format in the API which has to be converted), contest URL (which is in the list of return items but not showing while I open the API) I am so new in Django and working for the first time with API I wrote the function in views.py def homepage(request): response = pip._vendor.requests.get('https://codeforces.com/api/contest.list').json() return render(request,'home.html',response) and in HTML I did this to get the name of all contests <div class="box"> {% for i in response %} {{i.name}} {% endfor %} </div>