Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I create a "package.json" file? Git clone repository is missing a package.json file
Am new to coding, I have cloned this GitHub repository https://github.com/TribeZOAGit/zoa_ussd it happens to be missing the package.json file, so how do I create a package.json file for the already existing project. I can't tell which dependencies. npm init command creates the package.json file but with no dependencies. After I cloned the repo, npm start throwing error "Missing script start" Then I found package.json file was missing npm init was meant to create the file but packages were not in the file, neither were dependencies nor scripts. How do I addresse this issue Thanks -
Django ValueError: Cannot assign "<SimpleLazyObject: <CustomUser: >>": "Booking.user" must be a "Customer" instance
The objective is simple: I'm building a car rental platform where customers can place an order for a car. The simple 'order' contains the car, start, and end-dates. The form should automatically save the authenticated user as the creator. It uses a CreateView with this code: class BookingCreate(CreateView): model = Booking fields = ['car', 'start_date', 'end_date'] permission_classes = [permissions.IsAuthenticated] def form_valid(self, form): form.instance.user = self.request.user return super().form_valid(form) The form works fine, but when submitted, it raises this error: ValueError at /rentals/booking/create Cannot assign "<SimpleLazyObject: <CustomUser: Test2 Two>>": "Booking.user" must be a "Customer" instance. I've looked up previous answers, and the best solution came from this thread, which recommended using this code instead def form_valid(self, form): form.instance.user = Booking.objects.get(user=self.request.user) return super().form_valid(form) However, this change returns a slightly different error: ValueError at /rentals/booking/create Cannot query "Test2 Two": Must be "Customer" instance. I have a customUser Model and a "customer" model that inherits from it. For additional context, I am using a customUser model. Because I have multiple user types (in particular (car) Owners and Customers), I use a special table with boolean fields to mark each type as True based on the registration form they use per this this tutorial. Here's the … -
how to use `url` template tag in `with` template tag in django templates
i have html component that i want to include in my template that has a link as below <a href="{{url_name}}" ........ in my template i am trying to pass the url_name using the with tag {% include 'components/buttons/_add_button.html' with url_name="{% url 'equipments:equipment-add' %}" reference_name='equipment' %} this seems not to work as i get the following error Exception Type: TemplateSyntaxError Exception Value: Could not parse the remainder: '"{%' from '"{%' this works though using the hardcoded url works however i wanted to implement this using url names for flexibility {% include 'components/buttons/_add_button.html' with url_name="equipments/equipment/add" reference_name='equipment' %} urls.py app_name = "equipments" .... path("equipment/add/",views.EquipmentCreateView.as_view(), name="equipment-add", ), ... can i use a custom tag to pass this url name to my component template -
Django waitress- How to run it in Daemon Mode
I've a django application with python package waitress to serve it. But I want the django application to run in daemon mode is it possible? Any help regarding this would be great thanks in advance. Daemon mode - app running without command prompt visible also I'll be helpful to open shell without even closing the server. -
How to open and read file from media folder django
In my Django project, there is a media folder, all information about which is entered in the settings and added to the urls MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') and ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) in my view function I have a path to a file like - txt, I want to read the lines there and I'm trying to use the following code: route = "/media/" for i in files: route += i['file'] f = open(route, 'r') for line in f: print(line) but it gives me an error that the path is not found, I suspect that the path to this file needs to be specified differently, could you tell me how to do it correctly(in i['file'] i get the file name) -
How to add any security image in admin login page in django?
Unable to customize admin login template. Right now, I am using the django default login process. But I want to set the security image. So once the user enters the username, I will fetch the respective security image then after user can add a password.Can I customize the existing admin login template like this? -
How to store ManyToManyField field in String?
I created a Document model to store content for a Case model. A case model can have multiple Document objects. But I also have to store these Document objects in Case model for using them in filters. But when I want to see the converted_content in Django admin or print in the terminal or database it's stored as <memory at 0x13083c580>. How can I store them properly? models class Document(Model): file_path = models.CharField(max_length=250) converted_content = models.TextField() class Case(Model): documents = models.ManyToManyField(Document, blank=True, related_name='document') views def upload(self, request, pk): obj = get_object_or_404(Case, id=pk) content = "done" document = Document.objects.create(file_path=upload.file.url, converted_content=content) obj.documents.add(document) for checked_object in obj.documents.all(): print(checked_object.converted_content) // <memory at 0x13083c580> -
Testing messages when using RequestFactory()
I am testing a class based view using mock to raise an exception. On exception, a message should be created and then a redirect executed. Whilst I am able to test that the redirect has been executed, I am unable as yet to retrieve the message to be able to verify it. view CustomUser = get_user_model() class SignUpView(FormView): template_name = 'accounts/signup.html' form_class = SignUpForm def form_valid(self, form): try: self.user = CustomUser.objects.filter(email=form.cleaned_data['email']).first() if not self.user: self.user = CustomUser.objects.create_user(email=form.cleaned_data['email'], full_name=form.cleaned_data['full_name'], password=form.cleaned_data['password'], is_verified=False ) else: if self.user.is_verified: self.send_reminder() return super().form_valid(form) self.send_code() except: messages.error(self.request, _('Something went wrong, please try to register again')) return redirect(reverse('accounts:signup')) return super().form_valid(form) My test so far: class SignUpViewTest(TestCase): def setUp(self): self.factory = RequestFactory() def test_database_fail(self): with patch.object(CustomUserManager, 'create_user') as mock_method: mock_method.side_effect = Exception(ValueError) view = SignUpView.as_view() url = reverse('accounts:signup') data = {'email': 'test@test.com', 'full_name': 'Test Tester', 'password': 'Abnm1234'} request = self.factory.post(url, data) setattr(request, 'session', 'session') messages = FallbackStorage(request) request._messages = messages response = view(request) self.assertEqual(response.status_code, 302) self.assertEqual(response.url, '/accounts/signup/') My question is, how do I retrieve the message so that I can make an assertEqual against the message: 'Something went wrong, please try to register again'? -
Reactjs Display the the output after sending audio input from from django as backend
I am trying to work on music classification project.So I need your help which is when I send my music from frontend my music classification machine learning model classifies which music it is but how do i show my answer on is it pop/rap on front end using django as backend and react as frontend -
manage.py runserver python not found
I'm trying to learn django and I'm almost completely new to python, I'm using pycharm btw. My problem is that when i try to type python manage.py runserver in the terminal it just tells me that Python was not found. I have already tried to reinstall python and add it to system variables. -
Django for loop based on mobile/screensize
I have a Django product page with a for loop that displays items als follows: picture | info info | picture picture | info ... This is made by using an forloop.counter|divisibleby: loop. The layout looks great on desktop but super weird on mobile. Is there a way to prevent this loop from running if the screensize is smaller/mobile? Find my code below: {% for category in categories %} {% if forloop.counter|divisibleby:'2' %} <a href="{% url 'academy:brandByCat_list' category.category_name %}"> <div class="row py-3 item-display"> <div class="col-md item-text"> <h1 class='py-3'>{{category.category_name}}</h1> <p>{{category.category_info | linebreaks}} </div> <div class='col-md item-img'> <img src= {{category.category_picture.url}} class="img-fluid category-picture"> </div> </div> </a> {% else %} <a href="{% url 'academy:brandByCat_list' category.category_name %}"> <div class="row py-3 item-display"> <div class='col-md item-img'> <img src= {{category.category_picture.url}} class="img-fluid category-picture"> </div> <div class="col-md item-text"> <h1 class='py-3'>{{category.category_name}}</h1> <p>{{category.category_info | linebreaks}} </div> </div> </a> {% endif %} {% endfor %} -
Dash Django installation
I want to install django-plotly-dash and I was going step by step as in this installation guide https://django-plotly-dash.readthedocs.io/en/latest/installation.html, however when I do python manage.py migrate I get the following problem: ImportError: cannot import name 'InvalidCallbackReturnValue' from 'dash.exceptions' Did anyone else have the same problem when installing django-plotly-dash? -
How can I use a Django variable in my html img tag?
I need to use a variable for creation of a url for the img html tag. I use python - Django. Here's a hardcoded example of what I need: And here's what I tried (but failed): I want to use x.id variable (currently it equals 1), in my url. Something like this: What am I missing? -
Image doesn't appear in mobile browser, desktop works
I am making my first web app with vue. and having a problem with file system for mobile. front - vue + advanced cropper backend - django server - lightsail + apache2 storige - aws s3 When I upload files to s3 and try to use Advanced Cropper in vue to crop it, it loads and works well in desktop browser( chrome, safari...) But when I use it in mobile( chrome, safari...), it doens't appear in the browser. I have changed all attributes that what I know on my side and been spending a couple weeks to solve this problem. Is there anyone who had the same problem? Please give me some advice. enter image description here Thank you. -
No such file or directory in linux2
Trying to access my directory to run some python commands. From my logs when I run : container_commands: 00_sudo1: command: "source /var/app/venv/*/bin/activate && sudo pwd" 01_sudo2: command: "source /var/app/venv/*/bin/activate && ls -a" I get this : 2022-11-25 12:22:08,505 P10497 [INFO] Command 00_sudo1 2022-11-25 12:22:08,529 P10497 [INFO] -----------------------Command Output----------------------- 2022-11-25 12:22:08,529 P10497 [INFO] /var/app/staging 2022-11-25 12:22:08,529 P10497 [INFO] ------------------------------------------------------------ 2022-11-25 12:22:08,529 P10497 [INFO] Completed successfully. 2022-11-25 12:22:08,544 P10497 [INFO] ============================================================ 2022-11-25 12:22:08,544 P10497 [INFO] Command 01_sudo2 2022-11-25 12:22:08,549 P10497 [INFO] -----------------------Command Output----------------------- 2022-11-25 12:22:08,549 P10497 [INFO] . 2022-11-25 12:22:08,549 P10497 [INFO] .. 2022-11-25 12:22:08,549 P10497 [INFO] .gitignore 2022-11-25 12:22:08,549 P10497 [INFO] Procfile 2022-11-25 12:22:08,549 P10497 [INFO] backend 2022-11-25 12:22:08,550 P10497 [INFO] ------------------------------------------------------------ Now I have to run more commands inside my project folder but no idea how to access it, tried lots of different ways. This is what I want to run : 02_makemigrations: command: "source /var/app/venv/*/bin/activate && /backend/project/python3 manage.py makemigrations --noinput" 03_migrate: command: "source /var/app/venv/*/bin/activate && /backend/project/python3 manage.py migrate --noinput" 04_collectstatic: command: "source /var/app/venv/*/bin/activate && /backend/project/python3 manage.py collectstatic --noinput" But I get ERROR :/bin/sh: No such file or directory -
Related Field got invalid lookup: contains
I am trying to include a search field inside my home page. It works for some of the module field. My problem is when I use a ForeignKey field (correct me please if I am wrong). models.py class Training_Lead(models.Model): handel_by = models.ForeignKey(UserInstance, on_delete=models.PROTECT) learning_partner = models.ForeignKey( Learning_Partner, on_delete=models.PROTECT, blank=False, null=False) assign_to_trainer = models.ForeignKey( Trainer, on_delete=models.PROTECT, null=True, blank=True) course_name = models.CharField(max_length=2000) lead_type = models.CharField(max_length=2000) time_zone = models.CharField(choices=(('IST', 'IST'), ('GMT', 'GMT'), ('BST', 'BST'), ( 'CET', 'CET'), ('SAST', 'SAST'), ('EST', 'EST'), ('PST', 'PST'), ('MST', 'MST'), ('UTC', 'UTC')), max_length=40, blank=False, null=False) getting_lead_date = models.DateTimeField(null=True, blank=True) start_date = models.DateTimeField(null=True, blank=True) end_date = models.DateTimeField(null=True, blank=True) lead_status = models.CharField(choices=(('Initial', 'Initial'), ('In Progress', 'In Progress'), ('Follow Up', 'Follow Up'), ( 'Cancelled', 'Cancelled'), ('Confirmed', 'Confirmed'), ('PO Received', 'PO Received')), max_length=40, blank=False, null=False) lead_description = models.CharField(max_length=9000, blank=True, null=True) def __str__(self): return str(self.assign_to_trainer) class Meta: ordering = ['start_date'] views.py def report_for_trainer(request): if request.user.is_authenticated: user = UserInstance.objects.all() partner = Learning_Partner.objects.all() trainer_info = Trainer.objects.all() trainer = Training_Lead.objects.all() if request.method == "POST": start_date = request.POST.get("start_date") end_date = request.POST.get("end_date") lead_status = request.POST.get("lead_status", default="") assign_to_trainer = request.POST.get("assign_to_trainer") trainers_info = Training_Lead.objects.filter( start_date__gte=start_date, end_date__lte=end_date, lead_status__contains=lead_status, assign_to_trainer_id__contains=assign_to_trainer, ) trainer_info_not_active = Training_Lead.objects.exclude( start_date__gte=start_date, end_date__lte=end_date, lead_status__contains=lead_status, ) df = {"user": user, "partner": partner,"start_date": start_date,"end_date":end_date,"trainer":trainer,"lead_status":lead_status,"assign_to_trainer":assign_to_trainer, "lead_status": lead_status,"trainers_info": trainers_info, "trainer_info": trainer_info, "trainer_info_not_active": trainer_info_not_active} … -
Why is occur "Error 400: redirect_uri_mismatch"?
My goal is to implement google authentication in my Django website. But it shows, Access blocked: This app’s request is invalid You can’t sign in because this app sent an invalid request. You can try again later, or contact the developer about this issue. Learn more about this error If you are a developer of this app, see error details. Error 400: redirect_uri_mismatch Why did it occur? I tried to implement it in the local host. Give me an understandable solution so that as a beginner I can understand. The same Kinda issues occur for the facebook authentication too. google developer console: Authorized JavaScript origins: urls1:http://localhost:8000 urls2:http://127.0.0.1:8000 urls3:http://localhost:3000 urls4:http://localhost Authorized redirect URIs: urls1:http://127.0.0.1:8000/ urls2:http://localhost:8000 urls3:http://localhost:3000 urls4:http://localhost settings.py: MIDDLEWARE = [ 'social_django.middleware.SocialAuthExceptionMiddleware', ] context_processors: 'social_django.context_processors.backends', 'social_django.context_processors.login_redirect', AUTHENTICATION_BACKENDS = [ 'social_core.backends.google.GoogleOAuth2', 'django.contrib.auth.backends.ModelBackend', ] LOGIN_URL = '/' LOGIN_REDIRECT_URL = '/' LOGOUT_URL = '/' LOGOUT_REDIRECT_URL = '/' SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = '****' #security purpose I hide this SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = '****' #security purpose I hide this urls.py path('social-auth/', include('social_django.urls', namespace='social')) -
Django - problem with concat in F expression
I have a query that gives the number of matched options. I managed to use annotate with Count and F expressions however Django is dividing my products into matched filters on the page. What I want is to have a product that will contain the product title, the number of matched filters, and a list of matched filters. product_list = product_list.annotate(client_type_product_count=Count('client_type', filter=Q(client_type__title__in=client_type)), client_type_title=F('client_type__title')).exclude(client_type_product_count__exact=0).distinct() Right now a page with results looks like on the screenshot below. The first value is the name of the product, the second (numeric value) is the number of matched options (so how many checkboxes user selected and are matching to this product) and the third is the option(s) name: But what I want is this: How can I achieve something like this? -
Is there a way to save a query in django and use it later?
I have a service that prints the incoming data to excel. This service works exactly as follows. I'm building the query but not running it. I dump and save the query with the help of "pickle", load and use it again with pickle in the celery task. This has worked on all my models so far. But in the model below, the pickle gives an error. django version=3.2 The Money Field I used in the model is here. django-money==3.0.0 class PaymentStatus: WAIT = 1 SUCCESS = 2 FAIL = 3 CANCEL = 4 types = ( (WAIT, _('Waiting')), (SUCCESS, _('Success')), (FAIL, _('Fail')), (CANCEL, _('Cancel')) ) class PaymentModel(models.Model): class Meta: app_label = 'betik_app_payment' indexes = [ models.Index(fields=['dt', 'user_email']) ] provider = models.PositiveIntegerField(choices=PaymentProviderTypeEnum.types) is_test = models.BooleanField(default=True) payment_status = models.PositiveIntegerField(choices=PaymentStatus.types, default=PaymentStatus.WAIT) price = MoneyField(max_digits=20, decimal_places=2, help_text=_('amount paid excluding tax and discount')) paid_price = MoneyField(max_digits=20, decimal_places=2, help_text=_('amount paid including tax and discount')) dt = models.DateTimeField() user_email = models.EmailField(null=True, blank=True) token = models.CharField(max_length=255, null=True, blank=True, help_text=_('This token comes from the payment system. With this token, inquiries are made in the payment system')) locale = models.CharField(max_length=10, default="en") pickle error: _pickle.PicklingError: Can't pickle <function QuerySet.distinct at 0x7faf69912430>: it's not the same object as django.db.models.query.QuerySet.distinct qs=PaymentModel.objects.filter(dt__date__lte="2030-01-01") pickle.dumps(qs) #raise … -
If it possible to filter out names of objects returned in Django Admin
For my Django CMS Admin I would like to prevent it returning a specific object to the CMS. What is the best way to do this? I would like to do something like class MyModuleAdmin(admin.ModelAdmin): list_display = ['name'] list_filter = ('my_module__name__is_not=moduleidontwant',) -
Django Rest Framework : how to specify a serializer to use different fields to create, update and get
I have a doubt with the serializers and so far I have not been able to solve it. I explain the doubt with the following example: I have a User model and this model has the following attributes: username, password, first_name, last_name, age, gender. I also have a serializer, which is called UserSerializer. The UserSerializer should do the following: When inserting information into the database, UserSerializer should only take into account the fields: username, password, first_name, last_name. When retrieving information from the database, UserSerializer should only take into account the fields: age, gender. When updating the database information, UserSerializer should only take into account the fields: password. My solution: class UserSerializer: class UserCreateSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['username', 'password', 'first_name', 'last_name'] class UserGetSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['age', 'gender'] class UserUpdateSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['password'] Question: The question: is there any way to synthesize the three serializers into one, or what is the best solution for this problem? Thank you very much. -
javastript get input element by checkbox
I have a table with 2 columns: checkbox and quantity. <form action="{% url 'create-order' %}" method="POST"> {% csrf_token %} <table class="table table-responsive table-borderless"> <thead> <th>&nbsp;</th> <th>Quantity</th> </thead> <tbody> {% for item in items %} <tr class="align-middle alert border-bottom"> <td> <input type="checkbox" id="check" name="item" value="{{ item.id }}" onclick={changeQuantityState(this)}> </td> <td> <input class="input" min="1" value=1 type="number" name="quantity"> </td> </tr> {% endfor %} </tbody> </table> <div class="submitButton"> <button type="submit" class="lgbtn green">Go to order</button> </div> </form> I have a handler for the checkbox: if checkbox is checked, then I can select the quantity. Otherwise, the quantity disabled. function changeQuantityState(checkbox) { checkbox.addEventListener('change', function(event) { var quantity = document.getElementById('qnt'); if (event.currentTarget.checked) { quantity.disabled = false; quantity.value = 1; } else { quantity.disabled = true; quantity.value = 0; } }); } I need change this line: var quantity = document.getElementById('qnt'); because I need the quantity for the current row in the table, for the current checkbox, but this code line return first quantity. -
How to fix the timezone in django while filtering datas from database
views.py: def index(request): if request.method == "POST": from_date = request.POST.get("from_date") f_date = datetime.datetime.strptime(from_date, '%Y-%m-%d') print(f_date) to_date = request.POST.get("to_date") t_date = datetime.datetime.strptime(to_date, '%Y-%m-%d') print(t_date) global roles roles = Scrapper.objects.all() # for i in roles: # print(i.description) global find_description # find_description = Scrapper.objects.all().filter(created_at=f_date,updated_at=t_date) find_description = Scrapper.objects.all().filter(created_at=f_date,updated_at=t_date) print(find_description) models.py from django.db import models from django.db import connections from django.utils import timezone # Create your models here. class Scrapper(models.Model): id = models.IntegerField(primary_key=True) full_name = models.CharField(max_length=100) slug = models.CharField(max_length=100) description = models.TextField(max_length=100) created_at = models.DateTimeField(default=True) updated_at = models.DateTimeField(default=True) class Meta: db_table = "test_table_1" When I pass the data as filter to the database to get value there occurs error RuntimeWarning: DateTimeField Scrapper.created_at received a naive datetime (2022-11-09 00:00:00) while time zone support is active. My f_date= "2022-11-09 00:00:00" . Is there any solution for removing error -
Django celery results does not store task results
The problem speaks for itself - django-celery-results does not store any task results. I did everything as it was described in 'getting started' section in documentation, but still no results. I'm using django 4.1.2 and django-celery-results 2.4.0 Here is related variables from settings.py: CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.redis.RedisCache', 'LOCATION': 'redis://redis:6379', } } CELERY_BROKER_URL = os.environ.get("CELERY_BROKER", "redis://redis:6379") CELERY_RESULT_BACKEND = os.environ.get("CELERY_BACKEND", "django-db") CELERY_CACHE_BACKEND = "django-cache" CELERY_RESULT_EXTENDED = True I also tried database cache - nothing changed. How can I get this to work? -
django - Createview add error message when none of checkboxes is checked
I'm struggling with adding error message when none of checkboxes is selected in my template. Now in my CreateView I've got following code to get value of checkboxes: def form_valid(self,form): box1=form.cleaned_data['box1'] box2=form.cleaned_data['box2'] How to produce an error when user doesn't click any of them?