Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Heroku deploys app but can't serve it - ModuleNotFoundError: No module named 'django_app'
I'm trying to deploy an app via Digitalocean/Heroku which works for both the build and deployment. However, once I visit the successfully deployed site I get this: I already tried this without success. This is the full traceback: [cherry] [2022-08-17 13:43:20] [2022-08-17 13:43:20 +0000] [1] [INFO] Starting gunicorn 20.1.0 [cherry] [2022-08-17 13:43:20] [2022-08-17 13:43:20 +0000] [1] [INFO] Listening at: http://0.0.0.0:8080 (1) [cherry] [2022-08-17 13:43:20] [2022-08-17 13:43:20 +0000] [1] [INFO] Using worker: sync [cherry] [2022-08-17 13:43:20] [2022-08-17 13:43:20 +0000] [17] [INFO] Booting worker with pid: 17 [cherry] [2022-08-17 13:43:20] [2022-08-17 13:43:20 +0000] [17] [ERROR] Exception in worker process [cherry] [2022-08-17 13:43:20] Traceback (most recent call last): [cherry] [2022-08-17 13:43:20] File "/workspace/.heroku/python/lib/python3.8/site-packages/gunicorn/arbiter.py", line 589, in spawn_worker [cherry] [2022-08-17 13:43:20] worker.init_process() [cherry] [2022-08-17 13:43:20] File "/workspace/.heroku/python/lib/python3.8/site-packages/gunicorn/workers/base.py", line 134, in init_process [cherry] [2022-08-17 13:43:20] self.load_wsgi() [cherry] [2022-08-17 13:43:20] File "/workspace/.heroku/python/lib/python3.8/site-packages/gunicorn/workers/base.py", line 146, in load_wsgi [cherry] [2022-08-17 13:43:20] self.wsgi = self.app.wsgi() [cherry] [2022-08-17 13:43:20] File "/workspace/.heroku/python/lib/python3.8/site-packages/gunicorn/app/base.py", line 67, in wsgi [cherry] [2022-08-17 13:43:20] self.callable = self.load() [cherry] [2022-08-17 13:43:20] File "/workspace/.heroku/python/lib/python3.8/site-packages/gunicorn/app/wsgiapp.py", line 58, in load [cherry] [2022-08-17 13:43:20] return self.load_wsgiapp() [cherry] [2022-08-17 13:43:20] File "/workspace/.heroku/python/lib/python3.8/site-packages/gunicorn/app/wsgiapp.py", line 48, in load_wsgiapp [cherry] [2022-08-17 13:43:20] return util.import_app(self.app_uri) [cherry] [2022-08-17 13:43:20] File "/workspace/.heroku/python/lib/python3.8/site-packages/gunicorn/util.py", line 359, in import_app [cherry] [2022-08-17 … -
Issue with Datetime from database and Django
I'm trying to generate some basic chart data, but I cannot, yet anyways. Whenever I retrieve datetime values from Django models, it gives me this output: [print(i) for i in UserAnalyticsMeta.objects.all().values('created_at')[:3]] {'created_at': datetime.datetime(2022, 8, 15, 22, 43, 23, 88381, tzinfo=datetime.timezone.utc)} {'created_at': datetime.datetime(2022, 8, 15, 22, 48, 43, 944993, tzinfo=datetime.timezone.utc)} {'created_at': datetime.datetime(2022, 8, 15, 22, 48, 49, 95255, tzinfo=datetime.timezone.utc)} Which translates to: 2022-08-15 22:43:23.088381+00:00 2022-08-15 22:48:43.944993+00:00 2022-08-15 22:48:49.095255+00:00 However, when I try to print out the date, this is the output I get: [print(i) for i in UserAnalyticsMeta.objects.all().values('created_at__date')[:3]] {'created_at__date': None} {'created_at__date': None} {'created_at__date': None} While I expect: 2022-08-15 2022-08-15 2022-08-15 What I've also noticed is that an old function I used also doesn't work anymore, and I feel like it has something to do with this. select_data = {"date_created": """strftime('%%m/%%d/%%Y', created_at)"""} qs = self.extra(select=select_data).values('date_created').annotate(models.Sum("page_visits")) return qs Now gives me the error: OperationalError at /admin/app_name/model_name/ (1305, 'FUNCTION app_name.strftime does not exist') Any help would be appreciated! Thank you. -
Django: assigning employees to the hotel rooms and manage dates overlaping and intersection
Task: Imagine we are a company and we want to send our employees on different work trips. Amount of employees for each trip can vary. Also, we are booking hotel rooms for each trip. The room type and max amount of employees per room can be one of these: [{"type": "single", "max_persons": 1}, {"type": "double", "max_persons": 2}, {"type": "triple", "max_persons": 3}, {"type": "quad", "max_persons": 4}] Employees can split the room if room is double, triple or quad Also, employees can live only few days in a row and then next employee could take this room. The task is to get list of dates when room is completely free (no employees lives there) and list of dates when room is partly free (there are 1-3 free beds) Image with visual task explanation The Django models.py is: class Hotels(models.Model): """ Model to store all hotels """ name = models.CharField(max_length=255) phone = PhoneNumberField(blank=True) address = models.CharField(max_length=255, blank=True) city = models.CharField(max_length=255, blank=True) country = CountryField(blank=True) zip = models.CharField(max_length=255, blank=True) REQUIRED_FIELDS = ["name", "address", "city", "country"] def __str__(self) -> str: return self.name class Meta: ordering = ["name"] verbose_name = "Hotel" verbose_name_plural = "Hotels" class RoomTypes(models.Model): """ Model to store all room types """ type = … -
Django Model While User Login
Iam new in programming. I need to make a model/table in django where details of a User has to save. If the User login It will goes to registration page if he is not completed the registration, else if he already completed the registration it will goes to home page. What should I do? models.py class UserReg(models.Model): Name=models.CharField(max_length=200) Date_of_Birth=models.DateField() Age=models.IntegerField() Gender=models.CharField(max_length=200, choices=GenderChoice) Phone_no=models.IntegerField() Mail=models.EmailField(unique=True) Address=models.TextField(max_length=700) District=models.ForeignKey(District,on_delete=models.CASCADE) Branch=models.ForeignKey(Branch,on_delete=models.CASCADE) Account_Type=models.CharField(max_length=200,choices=AccType) Materials=models.ManyToManyField(Materials) views.py def reg(request): form = Userform() if request.method == 'POST': form=Userform(request.POST) if form.is_valid(): Name=request.POST.get('Name') Date_of_Birth = request.POST.get('Date_of_Birth') Age = request.POST.get('Age') Gender = request.POST.get('Gender') Phone_no = request.POST.get('Phone_no') Mail = request.POST.get('Mail') Address = request.POST.get('Address') District = request.POST.get('District') Branch = request.POST.get('Branch') Account_Type = request.POST.get('Account_Type') Materials = request.POST.get('Materials') obj=UserReg(Name=Name,Date_of_Birth=Date_of_Birth,Age=Age,Gender=Gender,Phone_no=Phone_no,Mail=Mail,Address=Address,District=District,Branch=Branch,Account_Type=Account_Type,Materials=Materials) obj.save() return redirect('/') return render(request,'registration.html',{'form':form,}) -
How to execute javascript code after htmx makes an ajax request?
Im currently building a website with django and htmx and i like the combination so far. Lets say I use an htmx attribute on a button to replace a div in the DOM with another div that is supposed to contain a wysiwyg editor. Now the wysiwyg editor has to be initialized with javascript. How do I do this? Can I just return the script tag under the editor div that is being requested with htmx? Wouldnt that be also a little ugly or bad practice because youd have script tags in the middle of the html body? Whats the best way of solving this? Thanks in advance -
How to save form to database only if its not already in the database in django
Here is the code and Im wondering how can I make it so it saves if the input from the form is unique and not already in the db. @login_required def settings(request): form = EmailInfoForm() if request.method == "POST": form = EmailInfoForm(request.POST) if form.is_valid(): form.save() context = {'form': form} return render(request, 'tasks/settings.html', context) -
Django sync to async
I have this json file below, I wrote a code to check weather a username exists in these sites or not using request library the problem is that it takes too much time and it returns this error. ('Connection aborted.', ConnectionResetError(10054, 'An existing connection was forcibly closed by the remote host', None, 10054, None)) So I have been trying to make it faster by using asyncio, unfortunately i wasn't able to convert this view to async as there were no tutorial demonstrated what i am trying to implement.I have read the django sync_to_async library docs too. { "BuyMeACoffee": { "errorType": "status_code", "url": "https://buymeacoff.ee/{}", "urlMain": "https://www.buymeacoffee.com/", "urlProbe": "https://www.buymeacoffee.com/{}", }, "BuzzFeed": { "errorType": "status_code", "url": "https://buzzfeed.com/{}", "urlMain": "https://buzzfeed.com/", }, "CNET": { "errorType": "status_code", "url": "https://www.cnet.com/profiles/{}/", "urlMain": "https://www.cnet.com/", }, .... } This the code synchronous code that i wrote: def create(request): form = SearchForm() if request.method == 'POST': name = request.POST['name'] with open('sites-data.json') as f: data = json.load(f) mod_data = json.loads(json.dumps(data).replace("{}",name)) search_term = SearchTerm( user = request.user, name = name ) search_term.save() for item in mod_data: if mod_data[item]['errorType'] == "status_code": url = mod_data[item]['url'] urlMain = mod_data[item]['urlMain'] response = requests.get(url) status_code = response.status_code if status_code == 200: site_data = SearchResult( term = search_term, url … -
Please I am looking for someone who is proficient in DJANGO to help me in authenticating multiple types of users [closed]
enter image description here Help me create multiple user types -
Django - Redirect Unauthenticated User trying to access UpdateView to DetailView
This is my last brain cell speaking. I have a model called Post with title, body, author, logo and pub_date fields. There is a page in my app that the user can Update/Edit the post. I want the user to be redirected to the Post's Detail page if they tried to access it without being logged in. The problem is that I can't reference the Post's pk to redirect the user to the related page, If I want to put it simply: the user trying to access .../2/edit/ will be redirected to .../2/ if they aren't logged in I Tried using LoginRequiredMixin to block the user but I can't redirect the user to the relative details page. urls.py: urlpatterns = [ path('', PostListView.as_view(), name='index'), path('<int:pk>/', PostDetailView.as_view(), name='details'), path('new/', PostCreateView.as_view(), name='new_post'), path('<int:pk>/edit', PostUpdateView.as_view(), name='update_post'), ] views.py: class PostUpdateView(LoginRequiredMixin, UpdateView): model = Post login_url = reverse_lazy('details', args=[self.object.pk,]) form_class = PostUpdateForm template_name = "posts/update_post.html" I also tried: class PostUpdateView(LoginRequiredMixin, UpdateView): def get_login_url(self) -> str: super().get_login_url() UpdateView.get(self, self.request) self.login_url = reverse_lazy('details', args=[self.object.pk,]) model = Post form_class = PostUpdateForm template_name = "posts/update_post.html" But it returns an empty/none value Is LoginRequiredMixin even the right way to do this? I know this can easily be achieved without … -
Pycharm doesn't see change in main.py when starting local server
I created a project, added main to it for the main page in views and about, there are no errors, but the text is not displayed [page screenshot][https://i.stack.imgur.com/gIO02.png] nothing changes at startup, but on the main page it writes [page screenshot][https://i.stack.imgur.com/TWUNg.png] maybe I'm missing something? setting[settings][https://i.stack.imgur.com/2hkmx.png] [urls][https://i.stack.imgur.com/Yy4oH.png] [page screenshot][https://i.stack.imgur.com/OJUEw.png] from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('main.urls')) ] setting.py # Application definition INSTALLED_APPS = [ 'main', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', -
Limit the choices of a choice field in the model class
This SO answer shows how to limit a choice field in the form. However, I have a choice field with options that should never be shown to the user. Hence, I want to limit the choice field options in the model class to adhere to the DRY principle and to prevent myself from forgetting to adding code in future forms. Any idea how to achieve this? -
how to declare a serializer field containing list of ids in django
Models: class Author(Base): name = models.CharField(max_length=100, unique=True) class Book(Base): name = models.CharField(max_length=100, unique=True) class AuthorBookAssn(Base): author = models.ForeignKey(Author, on_delete=models.PROTECT) book = models.ForeignKey(Book, on_delete=models.CASCADE) I have an api to create a book, and along with the book data we would also get a list of author ids how should the serializer field be created such that it is a list of ids. for example: [1, 2, 3] This field would not be present in any models we only need to use these fields to create records in the AuthorBookAssn table. -
Separate Django permissions per group per user's companies
I have a CustomUser model, each user could be linked to multiple companies. I have initiated my application with 3 generic Django groups; viewer, editor, and supervisor and each user could be a member in only one group. Permissions I have used some global Django permissions like the {app_label}.add_{class_name} permisison with the editor group for an instance. In parallel, I used also django-guardian to have some object-level permissions to get deeper with my objects' permissions as they vary depending on some of the object attributes' values. So, at the end of the day, each user (depending on his group) has some global permissions and some object-level permissions. It works fine that way with no problem so far. Problem As stated earlier, each user is linked to multiple companies. Additionally, each object in my database is linked to a specific company. So, I need to have a higher level of permissions so that each user can deal and interact ONLY with the objects that are linked to one of his companies weather he/she is a viewer, editor, or supervisor. Proposed solutions Those are the solutions that I thought about, but each one of them has some drawbacks and I don't prefer … -
Schema validation failed; XML does not comply with UBL 2.1 standards in line with ZATCA specifications
I am trying to use validate my xml with UBL 2.1 standards in line with ZATCA specifications. But I can't validate that as my xml looking great but I don't understand what's going wrong .I used python json2xml package for creating xml.This package generate xml from json. Erros list what I am getting from ZATCA XML Validator: category : XSD_SCHEMA_ERROR code :SAXParseException message : Schema validation failed; XML does not comply with UBL 2.1 standards in line with ZATCA specifications Here is my Xml code: <?xml version="1.0" ?> <Invoice> <ProfileID>reporting:1.0</ProfileID> <ID>INV004</ID> <UUID>fd5a7cc4-2316-49ee-ac07-6f4be4be3731</UUID> <IssueDate>2022-08-13</IssueDate> <IssueTime>23:46:07</IssueTime> <InvoiceTypeCode>388</InvoiceTypeCode> <InvoiceTypeCodeName>0101001</InvoiceTypeCodeName> <DocumentCurrencyCode>SAR</DocumentCurrencyCode> <TaxCurrencyCode>SAR</TaxCurrencyCode> <Note/> <OrderReference> <ID/> </OrderReference> <ContractDocumentReference> <ID/> </ContractDocumentReference> <AdditionalDocumentReference> <UUID>4</UUID> <PIH> <Attachment> <EmbeddedDocumentBinaryObject>ET05jV7roub7D66wOAQ49TQ8mCkyldhmH7B8CV3Rc6g=</EmbeddedDocumentBinaryObject> </Attachment> </PIH> <QR> <Attachment> <EmbeddedDocumentBinaryObject>5D6ZU7f6nb+s1szmMw46l4NZ7yTy0p1wi0ZUMsdQWBE=</EmbeddedDocumentBinaryObject> </Attachment> </QR> </AdditionalDocumentReference> <Signature> <ID>urn:oasis:names:specification: ubl:signature:Invoice</ID> <SignatureMethod>urn:oasis:names:specification:ubl:dsig:enveloped: xades</SignatureMethod> </Signature> <AccountingSupplierParty> <Party> <PartyLegalEntity> <RegistrationName>Altaf Miazee</RegistrationName> </PartyLegalEntity> <PartyIdentification> <ID/> </PartyIdentification> <PartyTaxScheme> <CompanyID>300600363600003</CompanyID> </PartyTaxScheme> <PostalAddress> <Country> <IdentificationCode>BD</IdentificationCode> </Country> <AdditionalStreetName>Altafbari</AdditionalStreetName> <StreetName>dhaka</StreetName> <BuildingNumber>1233</BuildingNumber> <PlotIdentification>1233</PlotIdentification> <CityName>Dhaka</CityName> <PostalZone>12302</PostalZone> <CountrySubentity>Dhaka</CountrySubentity> <CitySubdivisionName>miazee</CitySubdivisionName> </PostalAddress> </Party> </AccountingSupplierParty> <AccountingCustomerParty> <Party> <PartyLegalEntity> <RegistrationName>Hosen MD Altaf</RegistrationName> </PartyLegalEntity> <PartyIdentification> <ID>398765409876333</ID> </PartyIdentification> <PartyTaxScheme> <CompanyID>398765409876333</CompanyID> </PartyTaxScheme> <PostalAddress> <StreetName>الملك سلمان</StreetName> <AdditionalStreetName>الملك سلمان</AdditionalStreetName> <BuildingNumber>1234</BuildingNumber> <PlotIdentification>1234</PlotIdentification> <CityName>dhaka</CityName> <PostalZone>12234</PostalZone> <CountrySubentity>Dhaka</CountrySubentity> <CitySubdivisionName>الملك سلمان</CitySubdivisionName> <Country> <IdentificationCode>BD</IdentificationCode> </Country> </PostalAddress> </Party> </AccountingCustomerParty> <Delivery> <ActualDeliveryDate>2022-08-25</ActualDeliveryDate> <LatestDeliveryDate/> </Delivery> <PaymentMeans> <PaymentMeansCode>10</PaymentMeansCode> <PayeeFinancialAccount> <PaymentNote/> </PayeeFinancialAccount> </PaymentMeans> <AllowanceCharge> <TaxCategory> <ID>S</ID> <Percent>0.0</Percent> <TaxScheme> <ID>VAT</ID> </TaxScheme> </TaxCategory> … -
mutations with one to many relationship graphene_django
i want to add an internships to a specific cv using the id of the cv here is the modles class CV(models.Model): photo = models.ImageField(upload_to='CV/%Y/%m/%d/', null=True) headline = models.CharField(max_length=250) education = models.CharField(max_length=250) employment=models.CharField(max_length=250) class Internships(models.Model): employer=models.CharField(max_length=250) position=models.CharField(max_length=250) internship=models.ForeignKey(CV,on_delete=models.CASCADE) and here is the schema file class Internships(models.Model): employer=models.CharField(max_length=250) position=models.CharField(max_length=250) internship=models.ForeignKey(CV,on_delete=models.CASCADE) class createInternships(graphene.Mutation): class Arguments(): employer=graphene.String(required=True) position=graphene.String(required=True) internship=graphene.Int() internship=graphene.Field(InternshipsType) @staticmethod def mutate(root, info, employer,position): cv_object=CV.objects.get(id=id) internship=Internships.objects.create(employer=employer,position=position,internship=cv_object) return createInternships(internship=internship) and it will be appreciated if someone can also tell me the query i should type to create an internship related to the cv i have already created -
Prepopulate a choice field by a model
Im new to Django development and have a question regarding choice fields. I want to populate a choice field by a model: # function.py [1] ingredients = Ingredients.objects.all() [2] extras = Extras.objects.filter(pizza_id=pizza_id) [3] form = SelectIngredientsForm(extras,ingredients) # forms.py # Note its Form not ModelForm class SelectIngredientsForm(forms.Form): [4] ingredients = forms.ChoiceField(choices=X) [5] extras = forms.ChoiceField(choices=X) My Question is: How can I populate the choices in the Form ([4] and [5]) with the objects I have got previously [3] from object [1] and object [2]? -
Why empty value to instance?
I use django-autocomplete-light. I have a model: class MyModel(models.Model): name = models.CharField( 'MyName', max_length=200, ) city = models.CharField( 'City', max_length=200, ) In my admin: @admin.register(MyModel) class MyModelAdmin(admin.ModelAdmin): list_display = ( 'pk', 'name', ) form = MyModelForm class MyModelForm(forms.ModelForm): class Meta: model = MyModel exclude = [] widgets = auto_widgets_city auto_widgets_city = { 'city': autocomplete.ListSelect2( url='city-autocomplete', ), } In views: class CityAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): qs = City.objects.all() return qs It`s work, but if I save instance with city and when I go to admin/change, field city is empty. Why is it? -
POSTGRESQL - DJANGO - time without time zone en date
I'm working on a project's Django with a Postegresql database. I just created a model like that : from django.db import models from members.models import CustomUser class Article(models.Model): title = models.CharField(max_length=250) body = models.TextField() custom_user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True, blank=True, null=True) updated_at = models.DateTimeField(auto_now=True, blank=True, null=True) def __str__(self): return self.title class Meta: ordering = ["-created_at"] def save(self, *args, **kwargs): super().save(*args, **kwargs) When I try to migrate, I've this issue : ERREUR: can't convert type time without time zone en date In my DB, I've in my table "time without time zone". Do you have any ideas ? Thanks ! -
Django + Vue 403 Forbidden Error On axios.get
I'm trying to log the user but the Django rest API can't see the current jwt token of the logging user and I'm getting a 403 error. The API is working fine on the Postman with all the Authentication aspects. I have tried some advised solutions but they don't seem to work. Attempt 1 axios.defaults.headers.common["authorization"] = "Bearer " + localStorage.getItem("jwt"); await axios.get(api-link) Attempt 2 axios.defaults.xsrfHeaderName = "X-CSRFTOKEN"; axios.defaults.xsrfCookieName = "csrftoken"; axios.defaults.withCredentials = true; await axios.get(api-link) Attempt 3 await axios.get(api-link.{ { headers:{header stuff} }, {withCredentials: true} ) (Basically adding headers and credentials inside the get request.) Django settings.py I couldn't find a standard for this, currently I'm using this one for testing: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken', 'corsheaders', 'users', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ALLOW_ALL_ORIGINS = True CORS_ALLOW_CREDENTIALS = True CORS_ALLOWED_ORIGINS = ['http://127.0.0.1:8000', 'http://localhost:8000'] REST_FRAMEWORK = { 'DEFAULT_PARSER_CLASSES': [ 'rest_framework.parsers.JSONParser', ] } CSRF_COOKIE_NAME = "XSRF-TOKEN" -
Django environ returns -> Invalid line: SECRET_KEY = "..."
I recently included Django environ and it returns the following notification when starting the development server: Invalid line: SECRET_KEY = "django-insecure-9o9f18*-fk%9dh5s0$4xzt836m)*y!testestyf*z8$=j^uxks)k" All other environment variables work smoothly within my settings.py except for that notification (which doesn't seem to interrupt any processes yet). Any ideas? -
Cant find video downloaded with selenium on Heroku - Django
I have the following application I'm working on but I have an error that I can't figure out what I should do. The application is as follows the user adds a link to a video, the task is sent to celery via redis, celery downloads that video and saves it to media/AppVimeoApp/videos/.mp4, then displays it on a page with src="media\AppVimeoApp\videos....mp4". This app works fine locally, on heroku however the task shows me as successful but the video is nowhere to be found, I just need it temporarily. tasks.py @shared_task def download_video(): chrome_options = webdriver.ChromeOptions() chrome_options.binary_location = str(os.getenv('GOOGLE_CHROME_BIN')) chrome_options.add_argument("--headless") chrome_options.add_argument("--start-maximized") chrome_options.add_argument("--no-sandbox") chrome_options.add_argument("--disable-extensions") chrome_options.add_argument('--disable-dev-shm-usage') chrome_options.add_argument("--disable-gpu") chrome_options.add_argument('--disable-software-rasterizer') chrome_options.add_argument("user-agent=Mozilla/5.0 (Windows Phone 10.0; Android 4.2.1; Microsoft; Lumia 640 XL LTE) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Mobile Safari/537.36 Edge/12.10166") chrome_options.add_argument("--disable-notifications") chrome_options.add_argument('--window-size=1920,1080') chrome_options.add_experimental_option("prefs", { "download.default_directory": f"{settings.MEDIA_ROOT}\\AppVimeoApp\\videos", "download.prompt_for_download": False, "download.directory_upgrade": True, "safebrowsing_for_trusted_sources_enabled": False, "safebrowsing.enabled": False } ) driver = webdriver.Chrome(executable_path=str(os.getenv('CHROMEDRIVER_PATH')), chrome_options=chrome_options) driver.get('videolink') time.sleep(5) while True: try: driver.find_element(by=By.XPATH, value='/html/body/div[2]/div[1]/div[6]/div[2]/div[1]/a').click() break except: time.sleep(1) continue time.sleep(5) return ("Downloaded") I am very grateful if you can help me. Thank you. -
django signals - reverse lookup
I have 2 models Product and ProductComponent. What I am trying to do is to copy the user's id from Product model to all components that are related to this product in ProductComponent model. Let's say that we have a user with id=1. We also have a product with id=3 that contains 3 components. Right now when a user adds a product to the cart it adds the user only to the Product model. What I want is to add user to ProductComponent automatically so if user adds a product to the cart then it will add the user's id to all components that are related to this product in the ProductComponent model. In SQL what should happen when user adds product to cart is something like this: product_id user_id 3 1 productcomponent_id user_id 1 1 2 1 3 1 For now, I need to manually add each component even if I added product to cart. I want to automate it so adding product to cart will be also adding users's id to all components related to this product. I tried to use post_save and m2m_changed but I am not sure how to copy user's id from Product model to … -
django.db.utils.NotSupportedError: Oracle 19 or later is required (found 12.2.0.1.0)
'''note: I installed oracle instance for windows ''' with connections['trdb'].cursor() as cursor: cursor.execute(sql) row = cursor.fetchall() col = cursor.description cursor.close -
problem with service worker accessing django admin when serving react as main url
Im encountering an odd problem. I serve react as main url("/") of my django backend. When Im trying to access django admin in "/admin/" it will interrupt by service worker and it is trying to route with react-router-dom instead of routing with django urls. When i unregister service worker or hard refresh it fixes my problem. Im really confused. thanks for your help in advance. my django main urls: urlpatterns = [ path('admin/', admin.site.urls), ... path('', TemplateView.as_view(template_name='index.html')), path("<str:public_url>", views.public, name="public") ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns.append(path('<path:route>', TemplateView.as_view(template_name='index.html'))) Im using BrowserRouter and default Service Worker of create-react-app. -
how to sort object in django
def bubble_sort(nts): nts_len = len(nts) for i in range(nts_len): for p in range(nts_len - i - 1): if nts[p] < nts[p+1]: t = nts[p] nts[p]= nts[p+1] nts[p+1] = t return nts def menu(request): products = Product.objects.all() if request.method == "POST": s = request.POST['select'] if s == 'Price: Low to High': element = [] for var in products: element.append(var) list_items = list(element) bb = bubble_sort(list_items) el = list(bb) print(el) pro = Product.objects.filter(id__in=bb) print(pro) products = bb # print(products) How to retrieve data from database in bubble sort for objects?TypeError: '<' not supported between instances of 'Product' and 'Product'