Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to delete row when use Django only templates
I tried several options but to no avail. How can I get the job done if I only use templates? I want to delete the selected record with a button. I also have an add button in the html, after the add button it shows me the base again. All entries come with a delete button, but I can't get the job done. urls.py: urlpatterns = [ path("", views.index, name='index'), path("all_flat", views.all_flat, name='all_flat'), path("contact", views.contact, name='contact'), path("about", views.about, name='about'), path("save", views.testing, name='save'), #path("save/<int:pk>", views.delete, name='delete'), ] views.py: @api_view(['GET', 'POST']) def testing(request): mydata = models.FlatModelSqlite.objects.all() serializer_class = serializers.FlatSerializerSqlite(mydata, many=True) if request.method == "GET": html_save = "MyHome/save.html" template = loader.get_template(html_save) context = { 'mymembers': serializer_class.data, 'flatP': ForecastField_all(), } return HttpResponse(template.render(context, request)) elif request.method == "POST": item_serializer = serializers.FlatSerializerSqlite(data=request.data) if item_serializer.is_valid(): item_serializer.save() return HttpResponseRedirect(redirect_to='save') else: er = item_serializer.errors html_save = "MyHome/save.html" template = loader.get_template(html_save) context = { 'mymembers': serializer_class.data, 'flatP': ForecastField_all(), 'errors': er, } return HttpResponse(template.render(context, request)) #@api_view(['GET', 'POST']) #def delete(request, pk): # if request.method == 'POST': # flat_delete = models.FlatModelSqlite.objects.get(pk=pk) # flat_delete.delete() # return HttpResponse(redirect_to='save') html /save: {% for x in mymembers %} <tr> <td>{{ x.id }}</td> <td>{{ x.Address_N }}</td> <td>{{ x.Project_N }}</td> <td>{{ x.Fasi }}</td> <td>{{ x.Status }}</td> <td> <form method="post"> … -
ERROR An error occurred (AccessDenied) when calling the DeleteObject operation: Access Denied
Deleting Object from s3 cause Access Denied Error my s3 IAM { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "s3:*", "s3-object-lambda:*" ], "Resource": "*" } ] } settings.py INSTALLED_APPS = [ 'storages', ] DEFAULT_FILE_STORAGE = "storages.backends.s3boto3.S3Boto3Storage" django code def UpdateCompanyView(request): user = request.user company = user.company old_logo = company.logo if old_logo and 'logo' in serializer.validated_data and data_logo is not None: old_logo.delete() #old_logo.delete(save=False)#I've tried this also other all actions working put, add, but deleting occurring this error -
Issue when trying to connect to mssql using Django
I'm trying to connect my mssql to my Django project. I've tried using pyodbc outside of the project and that works. But when i'll try to connect inside the project it doesn't work.. I have tried "mssql-django" and "pyodbc-django". The error i get is: [Microsoft][ODBC SQL Server Driver]Invalid connection string attribute (0)') At the driver string i have also tried, "ODBC Driver 17 for SQL Server". DATABASES = { "default": { "ENGINE": "mssql", "NAME": "####", "USER": "####", "PASSWORD": "####", "HOST": "####", "PORT": "", "OPTIONS": {"driver": "SQL Server", ## "ODBC Driver 17 for SQL Server" }, }, } -
Static files deploy on Render
How to deploy python-django static files in cloud like render I've deployed the webapp but i'm not able to get my static files I've also used the command python manage.py collectstatic -
Why can’t I log in using the token contained in the cookie on mobile?
The front end uses React and the back end uses Django, each communicates with a server with a different domain in AWS, and the login functions work well on the web Currently, my functions only work when I am logged in, but when I move to another page, the token contained in the cookie disappears and the login expires Of course, the login expiration setting is set so that it expires when the refreshtoken expires. The current problem is that it works well on the web, but when I log in through mobile, the server sends me a refresh token in the header, but maybe it doesn't recognize it, or the login expires right away when I move to another page The logic is to put only the refresh token in the header as httponly, set samesite=none and secure, and receive the access token as a response upon logging in, store it in a local cookie, and reissue it by refreshing the header every time it expires Why does the token disappear when changing pages only on mobile devices? I'm not sure if it's a problem with the token settings coming from the header, or if the problem is that … -
Django db rollback specific commits
I have a django model called User I have a method that takes a list of different user updates like this [user1_payload, user2_payload, user3_payload,...,user100_payload] Some updates can fail in the database. There is another third party api which takes a list of user updates and perform the update action on their end. I would like to take only the successful updates in the database and call the third party api. Keep in mind that the third party api can also have some failed update operations and will return a response like this: { "successful_users": [1, 3, 5,...], "failed_users": [2, 4,...] } In case of the failed users in the third party api, i want to rollback those updates in my db. How can I achieve this using minimum number of db transactions and minimum number of api calls using django? -
RuntimeError Failed to lock Pipfile.lock
im a beginner on learning Django. That too on my new Mac. while I was install mysqlclient for my project using this command pipenv install mysqlclient I get this error saying RuntimeError: Failed to lock Pipfile.lock! how can I fix this? demo) chandanm@Chandans-MacBook-Air demo % pipenv install mysqlclient Courtesy Notice: Pipenv found itself running within a virtual environment, so it will automatically use that environment, instead of creating its own for any project. You can set PIPENV_IGNORE_VIRTUALENVS=1 to force pipenv to ignore that environment and create its own instead. You can set PIPENV_VERBOSITY=-1 to suppress this warning. Installing mysqlclient... Resolving mysqlclient... Added mysqlclient to Pipfile's [packages] ... ✔ Installation Succeeded Pipfile.lock (e35515) out of date, updating to (537503)... Locking [packages] dependencies... Building requirements... Resolving dependencies... ✘ Locking Failed! ⠴ Locking...False ERROR:pip.subprocessor:Getting requirements to build wheel exited with 1 [ResolutionFailure]: File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/pipenv/resolver.py", line 645, in _main [ResolutionFailure]: resolve_packages( [ResolutionFailure]: File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/pipenv/resolver.py", line 612, in resolve_packages [ResolutionFailure]: results, resolver = resolve( [ResolutionFailure]: ^^^^^^^^ [ResolutionFailure]: File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/pipenv/resolver.py", line 592, in resolve [ResolutionFailure]: return resolve_deps( [ResolutionFailure]: ^^^^^^^^^^^^^ [ResolutionFailure]: File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/pipenv/utils/resolver.py", line 908, in resolve_deps [ResolutionFailure]: results, hashes, internal_resolver = actually_resolve_deps( [ResolutionFailure]: ^^^^^^^^^^^^^^^^^^^^^^ [ResolutionFailure]: File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/pipenv/utils/resolver.py", line 681, in actually_resolve_deps [ResolutionFailure]: resolver.resolve() [ResolutionFailure]: File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/pipenv/utils/resolver.py", … -
Django deployment failure
I'm in the process of trying to deploy a Django project, and I'm running into difficulties getting it on the web. Let me run through the issues I'm having at the moment: I SSH into a remote server and am trying to deploy the project there. I don't currently have a domain name, so right now I'm using the IP address. I have set up both Gunicorn and Nginx and have them running, but when I go to the browser and try to access the site via 'https://...', I get the following error: Request Method: GET Request URL: http://**.**.***.***/ Using the URLconf defined in apegd_ai_core.urls, Django tried these URL patterns, in this order: admin/ The empty path didn’t match any of these. You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. I have a Gunicorn .service file under '/etc/systemd/system' called 'apegd_ai.service'. The configuration is as follows: [Unit] Description=Gunicorn instance to serve application After=network.target [Service] User=john Group=john WorkingDirectory=/home/john/graph_django/apegd_ai_core ExecStart=/home/bobby/Documents/graph_project/vDect2/bin/gunicorn -w 4 -b 0.0.0.0:8007 --error-logfile /home/john/gra> Environment="DJANGO_SECRET_KEY=encrptedsecretkey" [Install] WantedBy=multi-user.target I have an Nginx configuration file called apegd_ai.conf under /etc/nginx/sites-enabled, which looks like this: server … -
How can I add Svelte to my docker container with Django?
I have managed to create a docker and get running a django project. This is the Dockerfile FROM python:3.12-slim-bullseye ENV PYTHONUNBUFFERED 1 COPY ./requirements.txt /requirements.txt RUN pip install -r /requirements.txt RUN mkdir /app WORKDIR /app COPY ./app /app RUN adduser --disabled-login user USER user and this is the dockercompose version: "3.9" services: db: image: postgres volumes: - ./data/db:/var/lib/postgresql/data environment: - POSTGRES_DB=XXXXX - POSTGRES_USER=XXX - POSTGRES_PASSWORD=XXX app: build: context: . command: > sh -c "python manage.py collectstatic --noinput && python manage.py migrate && python manage.py runserver 0.0.0.0:XXXX" volumes: - ./app:/app ports: - "XXXXX" environment: - POSTGRES_NAME=XXXXX - POSTGRES_USER=XXXXXX - POSTGRES_PASSWORD=XXXXX depends_on: - db What do I need to modify to be able to add Svelte in the same docker? And what if I wanted to add SvelteKit? I saw something about multistage builds but I don't fully understand it -
"django.db.utils.ProgrammingError: relation does not exist" In production
I've been working on a feature for the past couple of months that hinges on a new one-to-many relation called "user_company". While in the development environment, I only had to migrate once the company model was created and haven't had any problems with it since but I haven't been able to update the production environment due to a "Django.db.utils.ProgrammingError: relation "app_company" does not exist" error. This throws the docker into a loop of "You can't run the app since it won't compile" and "I can't migrate the tables since the app ain't running" what can I do to either circumvent the error and migrate the table before it fails or ignore the table long enough for it to compile? Currently the user.company attribute looks like this: ... company = models.ForeignKey( Company, verbose_name=_("Company"), help_text=_("Company name where the user works at"), default=Company.get_default(), on_delete=models.CASCADE ) ... while the company model looks like this: class Company(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=100) description = models.TextField(max_length=500) file = models.FileField(blank=True, null=True, upload_to=partial( storage.upload_location, path="pidenomina"), validators=[file.FileValidator(allowed_extensions=['csv'], max_size=5242880)], verbose_name='File') # TODO - Created at def __str__(self): return self.name def get_default(): try: return Company.objects.first().pk except Company.DoesNotExist: company = Company.objects.create(id=1, name="Void", description="") company.save() return company Any help is appreciated, cheers. -
Cookiecutter Django Docker Hot Reloading Not Detecting Changes
I have recently created a new Docker project using cookiecutter-django. I've done this before and "hot reloading" has worked, however for some reason changes are not being detected properly in this project. The docs start to reload, and then detect no changes, as shown in the image below. Does anyone know why this is, or how to fix it? Thanks for any help anyone can offer! -
How can Django QuerySet filters modify the fields for comparison? (Like inet6_aton for IP addresses.)
Take this MySQL database for example, which stores IP addresses as strings in either IPv4 or IPv6 format. name | ip ------+--------------------------------------- Tony | 127.0.0.1 Jones | 2001:db8:3333:4444:5555:6666:7777:8888 This is the equivalent SQL I need to run, where VALUE is the variable determined by the website's user and already converted to a numeric value for comparison: select name from customers where name like 'J%' and hex(inet6_aton(ip)) > VALUE; Here is my filter, which would work if the ip field was already the numeric equivalent instead of a string: filter = Q(name__startswith="J") filter &= Q(ip__gt=VALUE) Alas, the ip values in the database are only stored as strings. (This is not my decision, and I cannot change it.) I need to perform the hex and inet6_aton functions on the fields in the database. How can I achieve this? Note: This is a very simplified version of what I am working with. These filters will apply to multiple searches across dozens of tables per search. I fear I may need to rework much of the established code to get this to work. -
How to get current user categories in ModelForm?
There is word study app. Currecnt user create own category with set of words. The idea is to customize the list of options in the selection form for the current user. models.py class ModelWords(models.Model): class Meta: verbose_name = 'Words' verbose_name_plural = 'Words' your_language_name = models.CharField(max_length=40) eng_name = models.CharField(max_length=40) cat = models.ForeignKey('ModelCatsWords', on_delete=models.CASCADE, null=True) author = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) def __str__(self): return self.your_language_name class ModelCatsWords(models.Model): class Meta: verbose_name = 'Categories' verbose_name_plural = 'Categories' name = models.CharField(max_length=100, db_index=True) author = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) def __str__(self): return self.name def get_absolute_url(self): return reverse('category', kwargs={'cat_id': self.pk}) There is two forms. The first form to add words to it and there is a list of user categories to choose, another form to add categories. forms.py class WordsFrom(forms.ModelForm): cat = forms.ChoiceField(choices=[], required=False, label="select cat") def __init__(self, *args, **kwargs): self.request = kwargs.pop('request', None) super(WordsFrom, self).__init__(*args, **kwargs) self.fields['cat'].choices = ModelCatsWords.objects.filter(author=self.request.user.id).values_list('name') for visible in self.visible_fields(): visible.field.widget.attrs['placeholder'] = visible.field.label class Meta: model = ModelWords fields = ['your_language_name', 'eng_name','cat'] labels = { 'your_language_name' : 'word on your language', 'eng_name' : 'word on english', 'cat' : 'categorie' } class ModelCatsWordsForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['name'].widget.attrs['placeholder'] = 'categorie' class Meta: model = ModelCatsWords fields = ['name'] labels = { 'name': 'Categorie' } There is views.py class … -
Django: can't load images but static files OK
I'm learning Django, and I've spent a week+ trying to display images in my app. I think that there's an issue with my settings but I'm perplexed since the static files are loading, though the images with similar settings are not. What confuses me so much is that my static files are loaded ok at MEDIA_ROOT/static, but that image files aren't found at MEDIA_ROOT/media. Based on settings.py, static seems like it would live at # C:\Users\...\final\static but it's clear that this isn't true. structure ├── final │ ├── dogtracks │ │ ├── static | │ │ ├── dogtracks │ ├── media | │ ├── images settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') ... MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') # C:\Users\...\final\media models.py class Animal(models.Model): ... photo = models.ImageField(upload_to='images', null=True, blank=True) ... class AnimalForm(ModelForm): class Meta: model = Animal fields = ['name', 'breed', 'species', 'birthday', 'photo'] html {% if pet.photo %} <img src="final{{ pet.photo.url }}" /> {% else %} <img src="{% static 'dogtracks/noun-pet.png' %}" /> {% endif %} I've read dozens of answers here on SO and gone through tutorials online. I've moved the location of my images folder to try to show these images. -
Python requests script with proxies does not work in Docker container on Windows
I have Docker installed on both Windows and Linux, and I have a dockerized Django app running on both operating systems. When I execute this script in the Django shell on Linux, it correctly returns the IP of the proxy server, as expected. However, when I run the same script on Windows, it returns my external IP address instead. import requests request = requests.get(url='https://httpbin.org/ip', proxies={ 'http': proxy_url, 'https': proxy_url, 'socks5': proxy_url }) print(request.text) Has anyone encountered a similar issue? -
Django ManifestFileStorage STATIC_ROOT misconfigured
I recently upgraded my project from Django 2.2.28 to 3.2 and am using Django-storage 1.14.2. As part of the upgrade, I replaced CachedFileMixin with ManifestFileStorage. Before the upgrade, everything was functioning correctly, and I haven't altered any other settings. However, I've run into an issue where self.location seems to cache a None value and it doesn't change. I found a temporary workaround by deleting the cache, which resolves the problem. Has anyone else experienced this or have any ideas on why this is happening? Code Snippet: class StaticFilesStorage(ManifestStaticFilesStorage, S3Boto3Storage): def __init__(self, *args, **kwargs): S3Boto3Storage.__init__(self, bucket_name=settings.STATIC_FILES_BUCKET, custom_domain=domain(settings.STATIC_URL), *args, **kwargs) ManifestStaticFilesStorage.__init__(self, *args, **kwargs) Error Message: Error output PDB Output: PDB output in ManifestStaticFilesStorage initializing After refreshing the cached value manually the error is resolved -
Django prefetch_related with multiple filters
Lets say this is my hypothetical codebase: class Address(models.Model): country = CountryField() ... class Location(models.Model): address = models.ForeignKey(Address, on_delete=models.CASCADE) class Zoo(models.Model): location = models.ForeignKey(Location, on_delete=models.CASCADE, related_name="zoos") class Animal(models.Model): name = CharField(max_length=200) animal_type = CharField(max_length=200) zoo = models.ForeignKey(Zoo, on_delete=models.CASCADE, related_name="animals") def animals_of_type_at_zoo(animal_type, zoo): return zoo.animals.filter(animal_type=animal_type) def generate_report(): report_data = {} animal_types = ["lion", "tiger", "bear", ...etc] locations = Location.objects.all() locations = locations.prefetch_related("zoos", "zoos__animals") for loc in locations.all(): for zoo in locations.zoos.all(): for animal in animal_types: report_data[loc.address.country][animal] += animals_of_type_at_zoo(animal, zoo).count() return report_data My goal is to make generate_report faster using prefetching. In this case I have added locations.prefetch_related("zoos", "zoos__animals"). However, since animals_of_type_at_zoo uses a filter, it triggers another query. My thought process was to prefetch each filter: locations = locations.prefetch_related("zoos", "zoos__animals") for animal in animal_types: locations = locations.prefetch_related(Prefetch("zoos_animals", queryset=Animals.objects.filter(animal_type=animal)) However zoos_animals can only be assigned once, I can't create multiple filters for this. My goal here is to prefetch everything needed with minimal impact to the animals_of_type_at_zoo function as it is used in other parts of the codebase and I want to minimize impact on the rest of the application (testing and performance). I had attempted to create custom object that override filter and would return the correct prefetch, but wasn't getting … -
RuntimeError: Failed to lock Pipfile.lock
I tried to install mysqlclient using the command Pipenv install mysqlclient. I get this error: RuntimeError: Failed to lock Pipfile.lock!. What does this mean, and how can I fix it? -
django-nose nose-py3 unit test shows the string None in the output even when successful
I have installed: django-nose==1.4.7 nose-py3==1.6.3 pinocchio==0.4.3 added django_nose to the INSTALLED_APPS added the lines: TEST_RUNNER = 'django_nose.NoseTestSuiteRunner' NOSE_ARGS = ['--with-spec', '--spec-color'] to the settings.py file in django created the following unit tests: def test_run_creation(self): """Test if the creation of runs creates instances of the Run model.""" self.assertIsInstance(self.run1, Run) self.assertIsInstance(self.run2, Run) self.assertIsInstance(self.run3, Run) def test_run_number_consistency(self): """Test if the number of runs in the project increases by 1 after run creation.""" self.assertEqual(self.final_no_of_runs_in_project, self.initial_no_of_runs_in_project + 1) the test run successfully and produce the following output: nosetests --with-spec --spec-color --with-xunit --verbosity=1 Creating test database for alias 'default'... None - Test if the creation of runs creates instances of the Run model. None - Test if the number of runs in the project increases by 1 after run creation. ---------------------------------------------------------------------- Ran 2 tests in 0.046s OK Destroying test database for alias 'default'... I would like to replace the String None in the output with something more descriptive but i have no idea what generate that text. Can anyone please help? Thank you -
I'm getting a "Connection unexpectedly closed" whenever I try to send an email with django hosted with Cloud Run. How do I diagnose this?
In my settings.py: EMAIL_BACKEND = django.core.mail.backends.smtp.EmailBackend EMAIL_HOST = smtp-relay.gmail.com EMAIL_HOST_USER = env('EMAIL_HOST_USER') EMAIL_HOST_PASSWORD = env('EMAIL_HOST_PASSWORD') EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_USE_SSL = False the line that actually sends the mail in one of the api end points is send_mail(subject, body, email_from, recipient_list) I can confirm with logs that the user and password is correct. I also can confirm that this works locally when I run it on my local environment. The issue is when I deploy this via Google Cloud Run I'm just getting Connection unexpectedly closed with no stacktrace and no information. From the Networking tab in cloud run I have allowed all ingress and have not set up any VPC network so I don't think it's that, however because of the nature of containerizing my app I don't know what else it could really be. What else would you try to diagnose and search? -
I have a django app running on a cpanel's subdomain. The challenge I am experiencing is I have ajax buttons that are not returning data
This is in my views.py ` def minuscreditcart(request): if request.method == 'GET': product_id = request.GET['prod_id'] print(product_id) print("GET MINUS {}", product_id) c = CreditCart.objects.get(Q(ordered=False) & Q(product=product_id) & Q(customer=Customer.objects.get(user_account=request.user))) if c.quantity <=1: pass else: c.quantity -= 1 c.save() cart = CreditCart.objects.filter(Q(customer=Customer.objects.get(user_account=request.user)) & Q(ordered=False)) creditApp = Credit_Facility_Application.objects.get(Q(disclaimer=False) &Q(customer=Customer.objects.get(user_account=request.user))) instal = Instalment.objects.get(application_form=creditApp) amount = 0 period = instal.period deposit = instal.deposit period = int(period) customer = Customer.objects.get(user_account=request.user) try: employment = Employment_detail.objects.get(customer=customer) employmentInfo = EmploymentForm(instance=employment) net_salary = employment.net_salary credit_limit = net_salary * 0.25 creditlimit = credit_limit except: credit_limit = False employmentInfo = EmploymentForm() admincharge = 0.03 ; mothlycharge = 0.08; ssbcharge = 0.05; for p in cart: value = p.quantity * p.product.discount_price amount = amount + value totalamount = amount balance = (1 + admincharge) * totalamount; depositlimit = int(balance * 0.3); balance = balance - deposit; totalmonthlycharges = mothlycharge * period; aftermonthlycharges = (1 + totalmonthlycharges) * balance; totalamount = ((1 + ssbcharge) * aftermonthlycharges) instalment = (totalamount / period) myinstalment = round(instalment, 2) data = { 'quantity':c.quantity, 'amount':amount, 'totalamount':totalamount, 'myinstalment':myinstalment, 'period':period, 'depositlimit':depositlimit, } return JsonResponse(data) This is the respective ajax code $('.minus-credit-cart').click(function(){ var id=$(this).attr("pid").toString(); var eml=this.parentNode.children[2]; $.ajax({ type:"GET", url:"/minus-credit-cart", data:{ prod_id:id }, success:function(data){ eml.innerText=data.quantity document.getElementById("amount").innerText=data.amount; document.getElementById("totalamount").innerText=data.myinstalment; document.getElementById("period").innerText=data.period; document.getElementById("depositamount").innerText = data.depositlimit; document.getElementById("depo").innerText = "Deposit … -
save() prohibited to prevent data loss due to unsaved related object 'classes'
Hello Help me please When I register the information, the first form saves the information, but when I register the second information, it gives an error and does not save the information. views.py class ClassesInline(): form_class = ClassesForm model = Classes template_name = "classes/classes_create_or_update.html" def form_valid(self, form): named_formsets = self.get_named_formsets() if not all((x.is_valid() for x in named_formsets.values())): return self.render_to_response(self.get_context_data(form=form)) kelas = form.save(commit=False) kelas.term = self.request.user.term kelas.branch = self.request.user.branch kelas.personnel_create = self.request.user self.object = kelas.save() for name, formset in named_formsets.items(): formset_save_func = getattr(self, 'formset_{0}_valid'.format(name), None) if formset_save_func is not None: formset_save_func(formset) else: formset.save() return redirect('kelas:classes_index') def formset_variants_valid(self, formset): reservs = formset.save(commit=False) # self.save_formset(formset, contact) # add this, if you have can_delete=True parameter set in inlineformset_factory func for obj in formset.deleted_objects: obj.delete() for reserv in reservs: reserv.classes = self.object reserv.save() class classesCreate(ClassesInline, CreateView): def get_form_kwargs(self): kwargs = super().get_form_kwargs() kwargs['request'] = self.request return kwargs def get_context_data(self, **kwargs): ctx = super(classesCreate, self).get_context_data(**kwargs) ctx['named_formsets'] = self.get_named_formsets() return ctx def get_named_formsets(self): if self.request.method == "GET": return { 'reservs': ReservationFormSet(prefix='reservs'), } else: return { 'reservs': ReservationFormSet(self.request.POST or None, prefix='reservs'), } The error that is observed and its reason -
AttributeError: Can't get attribute 'tokenizer' on <module '__main__'
I am trying to use y machine learning model in my Django but I have been getting so many error, and this is my first time of doing something like this. I need help the following is my view code # BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)) nltk.download('punkt') logger = logging.getLogger(__name__) # Load your AI model current_directory = os.path.dirname(os.path.abspath(__file__)) model_file_path = os.path.join(current_directory, 'ml_model/phishing_url_model.joblib') tfidf_vectorizer_path = os.path.join(current_directory, 'ml_model/tfidf_vectorizer.joblib') # tfidf_vectorizer = joblib.load(tfidf_vectorizer_path) # model = joblib.load(model_file_path) class UnregisteredScanCreate(generics.CreateAPIView): serializer_class = UnregisteredScanSerializer def tokenizer(self, url): # Your tokenizer code here """Separates feature words from the raw data Keyword arguments: url ---- The full URL :Returns -- The tokenized words; returned as a list """ tokens = re.split('[/-]', url) for i in tokens: if i.find(".") >= 0: dot_split = i.split('.') if "com" in dot_split: dot_split.remove("com") if "www" in dot_split: dot_split.remove("www") tokens += dot_split return tokens def create(self, request, *args, **kwargs): try: # Load the trained TF-IDF vectorizer tfidf_vectorizer = joblib.load(tfidf_vectorizer_path) # Load the trained model model = joblib.load(model_file_path) # Get the URL from the request data url = request.data.get("url", "") if not url: return Response({"error": "URL is required"}, status=status.HTTP_400_BAD_REQUEST) # Transform the URL into a numeric format using the fitted vectorizer url_features = tfidf_vectorizer.transform([url]) # Predict … -
Popen subprocess giving wrong ffmpeg process ID when trying to close
I'm trying to create a Video Management System application using React and Django, that displays live camera stream and do video recording. For this, I add cameras using POST request and everything works fine. But when I am required to update a camera's details, like IP address or password, then first I delete the camera and then create a new instance with same camera name. The problem I'm facing is that the process ID of the camera (ffmpeg instance here) is not updating, e.g. if initially the process ID was 10, then it remains 10 (in terminate() function in the code) even when I re-create the camera with new details but I do get new process ID in start() function. Below is the code: import subprocess from subprocess import Popen import os, sys import threading import time from datetime import datetime import pytz import os, signal """This class is used to create camera objects to display live stream and recordings, it is also used to manage recordings files by deleting them at the given time""" class CameraStream: def __init__(self, device_name, username, password, ip_address, storage_days): self.cam_name = device_name self.username = username self.password = password self.cam_ip = ip_address self.storage_days = storage_days self.p1 … -
How to Query If An Instance Exists Within A Many-To-Many Field On Django Queryset
Here are simplified model definitions class Resource(models.Model): name = models.CharField(max_length=100, unique=True) class Location(models.Model): name = models.CharField(max_length=100, unique=True) resources = models.ManyToManyField(Resource) And I want to know for one type of Resource, the existence on each Location. So the json data I want is like [ { "id": 1, "name": "loaction_A", "resource": true }, { "id": 2 "name": "location_B", "resource": false }, ... ] I tried following view function but obviously got wrong results. def resource_view(request, res_id): res = get_object_or_404(Resource, pk=res_id) locations = Location.objects.values('id', 'name')\ .annotate(resource=Q(resources=res)) return JsonResponce({'locations': list(locations)}) I know I need something like below (in SQL) select app_location.*, 1 in ( select resource_id from app_location_resources where location_id = app_location.id ) as resource from app_location How should I construct the queryset?