Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Unable to create new project in django
(zenv) PS C:\Users\heman\Dev\try-django> django-admin startproject zFirst_site EROOR: Traceback (most recent call last): File "<frozen runpy>", line 198, in _run_module_as_main File "<frozen runpy>", line 88, in _run_code . . . . . . . File "C:\Python311\Lib\site-packages\django\db\models\fields\__init__.py", line 155, in __init__ if isinstance(choices, collections.Iterator): ^^^^^^^^^^^^^^^^^^^^ AttributeError: module 'collections' has no attribute 'Iterator' * It was all okay till by mistake i uninstalled every pip packages* -
Inside a Django model class, is it possible to asssign an attribute with the value of another attribute's foreign key?
class Post(models.Model): item = models.ForeignKey(Item, related_name="posts", on_delete=models.CASCADE) post_by = models.TextField(max_length=50) # value= With the above django model, is it possible to assign to value such that I get item's foreign key object called Item and then with that I get Item's id and this is stored in the attribute value? -
Django User Logging In System | Views.py doesn't work
I am currently making a user authentication system. I have a login screen with a couple of input fields. I can log the values of the input fields to the console in my javascript. I send the data to my backend. Submitting doesn't work and in my views.py loggin the data to the console too. I can basically completely remove the views.py function and the Template is shown anyway! Is that because I am using the Django Authentication Urls, so the registration folder is the default for the django registration? How can I send that to my backend? I have my logging in template (https://pastebin.com/RKe5ECps) Views.py def login_user(request): if request.method == "POST": username = request.POST["username"] password = request.POST["password"] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect('forum') else: messages.success(request, ("There was an error Loggin in, Try Again!")) return redirect('login') else: return render(request, 'login.html', {}) Urls.py path('', include('django.contrib.auth.urls')), Folder Structure: templates/registration/login.html templates/registration/signup.html I tried removing the authentication, but than i couldn't see anything, because at the login/ url there was nothing. -
Duplicate data after using update_or_create
In my project I retrieve data from an API that I save on my database created in parallel, the problem is that the initial data is duplicated each time I refresh the page that executes the API models.py class Empl(models.Model): code=models.CharField(max_length=10,blank=True,null=True) age=models.CharField(max_length=255,blank=True,null=True) service=models.CharField(max_length=255,blank=True,null=True) views.py url='http://myAPI/Empl/GetEmpl' x=requests.get(url) content=x.json() for data in content: emp , _ = Empl.objects.update_or_create(code=data['code'],age=data['age'],service=data['service']) emp.save() At the level of my project when I look for an employee on the search bar, several employees with the same data. And this every time I refresh the page that executes the API, the initial data is duplicated and so on. Oddly when I perform a filter on an employee through her code in Mysql Base I get a single tuple, I don't understand? -
How to handle network errors when saving to Django Models
I have a Django .save() execution that loops at n times. My concern is how to guard against network errors during saving, as some entries could be saved while others won't and there could be no telling. What is the best way to make sure that the execution is completed? Here's a sample of my code # SAVE DEBIT ENTRIES for i in range(len(debit_journals)): # UPDATE JOURNAL RECORD debit_journals[i].approval_no = journal_transaction_id debit_journals[i].approval_status = 'approved' debit_journals[i].save() -
Converting texts to foreign keys when importing data with Django excel
Tbl.1 id author brand_id name barcode unit user1 TestBrand1 Product1 TST1234 700 user2 TestBrand2 Product2 TST5678 380 I have an excel spreadsheet as in the example above. The author and brand_id in the table fields represent the foreignkey fields in the model. When the user wants to add a product to the system with excel, he/she has to enter the author and the brand as strings. Like the table in the example above. But since author and brand_id are foreign keys, excel should be like this.` Tbl.2 id author brand_id name barcode unit 1 1 Product1 TST1234 700 2 2 Product2 TST5678 380 My question is how can I dynamically convert the author and brand data received as strings as a foreign key on the database and save it. For example, if brand_id = TestBrand1, I want to record the id of that brand on the database.(As in Tbl.2) Here my Product models: class Product(models.Model): id = models.AutoField(primary_key=True) author = models.ForeignKey(User,on_delete= models.CASCADE, verbose_name='Product Author', null=True) brand_id = models.ForeignKey(Brand,on_delete=models.CASCADE, verbose_name="Brand Names") name = models.CharField(max_length=255, verbose_name="Product Name",unique=True) barcode = models.CharField(max_length=255, verbose_name="Barcode") unit = models.CharField(max_length=255,verbose_name="Product Unit") def __str__(self): return self.name Here my product views: @login_required(login_url="login") def addProduct(request): . . . . . elif … -
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'}), }