Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to save python docx on client side using ajax?
I use python 3.6 Django, my code looks like this: from docx import Document document = Document() document.add_heading('My docx', 0) document.save('myFile.docx') return HttpResponse(document, content_type='application/vnd') I don't want to save it on server, instead I want to send it to client side using ajax and save it on client pc. Any thoughts how to do it? -
Django Oscar - Override form - AddToBasketForm
Alright, To be able to add another field to the "AddToBasketForm" in Django Oscar, I created a fork for the basket app and tried overriding the default "AddToBasketForm". #forms.py import datetime from django import forms from oscar.apps.basket.forms import AddToBasketForm as CoreAddToBasketForm # noqa isort:skip class AddToBasketForm(CoreAddToBasketForm): pass def __init__(self, basket, product, *args, **kwargs): # Note, the product passed in here isn't necessarily the product being # added to the basket. For child products, it is the *parent* product # that gets passed to the form. An optional product_id param is passed # to indicate the ID of the child product being added to the basket. self.basket = basket self.parent_product = product super().__init__(*args, **kwargs) # Dynamically build fields if product.is_parent: self._create_parent_product_fields(product) self._create_product_fields(product) # Create an aditional DateField self.fields['date'] = forms.DateField(initial=datetime.date.today) Now by overriding the form, I get an error saying: TypeError at /catalogue/product_1/ __init__() missing 2 required positional arguments: 'basket' and 'product' So by overrriding the form, I lost the initial form data, basket and product. It feels like this isn't the correct way to modify a form within Django Oscar. Anyone any ideas? Best regards, Kevin -
In Django how to convert a single page pdf from html template?
I am using puppeteer_pdf package to convert an HTML template into a pdf, but when my content increases, it creates another page in the pdf. I want the whole pdf as a single page. My main goal is the make a jpg image from that pdf and send the image to the client. If there is another way to make a jpg image from HTML maintaining all CSS and images it will be very helpful. This is my code : import os from puppeteer_pdf import render_pdf_from_template from django.conf import settings from django.http import HttpResponse def generate_pdf_invoice(invoice): context = { 'invoice': invoice } output_temp_file = os.path.join( settings.BASE_DIR, 'static', 'temp.pdf') pdf = render_pdf_from_template( input_template='shop/invoice_email_pdf.html', header_template='', footer_template='', context=context, cmd_options={ 'format': 'A4', 'scale': '1', 'marginTop': '0', 'marginLeft': '0', 'marginRight': '0', 'marginBottom': '0', 'printBackground': True, 'preferCSSPageSize': False, 'output': output_temp_file, 'pageRanges': '1-2', } ) filename = 'test.pdf' # return pdf response = HttpResponse(pdf, content_type='application/pdf;') response['Content-Disposition'] = 'inline;filename='+filename return response -
ImportError create_namedtuple_class Django Modeltranslation
I have an error while trying to use django-modeltranslation 0.18.3 in Django 2.2. Here's the end of the traceback: [...] from django.db.models.utils import create_namedtuple_class ImportError: cannot import name 'create_namedtuple_class' from 'django.db.models.utils' (/home/me/project/.venv/lib/python3.10/site-packages/django/db/models/utils.py) I can't figure what's wrong with modeltranslations and with django. I recreated a clean venv, nothing works. -
Django 'Makemigrations' are unable to access the database
When running python manage.py makemigrations I'm all of a sudden running into an error about being unable to connect to the database. The application itself is running perfectly fine and can connect with no issues, but manage.py is broken. This is the error in question: /Users///.venv/lib/python3.10/site-packages/django/core/management/commands/makemigrations.py:143: RuntimeWarning: Got an error checking a consistent migration history performed for database connection 'default': connection to server on socket "/tmp/.s.PGSQL.5432" failed: No such file or directory Is the server running locally and accepting connections on that socket? I've tried restarting everything, the database, application, computer, etc. I've nuked the venv and created a new one, double checked the database settings in settings.py and they are listed below: DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql", "NAME": os.getenv("DB_NAME"), "USER": os.getenv("DB_USER"), "PASSWORD": os.getenv("DB_PASSWORD"), "HOST": os.getenv("DB_HOST"), "PORT": os.getenv("DB_PORT"), } } -
Meta descriptions and titles on all html pages
I'm building a website using django and i'm now esploring about SEO and how to make my page visible when i'll publish it. I read that you should put titles and description for your website in all of your html pages that compose your website, however is it really necessary to put a title and a description for an URL that i use for exemple a password reset that you should not search directly from google? I used a block in the django template of my base.html and i was adding manually a title and a description tag for every html i have in this project. The fact is that i don't know what to write in specific URLs used for the website service reason and i would let it blanked. -
404 page not found django cookiecutter without error message
First time running the app on production (35.231.94.10) I am getting 404 page not found Not from django server and there aren't any error messages last logs belal-django-1 | PostgreSQL is available belal-django-1 | [2023-01-12 11:54:08 +0000] [1] [INFO] Starting gunicorn 20.1.0 belal-django-1 | [2023-01-12 11:54:08 +0000] [1] [INFO] Listening at: http://0.0.0.0:5000 (1) belal-django-1 | [2023-01-12 11:54:08 +0000] [1] [INFO] Using worker: sync belal-django-1 | [2023-01-12 11:54:08 +0000] [9] [INFO] Booting worker with pid: 9 belal-django-1 | [2023-01-12 11:54:08 +0000] [10] [INFO] Booting worker with pid: 10 belal-django-1 | [2023-01-12 11:54:08 +0000] [11] [INFO] Booting worker with pid: 11 belal-django-1 | [2023-01-12 11:54:08 +0000] [12] [INFO] Booting worker with pid: 12 belal-traefik-1 | time="2023-01-12T12:04:06Z" level=warning msg="A new release has been found: 2.9.6. Please consider updating." Tried rebuilding it Tried every page and still nothing -
How to fix Assertion error 400 in the following problem?
I am working on Django project. I am writing a test case for the following model: class Meeting(models.Model): team = models.OneToOneField("Team", on_delete=models.CASCADE) created_at = models.DateTimeField() def __str__(self) -> str: return self.team.name The code for Test case is as follows: class MeetingTestCase(BaseTestCase): def test_meeting_post(self): self.client.force_login(self.owner) meeting_data = { "team": self.team.id, "created_at": "2023-01-12T01:52:00+05:00" } response = self.client.post("/api/meeting/", data=meeting_data) self.assertEqual(response.status_code, status.HTTP_201_CREATED) Inside .setup() function, I have created a team object: self.team = factories.TeamFactory(name="Team", organization=self.organization) This is my factory class: class TeamFactory(factory.django.DjangoModelFactory): class Meta: model = models.Team But My test case is failing and I have following assertion error: self.assertEqual(response.status_code, status.HTTP_201_CREATED) AssertionError: 400 != 201 which means there is something wrong with my request. What wrong am I doing? -
I have problem with updating profile photo in Django
I am trying to update Profile photo with Django According to yt tutorials I created form for updating photo: class UserProfileForm(forms.ModelForm): class Meta: model = User_Model fields = ["profile_photo"] And this is my class to Change photo in views: class UpdatePhoto(TemplateView): template_name = "Messenger/update_photo.html" profile_form = UserProfileForm def post(self, response): data = response.POST file_data = response.FILES profile_form = UserProfileForm(data, file_data, instance=response.user.profile) if profile_form.is_valid(): profile_form.save() return redirect("/") print("rere") context = self.get_context_data(profile_form=profile_form) return self.render_to_response(context) My Model: class User_Model(models.Model): user = models.OneToOneField( User, null=True, on_delete=models.CASCADE, related_name="profile" ) profile_photo = models.ImageField( upload_to="images/", default="default_photo.jpg", null=True, blank=True ) chats = models.ManyToManyField(User, related_name="chats", blank=True) blocked_list = models.ManyToManyField(User, related_name="blocked_list", blank=True) I was trying with and without 'response.POST', result was the same, it does not update. However when I try to print 'file_data' I get something like this: <MultiValueDict: {'Browser': [<InMemoryUploadedFile: thumb.jpg (image/jpeg)>]}> Main Settings.py: # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/4.1/howto/static-files/ STATIC_URL = "static/" MEDIA_URL = "/media/" MEDIA_ROOT = os.path.join(BASE_DIR, "media") STATICFILES_DIRS = (os.path.join(BASE_DIR, "static"),) # Default primary key field type # https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField" And main urls.py: from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path("admin/", admin.site.urls), path("", include("Messenger.urls")), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) … -
How to check if a function parameter is a database model class?
I have a Django database models like: from django.db.models import Model class Student(Model): ..... class Grade(Model): ..... If I have a function that takes a model class as a parameter. How to check if the input parameter is a generic class that inherits from Model class? def do_stuff(model_class): ## check if model_class is a child class of Model -
Can I make changes in manage.py?
I am doing a django project where I want my manage.py to run the server automatically(python manage.py runserver command) if its called. I believe that manage.py uses "execute_from_command_line". So is it possible or I have to find some other way to solve my problem. I want my manage.py to run the server automatically -
Where to create .aws/config in my django project?
how to add .aws/config in django project on this file structure Hello I'm Studying Front-End Development and I was proceeding E-commerse Project with pre-made API, and Design. but they suddenly shut down the server and gave me away the backend Code without any explaination. the thing is I have no idea what to do. So I excute following command from README Install Virtual Environment & Dependency # ./backend python -m venv .venv source .venv/bin/activate pip install -r requirements.txt python manage.py githooks once I excute python manage.py githooks it says botocore.exceptions.NoCredentialsError: Unable to locate credentials Set AWS Profile vi ~/.aws/config ... [profile incourse-commerce] aws_access_key_id=** aws_secret_access_key=** region = ap-northeast-2 I think I should add my IAM credentials on this application but I dont know where to add ./aws/config on this file structure enter image description here please help ㅠㅠ -
Как можно реализовать GET запрос в Django на определенный URL и в качестве результата вывести в шаблон нужные поля из JSON?
Во views создал функцию, на чистом Python нужный резуальтат есть, не получается прокинуть в шаблон нужные поля и дальше перебрать их, пробовал с JsonResponse def index(request): str_input = 'https://upload.peertube.datacenter.by/w/h3e6b9MaFqbc5u4cZUxyQh' new_str = str_input.replace('/w', '/api/v1/videos') response = request.GET.get(new_str) links = json.loads(response) return render(request, 'hls_links/index.html', {'links': links}) -
Django form update optimistic locking, version based
I've got django model and view implemented like here: (+mysql db) class MyModel(models.Model): name = models.CharField(max_length=100) version = models.IntegerField(default=1, editable=False) def updateModel(request, id): toUpdate = MyModel.objects.get(pk=id) if request.method=='POST': form = MyModelForm(request.POST, instance=toUpdate) if form.is_valid(): actual = MyModel.objects.get(pk=id) if (actual.version == form.instance.version): form.instance.version = form.instance.version+1 form.save() return redirect('somewhere') else: #some error form = MyModelForm(instance=toUpdate) return render(request, 'somwhere2/createupdate.html', {'form':form}) The scenario is, - current model value is name="aaa", version=1 2 users open edit form, first, changes name "aaa" to "bbb", and saves, second changes name "aaa" co "ccc" and saves. I'd like that versioning mechanism to prevent such scenario, but I'm unable to achieve it... How to implement it? I've read everything I could about django optimistic locking etc, but unable to achieve it, -
Access SharePoint Folder using Service account
I have a SharePoint folder where the url looks like: "team..com/sites//Documentation/Forms/All items.aspx Now the requirement is to access this url using a service account and Django. Can you help me a way? Thanks in advance We have looked for different cases but haven't been successful at all. -
Pagination does not seem to be working in Django rest api with GET method
I have been trying to paginate by json response but in vain. below are my code snippets. views.py This gives me the entire result. The reason i'm converting to a dataframe is that i want to do some data cleaning and minipulation. class LogsNewAPI(APIView): pagination_class=CustomPagination def get(self,request, *args, **kwargs): envid = self.kwargs.get('envid') nodeid = self.kwargs.get('nodeid') startdatetime = self.request.GET.get('startdatetime') enddatetime = self.request.GET.get('enddatetime') filter_list=PegaAlerts.objects.filter(envId=envid, serverId=nodeid, generateddatetime__lte=enddatetime, generateddatetime__gte=startdatetime,).order_by('generateddatetime') df = read_frame(filter_list) json = df[['generateddatetime','msgid','fullLine']].to_json(orient='records',date_format='iso') return HttpResponse(json, content_type = 'application/json') i have also tried as below and that gives the error: LogsAPI requires either a 'template_name' attribute or a get_queryset() method that returns a QuerySet class LogsAPI(ListView): pagination_class=CustomPagination def get_queryset(self): startdatetime = self.request.GET.get('startdatetime') enddatetime = self.request.GET.get('enddatetime') filter_list=Alerts.objects.filter(envId=self.kwargs['envid'], serverId=self.kwargs['nodeid'], generateddatetime__lte=enddatetime, generateddatetime__gte=startdatetime,).order_by('generateddatetime') df = read_frame(filter_list) json = df[[ 'generateddatetime','msgid','fullLine']].to_json(orient='records',date_format='iso') return HttpResponse(json, content_type = 'application/json') pagination.py class CustomPagination(pagination.PageNumberPagination): page_size = 10 page_size_query_param = 'page_size' page_query_param = 'page_number' not sure if I'm missing something. Any suggestions or redirection would be of great help..Thanks!! -
How to create an registration form in django and create an qr code for the given data also store data in mysql database
create an platform with Django that gets input from the user about their name, states and cities in India and create QR code for it , also the data needs to be stored in Mysql database. The states and cities should be in dependent dropdown. If anyone can create this project, please send the code to me via email. Thanks for accepting! -
How to make the list into table Django
I have got an a list: [{'name': 'WEB-Разработчик/программист (SEO-правки)', 'description': 'Hastra Agency ищет разработчика с опытом работы с связи с ростом отдела SEO-продвижения. Требуемый о...', 'key_skills': ['HTML', 'CSS', 'MySQL', 'PHP', 'SEO'], 'employer': 'Hastra Agency', 'salary': 'None - 60000 RUR', 'area': 'Москва', 'published_at': '2022-12-12', 'alternate_url': 'https://hh.ru/vacancy/73732873'}, {'name': 'Веб-разработчик golang, react, vue, nuxt, angular, websockets', 'description': 'Обязанности: Стек: react, vue, nuxt, angular, websockets, golang Поддержка текущего проекта с сущест...', 'key_skills': [], 'employer': 'МегаСео', 'salary': '150000 - None RUR', 'area': 'Москва', 'published_at': '2022-12-12', 'alternate_url': 'https://hh.ru/vacancy/73705217'}, ....., ...... array is with 10 list's How can i make it into table? csv file? columns - name, description, key_skills, .... rows - 1, 2, 3, 4, 5 ... I need to make this table in Django, how can i do it? -
How To Make A Payment Gateway, With Both Python 3 And Django?
How do i make a payment gateway templet, That accepts both Debit, Creddit card (Visa, Mastercard, and American express), Cryptocurrencies (Bitcoin, Ethereum, Dogecoin, and Monero), By using both Python 3, And the Django framework, For my e-commerce website? It will be an open-source payment gateway templet, That could communicate directly with both Visa, Mastercard, American express, Coinbase, and Monero... themselves (I think). -
How to access static files when using URL dispatcher in django
How can I access the static files in Django when using URL dispatcher In the below code. I was unable to access static files In settings.py STATIC_URL = 'static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR,'static') ] In urls.py path('userupdate/<int:id>',UserOperation.updateInfo,name='update'), The static files is accessible when I am not sending the User.ID in url -
Can't change user profile image in django
I am really new to django and I am building a website for internal use in my company. I have extended the user model with another model called "profile" in order to store extra information about each user, including a profile picture. I have set up a form.py class with the data i'd like to be able to modify: class UserForm(forms.ModelForm): class Meta: model = Profile fields = ['office','role', 'userImage'] The form in the html is as follows: <form class="form" action="" method="POST" enctype="multipart/form-data"> {% csrf_token %} {% for field in form %} <div class="form__group"> <label for="Profile.userImage">{{ field.label }}</label> {{ field }} </div> {% endfor %} <div class="form__action"> <a class="btn btn--dark" href="{% url 'user-profile' request.user.id%}">Cancel</a> <button class="btn btn--main" type="submit">Update</button> </div> </form> And in the views.py, here is the function that takes care of this: def update_user(request): user = request.user profile = request.user.profile if request.method == 'POST': form = UserForm(request.POST, request.FILES, instance=profile) if form.is_valid(): form.save() return redirect('user-profile', pk=user.id) else: form = UserForm(instance = profile) return render(request, 'base/update-user.html', {'form': form}) And the profile model is: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) job= models.TextField(max_length=50, blank=True, verbose_name="Centro") role= models.TextField(null=True, max_length=50, blank=True, verbose_name="Cargo") userImage = models.ImageField(upload_to='profileImages/', default='profileImages/happy.jpg', verbose_name="Profile Image") @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): … -
How to make Nested Models in django
I am new to django. My task is to make a feature on shared documents in backend. Documents can have folders, like google docs.We will have list of documents within list of folders. I created following model classes: class Folder(models.Model): name = models.CharField(max_length=128, unique=True) def __str__(self) -> str: return self.name class File(models.Model): folder_name = models.ForeignKey(Folder, on_delete=models.CASCADE) docfile = models.FileField(upload_to='documents/%Y/%m/%d') def __str__(self) -> str: return self.name So first, a folder will be created. Then a file will be uploaded in that folder. My Questions are: In google docs, we can have folders inside folders. How can I update my model if I want to add this feature of adding folder inside folder and then storing file on it. What does FileField attribute actually do? I want to store the data in postgres database, not in my local storage. How to deal with that? What additional features should I add in my model for this purpose? -
How can i successfully implement django amp on my site
Please I'm trying to implement Django AMP in my site so According to the docs here https://django-amp-tools.readthedocs.io/en/latest/installation.html. I have added the required to my settings.py but still getting this error below (my_venv) ~/my_venv/amp $ python manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/data/data/com.termux/files/usr/lib/python3.11/threading.py", line 1038, in _bootstrap_inner self.run() File "/data/data/com.termux/files/usr/lib/python3.11/threading.py", line 975, in run self._target(*self._args, **self._kwargs) File "/data/data/com.termux/files/home/my_venv/lib/python3.11/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/data/data/com.termux/files/home/my_venv/lib/python3.11/site-packages/django/core/management/commands/runserver.py", line 125, in inner_run autoreload.raise_last_exception() File "/data/data/com.termux/files/home/my_venv/lib/python3.11/site-packages/django/utils/autoreload.py", line 87, in raise_last_exception raise _exception[1] File "/data/data/com.termux/files/home/my_venv/lib/python3.11/site-packages/django/core/management/__init__.py", line 398, in execute autoreload.check_errors(django.setup)() File "/data/data/com.termux/files/home/my_venv/lib/python3.11/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/data/data/com.termux/files/home/my_venv/lib/python3.11/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/data/data/com.termux/files/home/my_venv/lib/python3.11/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) ^^^^^^^^^^^^^^^^^^^^^^^ File "/data/data/com.termux/files/home/my_venv/lib/python3.11/site-packages/django/apps/config.py", line 193, in create import_module(entry) File "/data/data/com.termux/files/usr/lib/python3.11/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1206, in _gcd_import File "<frozen importlib._bootstrap>", line 1178, in _find_and_load File "<frozen importlib._bootstrap>", line 1149, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 690, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 940, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "/data/data/com.termux/files/home/my_venv/lib/python3.11/site-packages/amp_tools/__init__.py", line 4, in <module> from amp_tools.settings import settings File "/data/data/com.termux/files/home/my_venv/lib/python3.11/site-packages/amp_tools/settings.py", line 25, in <module> class defaults(object): … -
Integration of Django-PayPal subscription based payment system
I am trying to implement a Subscription-based payment method in Django with paypalrestsdk, and even the Django-Paylpal library. Integration with Django-Paypal Library. But with this, somehow it is not working for me. I am new to Django python and I am not able to integrate it so please help me with this. -
Flatten Nested QuerySet to a Pandas DataDrame
I am trying to fetch records of all devices with their related owners for the data as below Device ====== .Id .Name .owner_id Owner ===== .Id .Name How I try to get the data in django: data = Device.objects.select_related('owner').values() Now I would need the data of devices and their owner in a flattened pandas' DataFrame. e.g. a column like 'owner.name' is created in the dataframe. How can I do that? Tried 'from_records' didn't work. Tried 'json_normalize' but cannot convert queryset to json first. Thanks