Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django project deployed on AWS using postgres - how to create a database
I have a django project that I deployed on AWS using the awsebcli. I need to provision a database (postgres) and once the enviroment is deployed I create from the console a database I would like to automate this process and I tried a config file so I tried adding this to my django.config file inside the .ebextensions folder of my project: aws:rds:dbinstance: DBAllocatedStorage: '5' DBDeletionPolicy: Delete DBEngine: postgres DBEngineVersion: 10.17 DBInstanceClass: db.t2.micro DBPassword: PASSWORD_HERE DBUser: USERNAME_HERE MultiAZDatabase: false But in this way the database is not created. I have to created it from the console and then pass as enviromental variables using the terminal (eb setenv) the endpoint of the database and other parameters. Is there a way to solve this and automate the deployment? -
Django does not display block content
Hello my block content does not work. My directory looks like this: /first_page /templates /first_page /landingPage.html /base.html This is my base.html file <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> Text {% block content %} {% endblock %} </body> </html> this is my landingPage.html file {% extends "base.html" %} {% block content %} Hello StackOverflow! {% endblock %} Did I forget to include something? Do I have to change something in the settings? I will just "text" but not "Hello StackOverflow!" -
django block not showing
I want to add a navbar, messages and the content to the base.html, is this the right way to do it? I also want the profile to be as an extension of navbar so when you hover on profile buttton from navbar profile pops up. For now, I cannot see the navbar with block, but it work with include. base.html {% block nav %}' {% endblock nav%} {% block messages %} {% endblock messages %} {% block content %} {% endblock content %} navbar.html, should I use here include profile or a profile block? {% extends 'app/base.html' %} {% block nav%} // some more code here.. <li class="nav-item dropdown position-static"> <a class="nav-link dropdown-toggle" href="#" id="dropdown04" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Profile</a> <div class="dropdown-menu p-4" aria-labelledby="dropdown04"> {% include 'users/profile.html' %} </div> </li> {% endblock nav%} messages.html {% extends 'app/base.html' %} {% block messages %} {% if messages %} {% for message in messages %} <div class="alert alert-{{ message.tags }}"> {{ message }} </div> <div class="swal2-icon swal2-error swal2-animate-error-icon" style="display: flex;"><span class="swal2-x-mark"><span class="swal2-x-mark-line-left"></span><span class="swal2-x-mark-line-right"></span></span> </div> {% endfor %} {% endif %} {% endblock messages %} -
How can I return default value in django-parler if content is not filled in other langauges?
I am facing error in djagno admin. I am using django-parler package for multilangauge content and i18. For example if django admin language (i18) is in 'uz' language and content in django parler multi language content is not filled in uz, then djagno throws error that 'there is no translation for uz langauge' How can I return default value if content in specific langauge is not filled in django-parler -
How can I set token in header and redirect the user to an external url in django
I am developing an application where I need to set an token in the header and the redirect the user to another url and at receiver end I need to get the token from the request and then do some processing to display user specific data. what is the optimize way to do it functional based views -
django redirect to different view/page if permission denied
Hej! I have a view where contact details are rendered. The goal is to have some users who are allowed to see all details ('A') and some who only can see for example the name ('B'). Therefore I have two serializers in my model and two views (one for each serializer). The users are divided in two groups. The @user_passes_test does work so only the one in group 'A' are able to get into the view with the details. I want the ones which are in group 'B' to be redirected automatically to the view/page where the details are minimized. Any idea how to achieve that? I've got: # views.py def contacts_check(user): return user.groups.filter(name="Contacts = True").exists() @login_required @user_passes_test(contacts_check) def contacts(request): . . . @login_required def contacts_small(request): . . . # urls.py app_name = "app" urlpatterns = [ path("contacts", contacts, name="contacts"), path("contacts2", contacts_small, name='contacts2') ] I tried: @user_passes_test(contacts_check, login_url='contacts') but both user groups are directed to the url 'contacts' with the full view. ('B' gets an error that the user has no access). Same when login_url='contacts2'. I also tried: def sees_contacts(self): if str(self.user.groups.filter) == 'Contacts = True': return True else: return False con_login_required = user_passes_test(lambda u: True if u.sees_individuals else False, … -
How can I get space consumed by a queryset using Postgres
Suppose I make a query like - SELECT * FROM table_name WHERE condition I want to know how much disk space this queryset has consumed. -
Pycharm is not recognizing db.sqlite3 file
I am learning django and while practicing i came across a db.sqlite3 file that pycharm was not recognizing. I dragged and dropped it in db browser sqllite and i got an error "no database file opened". So what should i do? Can anyone help? If you want a clear idea of what i was doing please refer to last section(i.e project 3) of the video: https://www.youtube.com/watch?v=_uQrJ0TkZlc&ab_channel=ProgrammingwithMosh -
Django, Openpyxl: column widths are returning strange values
inside my app I'm creating a simple workbook and -sheet! Afterwards I'm iterating through a dictionary to adjust the columns width and the rows height. functions.py def create_workbook(): dict_col_width = { 'A': 2.22, 'B': 0.5, 'C': 2.33, 'D': 2.89, } dict_row_height = { 1: 44.4, 2: 9.9, 3: 15.6, 4: 85.2, } wb = Workbook() ws = wb.active ws.title = "Some title" for key, value in dict_col_width.items(): ws.column_dimensions[key].width = value for key, value in dict_row_height.items(): ws.row_dimensions[key].height = value return wb views.py ... wb = create_workbook() file_text = "some_file_name" response = HttpResponse(content=save_virtual_workbook(wb), content_type='application/ms-excel') response['Content-Disposition'] = f'attachment; filename={file_text}.xlsx' return response My problem is, that after downloading and opening the file, it seems the column widths have been created randomly. I've also tested the column width with the numbers 1 to 4 and these were the results: ws.column_dimensions[...].width = 1 --> results in a width of 0.56 ws.column_dimensions[...].width = 2 --> results in a width of 1.22 ws.column_dimensions[...].width = 3 --> results in a width of 2.22 ws.column_dimensions[...].width = 4 --> results in a width of 3.22 Strangely enough the rows were working perfectly fine! I've adjusted the column width in other programs before and this error(?) never occurred before! Does someone know … -
Django: Reproducing Migrations in Test Environment
Issue Background My development version is continuously developing with it's own database. I will makemigrations and migrate numerous times and evolve the local db. I will then push my changes on GIT once I feel the version is ready for the Test Environment. I will pull from the master and begin working on making the same migrations for the Test Environment (Has it's own DB). Issue As the code on the development version is being continuously developed (forms, views etc.) they become dependent on the models.py and database structure (imports and model usage). Therefore, when I attempt to makemigrations on the test environment by loads of dependency errors will throw up where I have referenced the new models in forms.py, views.py. For example: >>> python manage.py makemigrations File "C:\Users\<user>\<project>\<app>\forms.py", line 101, in UpdateCanisterForm choices=queryset_to_choice(CellModel.objects.all()), File "C:\Users\<user>\<project>\<app>\forms.py", line 34, in queryset_to_choice return [(x.id, x.__str__) for x in queryset] File "C:\Users\<user>\anaconda3\lib\site-packages\django\db\models\query.py", line 287, in __iter__ self._fetch_all() [...] django.db.utils.OperationalError: (1054, "Unknown column '<app>.site_id' in 'field list'") Note: <> replaced to maintain privacy Current Workaround My current work around is to comment out all the newly referenced fields until the code is happy with it's dependencies and I can migrate. What I want I'd … -
Create user in production or in local host for django
I don't know if this is a newbie question. But basically, I have website hosted on Pythonanywhere. When I want to make changes, the normal workflow is to make changes locally -> commit and push changes to github -> pull changes to pythonanywhere(PA) console and migrate. At the moment, I create accounts for my users manually and an email is then automatically sent to them with a link to set their own password. I do this like this. uid = urlsafe_base64_encode(force_bytes(user.pk)) token = default_token_generator.make_token(user) reset_view = reverse('password_reset_confirm', args=[uid, token]) url = request.build_absolute_uri( reset_view ) set_password_form = PasswordResetForm({'email':email}) assert set_password_form.is_valid() set_password_form.save( request=request, from_email="email", subject_template_name='accounts/welcome_email_subject.txt', email_template_name="accounts/welcome_email_template.html", html_email_template_name="accounts/welcome_email_template.html", extra_email_context = {'url':url , 'username':username,"name":name} ) I recently just realized that the domain of the generated password reset link depends on where I created the user account from. So if i created the user on localhost, the domain will be 127.0. 0.0 but if I created the account in Pythonanywhere, the domain will be mywebsite.com. Say if I decided to create an account on local server. the domain will be localhost so if I closed my computer before the user clicked on the link, they won't be able to set their password as the server … -
ERROR malformed node or string: <_ast.Call object at 0x7fcd19516d90> in django
I am trying to run a function on cluster after every 15 mins. But I am getting an error- The function is - def printer_function(): print("worked") reference for this function is - bbb_api.helper_lib.helper.stream_killer and I have scheduled it using on admin. but I am getting an error- ERROR malformed node or string: <_ast.Call object at 0x7fcd19516d90> can anyone help me understand this issue ? -
Django: Upload multiple directory of images at once
In my Django project, I want to upload bulk images for products from a directory of directories. Each directory is named after SKU for a product. There may or may not be multiple images inside each directory. How can I achieve this functionality? My Models: class Product(models.Model): sku = models.CharField('SKU', max_length = 200) name = models.CharField('Name', max_length = 1000) price = models.CharField('Price', max_length = 200) quantity = models.CharField('Quantity', max_length = 200) class Meta: verbose_name = 'Product' verbose_name_plural = 'Products' def __str__(self): return self.name class Image(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE, verbose_name='product_image') image = models.ImageField(upload_to='images/') class Meta: verbose_name = 'Image' verbose_name_plural = 'Images' def __str__(self): return str(self.image) I can upload bulk products using the below CSV. There are multiple images inside each SKU folder below. I want to upload the images from the folders at once and link them with their respective SKUs. How can I achieve that? Any guidance will be much appreciated. NB: I can upload a single image for a product. If we want to upload thousands of products and their related images, uploading a single image is not a feasible solution. -
how to restrict pages in Django? if "@login required(login_url='login')" does not work
I'm working on this signup-login project in Django and i want to restrict home page.. but for some reason this code is not working for me.. can you tell me why? and is there any other way to restrict pages in Django? @login_required(login_url='login') views.py @login_required(login_url='login') def index(request): all_members = {} return render(request, "HTML/index.html",{'Members': all_members}) -
Memcached warn with django "Select No error"
I'm using django with memcached store realtime data maybe reset key-value per 1min , however sometimes memcached will crash with problem "[warn] select: No error", and then django will miss getting data from memcached. how can i fix it? enter image description here -
*_set attributes on models from different Apps
I have two models defined in different Apps, related by a Many to Many relationship: #App 1, models.py class Parent(models.Model): name=models.CharField(max_lenght=10) #App2, models.py from App1.models import Parent class Child(models.Model): parents = models.ManyToManyField( to = Parent, blank = True, default = None, related_name = 'padres' ) I would like to access the Child element from the Parent Model. When Models are in the same app, you can just do child_set, but in this case, it is not defined. Is there anyway to do it? I can't define the M2M relationship in Parent because I'm importing other models from App1 in App2, and doing so would lead to a circular importing. -
Celery unit test retrying
I am currently writing unit tests for my celery tasks and would like to test that my task is being retried. Note: ALWAYS_EAGER is set to True in test settings @app.shared_task(bind=True, soft_time_limit=600, autoretry_for=(Exception,), retry_kwargs={'max_retries': 3}, retry_backoff=3) def my_task(self, obj_pk): try: # ... function_call_that_can_raise_exception() except Exception as exc: last_try = self.request.retries >= self.retry_kwargs["max_retries"] if last_try: # .... else: # ... raise_with_context(exc) I can test my last run by mocking celery.app.task.Task.request; @mock.patch("celery.app.task.Task.request") def test_my_task(self): mock_task_request.retries = 3 my_task(12) # some asserts How can I test that my task is actually retried automatically? -
Display two ModelForm class in a single Django html page
I am trying to create 2 forms and display it in a single Django HTML page. I created 2 Modelform class like this class CompanyForm(forms.ModelForm): class Meta: model = Company fields = "__all__" class ToyForm(forms.ModelForm): class Meta: model = Toy fields = "__all__" In the HTML page I am only able to embed the model = Company. How can I embed the Model = Toy in the same page, what I tried brings up the same Company Form. Here is the html code <form method="post"> {% csrf_token %} <h2> Company Form </h2> {{ form.as_p }} <input type="submit" value="Submit" /> </form> <form method="post"> {% csrf_token %} <h2> Toy Form </h2> {{ form.as_p }} <input type="submit" value="Submit" /> </form> -
Django HINT: You will need to rewrite or cast the expression./ ProgrammingError
Iam using Django i got this error wile migrate ProgrammingError at /admin/images/data/add/ column "order_data" is of type integer but expression is of type date LINE 1: ...Babies_name", "Age_name", "Images") VALUES (1234, '2021-09-0... ^ HINT: You will need to rewrite or cast the expression. Request Method: POST Request URL: http://localhost:8000/admin/images/data/add/ Django Version: 3.2.7 Exception Type: ProgrammingError Exception Value: column "order_data" is of type integer but expression is of type date LINE 1: ...Babies_name", "Age_name", "Images") VALUES (1234, '2021-09-0... ^ HINT: You will need to rewrite or cast the expression. Exception Location: C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\utils.py, line 84, in _execute Python Executable: C:\Users\Admin\AppData\Local\Programs\Python\Python39\python.exe Python Version: 3.9.7 Python Path: ['D:\vikram\Django\psi', 'C:\Users\Admin\AppData\Local\Programs\Python\Python39\python39.zip', 'C:\Users\Admin\AppData\Local\Programs\Python\Python39\DLLs', 'C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib', 'C:\Users\Admin\AppData\Local\Programs\Python\Python39', 'C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\site-packages'] Server time: Wed, 08 Sep 2021 20:41:59 +0000 from django.db import models # Create your models here. class data(models.Model): order_id = models.IntegerField() order_data = models.DateField() Babies_name = models.CharField(max_length=100) Age_name = models.IntegerField() Images = models.ImageField(upload_to='photo') -
django.db.utils.IntegrityError: could not create unique index "book_still_pkey" DETAIL: Key (number)=() is duplicated
That is my 2 migration where I try to change one field 'number' But I have the error : django.db.utils.IntegrityError: could not create unique index "book_still_pkey" DETAIL: Key (number)=() is duplicated. my migrations 003: class Migration(migrations.Migration): dependencies = [ ('book', '0003_auto_20510907_1254'), ] operations = [ migrations.RemoveField( model_name='library', name='number', field=models.CharField(blank=True, editable=False, max_length=8, unique=True,), ), migrations.RemoveField( model_name='library', name='link_number', field=models.PositiveIntegerField(validators=[django.core.validators.MinValueValidator(1), django.core.validators.MaxValueValidator(99999999)]), ), Than I changed my field 'number' in models.py and create new migration 004: class Migration(migrations.Migration): dependencies = [ ('efish', '0004_auto_20210901_2050'), ] operations = [ migrations.RemoveField( model_name='library', name='id', ), migrations.AddField( model_name='library', name='number', field=models.CharField(blank=True, editable=False, max_length=11, primary_key=True, serialize=False), migrations.AddField( model_name='library', name='link_number', field=models.PositiveIntegerField(default='', validators=[django.core.validators.MinValueValidator(1), django.core.validators.MaxValueValidator( 99999999)],preserve_default=False,), ] I think the problem in primary key!Anybode can help ???Please -
Add Pagination in Django Rest Framework
I am trying to use PageNumberPagination in DRF anf for that I have changed the settings.py file like the following: REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ), 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', # 'PAGE_SIZE':10 } and views.py from rest_framework.pagination import PageNumberPagination class GrnListAPIView(generics.ListAPIView): serializer_class = GrnListSerializer pagination_class = PageNumberPagination permission_classes = (permissions.IsAuthenticated, GRNViewPermission) def get_queryset(self): return Grn.objects.all() now when I try to access the data using the URL: http://localhost:8000/grns/?page=1&page_size=10 It gives me all the data rather than returning 10 objects. It works fine when I uncomment the PAGE_SIZE but only returns 10 values per page, which is understandable as I have mentioned page_size=10 in my params but when I change it to 20 or 30 it still returns the same amount of data instead of 20 or 30 objects. -
How to configure parallel execution in celery
I have a Django application with ML code taking around 15 min for execution. I have used RabbitMQ as the message broker and celery to handle the time taking task. currently i'm using the below command to run celery. this allows me to execute 4 task parallelly. celery -A Myappname worker --loglevel=info --concurrency=4 I want to execute 30 tasks parallelly. which command should i use ? should i just change concurrency=30 or is there any other way? The docs for celery is confusing. any help is appreciated. -
How to correctly create a json response of a logged in user for react
I started to try react and tried to simply get the logged in user info but this does not seem to work. I have a Django view to display the user data: def user_details_view(request, *args, **kwargs): #REST API for detailing some basic info about the user that is using the system at the moment current_user = request.user id = current_user.id try: obj = CustomUser.objects.get(id=id) data =obj.serialize() except: #data['message'] = "Not Found" status = 404 return JsonResponse(data) I set this view in the urls and if I access it I get the data I want. However, when I try it on react I get an internal server error. Here is the code so far: function loadUserInfo(callback){ const xhr = new XMLHttpRequest(); const method = 'GET'; const url = "http://127.0.0.1:8000/userdetails/"; const responseType = "json"; xhr.responseType = responseType; // Let the xhr request know that its getting a json xhr.open(method, url); //This opens the request with the method and url entered xhr.onload = function(){ console.log("This is the response: ",xhr.response) callback(xhr.response, xhr.status) } xhr.onerror = function(){ callback({"message":"The request was an error"}, 400) } xhr.send();//Trigger that request } function App() { const [info, setinfo] = useState(null) useEffect(()=>{ const myCallBack = (response,status)=>{ console.log(response,status) if (status === … -
Django error , Broken pipe from ('127.0.0.1', 33609)
I am creating django project and got this error. Broken pipe from ('127.0.0.1', 33609). What I've been trying to do is that I created table using auth_user table (default user authentication table of django framework) and I created my own table. When the user register , I will record it in auth_user table by using User.objects.create_user() then I create my own object and then .save() to my table. In this step , I created the nested property and I think I assigned each property in the correct way. From what I've got , both of them are successful and the records are saved to database. For the frontend ,I use axios with function .then to receive response from the server and it gives me error saying that Broken pipe from ('127.0.0.1', 33609). I've tried to debug this many ways and each of the way I tried , it makes no sense at all because both object are saved to database. Besides, the object mapping is correct (that's what I think). Here is my code (quite long , sorry for that) from django.http.response import JsonResponse from django.shortcuts import render from django.contrib.auth import authenticate , login from django.contrib.auth.models import User from application1.models … -
Conditional redirect on django?
I have a wishlist system. By this, user can add items to wishlist by clicking on heart icon, the problem is that i have two places where user can remove the items from wishlist: 1. User can remove items on the wishlis from the search results 2. User can remove items on the wishlis from "Wishlist" menu So by this, how to redirect based on page for example, 1, When user reclicks heart icon on search results it do action and redirect to same search result page 2, And when user reclicks heart icon on wishlist menu it should redirect back to wishlist again Here is the code def save_wish(request, pk): if request.method == 'POST': student = request.user.student ......... ......... return redirect('students:search') So the above code always returns to "search" irrespective the page user clicked, how to conditional redirect to "Search" when user clicks from search and to "wishlist" when user clicks from "wishlist" page?