Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to serialize and retrieve list of objects in Django Rest Framework?
I'm trying to retrieve a list of objects from my API, but even though they are properly stored in the Database from a script separate from the Django app, I am unable to read the list of objects properly and it gets converted to OrderedDic like so: -
send request from signal
I have an exam model that whenever an instance is created, instances of the Question model to the number that is specified in the Exam are created(using post_save signal). Also, I have a Go code that whenever a request is sent, fills out 3 fields of the Question model. My problem is how can I send this request in the signal part. The codes are as followed: models.py: class Exam(models.Model): title = models.CharField(max_length=255) subject = models.CharField(max_length=255, default='') organizer = models.CharField(max_length=255, default='...') description = models.TextField(max_length=1000) created_at = models.DateTimeField(auto_now_add=True) duration = models.DurationField() number_of_questions = models.PositiveSmallIntegerField() order = models.IntegerField(default=0) def __str__(self): return self.title class ExamQuestion(models.Model): exam = models.ForeignKey('ExamApply', on_delete=models.CASCADE) question_template = models.ForeignKey(QuestionTemplate, on_delete=models.CASCADE) text = models.TextField(max_length=5000, null=True, blank=True) question_params = models.JSONField(null=True, blank=True) answer_choices = models.JSONField(null=True, blank=True) answer_given = models.JSONField(default=dict, null=True, blank=True) correct_answer = models.JSONField(null=True, blank=True) data = models.JSONField(null=True, blank=True) is_correct = models.BooleanField(null=True) order = models.IntegerField(null=True, blank=True) def __str__(self): return str(self.id) class ExamApply(models.Model): class Status(models.TextChoices): CREATED = 'CR', 'Created' STARTED = 'ST', 'Started' FINISHED = 'FN', 'Finished' user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) exam = models.ForeignKey(Exam, on_delete=models.CASCADE) start_date = models.DateTimeField() end_date = models.DateTimeField() status = models.CharField(max_length=2, choices=Status.choices, default=Status.CREATED) def get_score(self): score = ExamQuestion.objects.filter(exam=self, answer_given=F('correct_answer')).count() return score signals.py: @receiver(post_save, sender=ExamApply) def create_examapply_examquestion(sender, instance, created, **kwargs): if created: … -
How to override a Model field without saving in Django
Suppose I have a model below : class Post(MainProcess, TimeStampedModel, SoftDeletionModel, models.Model): """Post model.""" slug = models.SlugField(default=uuid.uuid4(), unique=True, max_length=100) uuid = models.UUIDField(unique=True, max_length=500, default=uuid.uuid4, editable=False, db_index=True, blank=False, null=False) title = models.CharField(_('Title'), max_length=100, blank=False, null=False) image = models.ImageField(_('Image'), upload_to='blog_images', null=True, max_length=900, blank=True) I wanted to override the image field values without using the save() function, what is the best approach here which will be efficient. -
How To Implement Streaming in video raising and comments in Django rest framework
I developed a web application contain app of videos, I want to make video uploaded and comments like tiktok and facebook in my application to be streaming with DRF is there any modules or github repos could i see it , -
Django Transaction.atomic() Vs SQLAlchemy session for bulk update
I'm trying to find the best way to bulk update a MySQL DB using python the current ways I have are: req_model.objects.bulk_update(update_queries, list(column_to_update)) in this method, the problem is the fetching part required for the update_queries which is a list of updated objects of the model through internet scouring, I found out about Django's transaction.atomic(): with transaction.atomic(): for key, value in user_ids_dict: model.objects.filter(id=key).update(some_value=value) another issue with this is that Django doesn't support composite primary keys other than specifying them in the metaclass the other method (which I currently use) is using SQLAlchemy sessions(this works but its very slow due to server limitations): self.init_session() self.execute_bulk_update(model, mappings) self.session.commit() model is a list of dicts that contain updates and mappings is an SQLAlchemy model is atomic() faster than the session? I'll also gladly accept any other better suggestions for bulk-updating tables. -
using both MySQL and PostgreSQL in Django
I have a heavy-traffic website with a lot of users and posts and some other additional Features. and I want to redesign it using Django with DRF and vue.js. while I am searching for what is better to use between PostgreSQL and MySQL as the progect database I read that MySQL is better on performance if it read-only data. and PostgreSQL is better at doing queries. a- so I wanted to use MySQL to save posts on it which is read-only data as I think so. b- and save everything else in PostgreSQL. 1- is a & b a good idea to get a better performance for my website or just work with one database only? 2- can i link between those two databases -
Django Website does not load static files
I am in the middle of creating a django project and I have templates and static folders within the project directory. I can render and view the html files however it cannot load css files stored in the static folder. I have placed the load static tag in my html file but when I run python manage.py runserver it I get this error Performing system checks... Watching for file changes with StatReloader System check identified some issues: WARNINGS: ?: (staticfiles.W004) The directory '/static' in the STATICFILES_DIRS setting does not exist. System check identified 1 issue (0 silenced). December 08, 2022 - 14:54:53 Django version 4.1.3, using settings 'brighterstrat.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. This is how I have referenced the static files in my html file <link rel="stylesheet" href="{% static 'css/bootstrap.min.css'%}"> <link rel="stylesheet" href="{% static 'css/style.css'%}"> setting.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = [os.path.join(BASE_DIR, '/static')] STATICFILES_STORAGE = "django.contrib.staticfiles.storage.StaticFilesStorage" How can I make it load the css files -
my image is not storing on submit in django
When i submit my form having image it is not saving in any folder and when i submit it from django admin panel it is saving this is my models.py class dish(models.Model): dish_id = models.AutoField dish_name = models.CharField(max_length=255, blank=True, null=True) dish_category = models.CharField(max_length=255, blank=True, null=True) dish_size = models.CharField(max_length=7, blank=True, null=True) dish_price = models.IntegerField(blank=True, null=True) dish_description = models.CharField(max_length=255, blank=True, null=True) dish_image = models.ImageField(upload_to="", default=None, blank=True, null=True) dish_date = models.DateField() def __str__(self): return self.dish_name this is my setting.py STATIC_URL = 'static/' MEDIA_URL = 'images/' DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' MEDIA_ROOT = os.path.join(BASE_DIR, 'card/static/images') this is my view.py def index(request): if request.method == "POST": dish_name = request.POST.get('dish_name') dish_size = request.POST.get('dish_size') dish_price = request.POST.get('dish_price') dish_description = request.POST.get('dish_description') dish_image = request.POST.get('dish_image') dish_category = request.POST.get('dish_category') item = dish(dish_name = dish_name, dish_size = dish_size, dish_price =dish_price, dish_description = dish_description,dish_category=dish_category, dish_image=dish_image, dish_date = datetime.today()) item.save() dishs = dish.objects.all() params = {'dish': dishs} return render(request, "card/index.html", params) this is my form <form method="post" action="/index"> {% csrf_token %} <div>Dish name: <input name="dish_name" type="text" placeholder="Dish name"></div> <div>Dish category: <input name="dish_category" type="text" placeholder="Dish category"></div> <div>Dish size: <input name="dish_size" type="text" placeholder="Dish size"></div> <div>Dish price: <input name="dish_price" type="text" placeholder="Dish price"></div> <div>Dish description: <input name="dish_description" type="text" placeholder="Dish description"></div> <div>Dish image: <input name="dish_image" type="file"></div> <button type="submit" class="btn btn-success">Submit</button> … -
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 ?