Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
How to compare list of dict contains same values and generate new list contains similar items [closed]
list 1 [{"code":"1",},"code":"2",}] list 1 [{"id":"2"},{"id":1}] Expecting Result: [{"code":"1","id":"1"},{"code":"2","id";"2"}] -
Send randomly generated 6 digit otp via mail after each login in Django class based views
I'm using Django Class based views to develop a application. I have used Django-allauth for User login,Signup and Logout . Now i want to send a randomly generated 6 digit number as an otp via mail to user whenever user login. In function based view i know how to do it but dont know how to do that is class based view using django-allauth. please help me out , Thankyou -
How do I add SSL certificates to Docker container which have Django with UWSGI Postgres connected and reverse Proxy?
I am totally new to Docker but I set up everything for development and deployment that you can see in the below image. I have followed this tutorial for that. Here you can see the file structure and default.conf.tpl file I am also sharing Other file screenshots. This is docker-compose-deploy.yml file screenshot-1 This is docker-compose-deploy.yml file screenshot-2 I used docker-compose.yml for development and docker-compose-deploy.yml for deployment. Docker file which is located inside the proxy folder. Docker file which is located in the root folder. Last file which is run.sh Browsing result with https is this site can't be reached. I can share just 8 links. Browsing result with http I think I have shared all the necessary Screenshots. Please tell me what I do to set up SSL certificate? Anyone can also contact me to help. sumitdhakad2232@gmail.com Thank you in advance. -
django rest framework request vs self.request
in djnago rest framework what is difference between self.request and request in why we cant always use request and exactly in what situations we need to use self.request or request class MyView(APIView): def post(self, request, format=None): data = self.request.data login(request, user) i try to print them and both of them return same thing <rest_framework.request.Request: POST '/url/sub_url'> so why we user like data = self.request.data login(request, user) -
How can i retrieve the currencies in Django moneyed and diaplay them on a react frontend?
I have been trying to get the list of currencies from django moneyed by importing either the CURRENCIES or list_all_currencies function and sending that list to the frontend to populate a dropdown but I always get Serializer errors E.g. TypeError(f'Object of type {o.class.name} ' TypeError:Object of type Currency is not JSON serializable -
How to add a notification in admin panel in django
I want to build a notification panel in django admin panel. It should work like, when a customer book a order a notification/push- notification pop up in django-admin panel that shows a user had booked this item. I have no idea how to implement it, or which python package help me to doing this, can anyone suggest me how should I implement this. Thank you in advance. -
I need to know where i can find a error in code?
class UserAccountInfo(View): @staticmethod def details(user): result = { "user_id": user.id, "profile_id": user.userprofile.id, "name": user.userprofile.name, "phone": user.userprofile.phone return result