Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Hi,the submit in this project is not working,how to fix it?
When I click submit in the add tasks page,I get no response.The submit button is supposed to add tasks to the list in the tasks page.It does not show any errors and I'm not sure if its code is even running. this is the views.py code from django.shortcuts import render from django import forms from django.urls import reverse from django.http import HttpResponseRedirect # Create your views here. class NewTaskForm(forms.Form): task = forms.CharField(label="New Task") # Add a new task: def index(request): # Check if there already exists a "tasks" key in our session if "tasks" not in request.session: # If not, create a new list request.session["tasks"] = [] return render(request, "tasks/index.html", { "tasks": request.session["tasks"] }) def add(request): # Check if method is POST if request.method == "POST": # Take in the data the user submitted and save it as form form = NewTaskForm(request.POST) # Check if form data is valid (server-side) if form.is_valid(): # Isolate the task from the 'cleaned' version of form data task = form.cleaned_data["task"] # Add the new task to our list of tasks request.session["tasks"] += [task] # Redirect user to list of tasks return HttpResponseRedirect(reverse("tasks:index")) else: # If the form is invalid, re-render the page with existing … -
Saved image cannot be displayed in Django filer
I'm having a problem viewing uploaded images in Django filer. The images can be uploaded without any problems and will also be saved in the specified folder. After that it will be shown as follows: Screenshot filer page When I then click on expand I get the following error: Screenshot Error My urls.py looks like this: from django.conf.urls.i18n import i18n_patterns from django.contrib import admin from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.urls import include, re_path, path from django.views.i18n import JavaScriptCatalog from django.contrib.sitemaps.views import sitemap from cms.sitemaps import CMSSitemap from djangocms_blog.sitemaps import BlogSitemap urlpatterns = i18n_patterns( re_path(r'^jsi18n/$', JavaScriptCatalog.as_view(), name='javascript-catalog'), ) urlpatterns += staticfiles_urlpatterns() urlpatterns += i18n_patterns( re_path(r'^admin/', admin.site.urls), re_path(r'^', include('cms.urls')), re_path(r'^sitemap\.xml$', sitemap, {'sitemaps': {'cmspages': CMSSitemap, 'blog': BlogSitemap,}}), re_path(r'^taggit_autosuggest/', include('taggit_autosuggest.urls')), re_path(r'^filer/', include('filer.urls')), ) admin.site.enable_nav_sidebar = False I installed django-filer according to the documentation. But apparently it doesn't work. How can I solve this problem? -
Overwrite file if the name is same in Django
How do I overwrite the file if the name of the new file is similar to the one already uploaded. If I can take file.name and delete any file present with this name and then store this file that also works for any . Any method would work please help This is my view.py from django.shortcuts import render from django.views.generic import TemplateView from django.core.files.storage import FileSystemStorage from django.http import HttpResponse import requests from geopy.distance import geodesic as GD import pandas as pd from subprocess import run,PIPE from .forms import UploadFileForm from django.core.files.storage import FileSystemStorage def upload_file(request): if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) file = request.FILES['file'] fs = FileSystemStorage() fs.save(file.name, file) else: form = UploadFileForm() return render(request, 'upload.html', {'form':form}) -
Add unique_together validation check on internal attirbutes of JSONField
I am using following model. class MyProfile(models.Model): name = models.CharField(max_length=100, default=None) account_id = models.CharField(max_length=64, default=None) prof_config = JSONField(null=True, blank=True, default=None) result = JSONField(null=True, blank=True, default=None) class Meta(object): app_label = "app" verbose_name = "MyProfile" unique_together = [["account_id", "prof_config"]] Previously prof_config included: prof_config = {"username":"pranav","password":"123456"} But now I have changed it to : prof_config = {"username":"pranav","password":"123456","last_sync_time":null} And as I want unique_together validation only on account_id, username and password. For that I changed unique_together to: unique_together = [["account_id", "prof_config__username","prof_config__password"]] But it didn't work. It gave me following error (if last sync time is null for both profiles): "Error while creating My Profile, error:duplicate key value violates unique constraint \"app_myprofile_account_id_prof_config_b94a5cdc_uniq\"\nDETAIL: Key (account_id, prof_config)=(4, {\"password\": \"123456\", \"username\": \"pranav\", \"last_sync_time\": null}) already exists.\n", "causality": "", "opid": "fc3501fa", "opid_chain": "fc3501fa", "level": "ERROR"} I am getting this error even after I have added unique_together for account_id, username and password ([["account_id", "prof_config__username","prof_config__password"]]). But it's still taking whole prof_config. And If last sync time is different the profile is being created. So Is there any way to do this. -
How can I reduce the CPU usage Python?
Here's the situation: There's a django command below. And I want to constantly scan the table EntityLimitTask whose status is not handle and changed it's status to success after some work # command name is update_entity_info import logging from concurrent.futures import ThreadPoolExecutor from functools import partial from django.core.management.base import BaseCommand from django.db.transaction import atomic from django.conf import settings from policy_insight.models import EntityLimitTask from policy_insight.enums import PiTaskStatusEnum, EntityTypeEnum, AgentTypeEnum from user_account.models import KaOEEntityInfo from utils.common import GetOeTokens logger = logging.getLogger('pi') logger.setLevel("ERROR") class Command(BaseCommand): help = 'entity limit info' def add_arguments(self, parser): ... def handle(self, *args, **options): import django.db django.db.close_old_connections() entity_limit_tasks = EntityLimitTask.objects.filter(handle_status=PiTaskStatusEnum.NOT_HANDLE, is_deleted=0) with ThreadPoolExecutor(max_workers=10) as e: e.map(partial(self._update_entity_limit_info, madhouse_token, bv_token), entity_limit_tasks) @staticmethod def _update_entity_limit_info(madhouse_token, bv_token, task): try: # do something task.handle_status = PiTaskStatusEnum.SUCCESS task.save() except Exception: import traceback as tb logger.error("[update_entity_limit] with error: {}".format(tb.format_exc())) Then I write a infinite loop in a shell file like : # update_entity_info.sh source /path/to/bin/activate while true do python /path/to/manage.py update_entity_limit --pythonpath /path/to/conf --settings settings done But when start it I found my CPU usage is very high top PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND 21297 user 20 0 984.5m 50.4m 11.6m R 191.3 0.1 0:02.35 python /path/to/manage.py update_entity_limit --pythonpath … -
TypeError at /productdetails/20 'Products' object is not iterable
I am doing CRUD using serializers and I am trying to make a page which will display the details of the clothes that I have clicked on. The below error is coming below is the productdetails function def productdetails(request,id): prod = Products.objects.get(id=id) product = POLLSerializer(prod,many=True) return render(request,'polls/productdetails.html',{'data':product.data}) model class Products(models.Model): categories = models.ForeignKey(Categories,on_delete=models.CASCADE) sub_categories = models.ForeignKey(SUBCategories,on_delete=models.CASCADE) color = models.ForeignKey(Colors,on_delete=models.CASCADE) size = models.ForeignKey(Size,on_delete=models.CASCADE) image = models.ImageField(upload_to = 'media/',width_field=None,height_field=None,null=True) title = models.CharField(max_length=70) price = models.CharField(max_length=10) sku_number = models.CharField(max_length=10) product_details = models.CharField(max_length=1000) quantity = models.IntegerField(default=0) isactive = models.BooleanField(default=True) below is productdetails.html ,since I need details of only 1 product,there is no need for loops hence I didnt add for loop <table> <tbody> <tr> <td>{{data.id}}</td> <td>{{data.title}}</td> <td>{{data.price}}</td> <td>{{data.sku_number}}</td> <td>{{data.product_details}}</td> <td>{{data.size}}</td> <td>{{data.quantity}}</td> <td>{{data.image}}</td> </tr> </tbody> </table> help is greatly appreciated,thanks! -
DRF update model with many-to-many field
I have two models with many-to-many relationship and I also have nested routers between them. When I'm trying to create a tag at the endpoint api/page//tags/, tag is created in the database for tags, but nothing happend in my table for many to many relationship. How can I fix it? Models look like this. models.py class Tag(models.Model): title = models.CharField(max_length=30, unique=True) class Page(models.Model): ... tags = models.ManyToManyField(Tag, related_name='pages') My serializers.py class TagSerializer(serializers.ModelSerializer): class Meta: model = Tag fields = '__all__' class PageSerializer(serializers.ModelSerializer): tags = TagSerializer(many=True) owner = serializers.HiddenField(default=serializers.CurrentUserDefault()) class Meta: model = Page fields = ['id', 'title', 'uuid', 'description', 'owner', 'is_private', 'tags'] views.py class PageViewSet(viewsets.ModelViewSet): queryset = Page.objects.all() serializer_class = PageSerializer def perform_update(self, serializer): serializer.save(owner=self.request.user, tags=serializer) class TagViewSet(viewsets.ModelViewSet): serializer_class = TagSerializer queryset = Tag.objects.all() class NestedTagViewSet(CreateModelMixin, ListModelMixin, GenericViewSet): queryset = Tag.objects.all() serializer_class = TagSerializer permission_classes = (IsAuthenticatedOrReadOnly,) def get_page(self, request, page_pk=None): page = get_object_or_404(Page.objects.all(), pk=page_pk) self.check_object_permissions(self.request, page) return page def create(self, request, *args, **kwargs): self.get_page(request, page_pk=kwargs['page_pk']) return super().create(request, *args, **kwargs) def get_queryset(self): return Tag.objects.filter(pages=self.kwargs['page_pk']) def list(self, request, *args, **kwargs): self.get_page(request, page_pk=kwargs['page_pk']) return super().list(request, *args, **kwargs) -
django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'authentication.User' that has not been installed
I'm creating app with authentication. My project is dockerized. When I run the server everything works fine, except authentication.User: (models.W042) Auto-created primary key used when not defining a primary key type, by default 'django.db.models.AutoField'. But when I want to run docker-compose exec web python3 manage.py makemigrations or docker-compose exec web python3 manage.py migrate I get an error: File "/usr/local/lib/python3.9/site-packages/django/contrib/auth/init.py", line 176, in get_user_model raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'authentication.User' that has not been installed I've thought it points to settings.py field AUTH_USER_MODEL, but I haven't got it. My views.py: def signup(request): if request.method == "POST": context = {'has_error': False, 'data': request.POST} email = request.POST.get('email') username = request.POST.get('username') password = request.POST.get('password') if len(password) < 6: messages.add_message(request, messages.ERROR, 'Password should be at least 6 characters') context['has_error'] = True if not validate_email(email): messages.add_message(request, messages.ERROR, 'Enter a valid email address') context['has_error'] = True if not username: messages.add_message(request, messages.ERROR, 'Username is required') context['has_error'] = True if models.User.objects.filter(username=username).exists(): messages.add_message(request, messages.ERROR, 'Username is taken, choose another one') context['has_error'] = True return render(request, 'authentication/signup.html', context) # status=409 if models.User.objects.filter(email=email).exists(): messages.add_message(request, messages.ERROR, 'Email is taken, choose another one') context['has_error'] = True return render(request, 'authentication/signup.html', context) # status=409 if context['has_error']: return render(request, 'authentication/signup.html', context) user = models.User.objects.create_user(username=username, email=email) … -
django import error in django-import-export
I am using django-import-export. I am getting errors in importing data to a database with foreignkey value. class Meta: model = model fields=('id','title','Model_code','Chipset','chipset_description','image','Brand__title','Cat')` Here Brand is used as foreign-key and I get the title by using Brand__title . It works perfectly for exporting but when importing it through an error for foreignkey is null. Line number: 1 - null value in column "Brand_id" of relation "firmApp_model" violates not-null constraint DETAIL: Failing row contains (6, f16, sd, images/sample_3pahsfV.jfif, gf, kjkj, null). None, f16, sd, images/sample_3pahsfV.jfif, gf, 1, kjkj, 1 -
Error when changing sqlite to postgresql while making an app with django
I got an error when I changed sqlite to postgresql while making an app with django. Shows the error that occurred. conn = _connect(dsn, connection_factory=connection_factory, **kwasync) django.db.utils.OperationalError DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': 'postgres', 'HOST': '127.0.0.1', 'POST': '5432' } } -
How to Hydrate dehydrated data and import to DB
Hi all i tried to export data from django postgresql and was facing issue of resolving the foreign key id to name/title which was resolved by below method and the data was extracted successfully. class MemberResource(resources.ModelResource): Brand=Field() class Meta: model = model fields=('id','title','Model_code','Chipset','chipset_description','image','Brand','Cat') export_order=('id','title','Model_code','Chipset','chipset_description','image','Brand','Cat') def dehydrate_Brand(self, obj): return str(obj.Brand.title) class modelAdmin(ImportExportModelAdmin): resource_class = MemberResource list_display=['id','title','Model_code','Chipset','chipset_description','Brand','categories'] search_fields = ['title','Model_code','Chipset',] fields=('title','Model_code','Chipset','chipset_description','image','Brand','Cat') admin.site.register(model,modelAdmin) now i want to import/upload the data back to database by using the same exported xls without inserting the ID of foreign key and inserting the name of foreign key. need guide to hydrate the data back. i also tried with below hydrate method def hydrate_Brand(self, obj): return str(obj.Brand.title) def hydrate not showing any error but the data is also not imported to database. -
Unable to list locks using list_at_resource_level in azure
compute_client = authenticate.client_management(subscription_id) for resource_group in resources_groups.keys(): vm_list = compute_client.virtual_machines.list(resource_group) for vm in vm_list: array = vm.id.split("/") locks_client = authenticate.locks_client(subscription_id) result = locks_client.management_locks.list_at_resource_level(resource_group, "Microsoft.Compute", "/subscriptions/XXXXXX/resourceGroups/YYYY", "Microsoft.Compute/virtualMachines", array[-1]) Using the following class for locks :: /usr/local/lib/python3.8/dist-packages/azure/mgmt/resource/locks/v2016_09_01/operations/_management_locks_operations.py The result of the above program is :: azure.core.exceptions.ResourceNotFoundError: (InvalidResourceType) The resource type could not be found in the namespace 'Microsoft.Compute' for api version '2016-09-01'. Code: InvalidResourceType Can someone please help me fix this. Thanks. -
How can i use Django template and jinja2 together? Such that i can use both in my project
I want to use both jinja and Django templates together, such that it does not show error of templatenotfound. When I try to use jinja as well, Django does not view the jinja templates but only Django templates, but when I omit the Django templates configuration, jinja works fine. I want to use both. TEMPLATES = [ # trying out jinja { 'BACKEND': 'django.template.backends.jinja2.Jinja2', 'DIRS': [os.path.join(MAIN_DIR, 'templates_jinja')], 'APP_DIRS': True, 'OPTIONS': {'environment': 'newquiz.jinja2.environment'} }, { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates_django')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', # for redirecting to previous page after login # imp 'material.context_processors.footer_processor', 'aboutus.context_processors.about_processor', 'quiz.context_processors.material_processor', 'social_django.context_processors.backends', 'social_django.context_processors.login_redirect', ], }, }, ] -
Cannot show image and css styling while sending html template with dj_rest_auth
Hy there, I have follow each and every step to send html template while registering user with dj_rest_auth. email is successfully send but image and css styling is shown in email. in urls.py path("auth/registration/", include("dj_rest_auth.registration.urls")), File structure appname templates account email email_confirmation_signup_message.html -
django custome login redirection middleware redirection problem says ERR_TOO_MANY_REDIRECTS
hi friends i need some help i want to redirect a user when he try to access a page in my django settings.py is MIDDLEWARE = ['cart.middleware.LoginRedirectMiddleware'] url.py is (home is the app name) path('',views.login,name="login"), path('home',views.home,name="home"), middleware.py is (located in mainapp) def process_view(self, request, view_func, view_args, view_kwargs): """ Called just before Django calls the view. """ print("executed") if (request.user.is_authenticated): return redirect('home') else: return redirect('login') -
Individual product details viewing
I am making a CRUD of products and one of my tasks is to have a page that would display the details of the product when clicked. I have seen various websites on how to make a product details page including from stackoverflow but without any success.I am also getting the below error despite writing the names of the functions correctly this is despite writing the name 'productdetails' in the urls.py below urlpatterns=[ path('',views.showAdminPage,name="showadmin"), path('products/<int:id>/',views.productdetails, name='productdetails'), path('show/',views.show,name="show"), path('insert/',views.insert,name="insert"), path('update/<int:id>/',views.update,name="update"), path('delete/<int:id>/',views.delete,name="delete"), path('shoppingpage/',views.shoppingpage,name="shoppingpage"), path('allproducts/',views.allproducts,name="allproducts"), path('9-6wear/',views.ninesixwear,name="ninesixwear"), path('kurta/',views.kurta,name="kurta"), path('skirtset/',views.skirtset,name="skirtset"), path('dress/',views.dress,name="dress"), path('kurtaset/',views.kurtaset,name="kurtaset"), path('desiswag/',views.desiswag,name="desiswag"), path('sharara/',views.sharara,name="sharara"), path('plazzo/',views.plazzo,name="plazzo"), path('dhoti/',views.dhoti,name="dhoti"), path('anarkali/',views.anarkali,name="anarkali"), path('fusionwear/',views.fusionwear,name="fusionwear"), path('drapesaree/',views.drapesaree,name="drapesaree"), path('jumpsuits/',views.jumpsuits,name="jumpsuits"), path('croptopwithskirt/',views.croptopwithskirt,name="croptopwithskirt"), path('indowestern/',views.indowestern,name="indowestern"), path('lehenga/',views.lehenga,name="lehenga"), path('heavysuitset/',views.heavysuitset,name="heavysuitset"), path('gown/',views.gown,name="gown"), path('bridalwear/',views.bridalwear,name="bridalwear"), ] productdetails function in views.py def productdetails(request,id): product = Products.objects.get(id=id); context = {'data':product} return render(request,'polls/productdetails.html') model class Products(models.Model): categories = models.ForeignKey(Categories,on_delete=models.CASCADE) sub_categories = models.ForeignKey(SUBCategories,on_delete=models.CASCADE) color = models.ForeignKey(Colors,on_delete=models.CASCADE) size = models.ForeignKey(Size,on_delete=models.CASCADE) image = models.ImageField(upload_to = 'media/',width_field=None,height_field=None,null=True) title = models.CharField(max_length=70) price = models.CharField(max_length=10) sku_number = models.CharField(max_length=10) product_details = models.CharField(max_length=1000) quantity = models.IntegerField(default=0) isactive = models.BooleanField(default=True) below is the productdetails.html page <table> {% for result in data %} <tbody> <tr> <td>{{result.id}}</td> <td>{{result.title}}</td> <td>{{result.price}}</td> <td>{{result.sku_number}}</td> <td>{{result.product_details}}</td> <td>{{result.size}}</td> <td>{{result.quantity}}</td> </tr> </tbody> </table> kurta.html where the error mentioned above is coming <ul class="row products columns-3" id="appendproducts"> {% for result in data %} <li class="product-item wow … -
Django: fields missing in the Queryset
I have this simple e-commerce project where I am trying to render ItemDetailView using slug, but object_list from Product views.py doesn't have them in the Queryset. I inspected the Queryset and I see many fields missing including Vendor.name Queryset: <QuerySet [{'id': 11, 'category_id': 1, 'vendor_id': None, 'title': 'sample - user1', 'slug': '', 'description': 'sample pic', 'price': Decimal('3.00'), 'date_added': datetime.datetime(2022, 7, 18, 2, 54, 48, 714506, tzinfo=), 'image': 'uploads/IMG-20191217-WA0021_qII27R4.jpg', 'thumbnail': 'uploads/uploads/IMG-20191217-WA0021_qII27R4.jpg'}]> Please help with this. Thanks in Advance #apps/vendor/models.py class Vendor(models.Model): name = models.CharField(max_length = 255) created_at = models.DateField(auto_now_add = True) created_by = models.OneToOneField(User, related_name = 'vendor', on_delete = models.CASCADE) class Meta: ordering = ['name'] def __str__(self): return self.name #apps/vendor/views.py class RegisterMember(CreateView): form_class = UserCreationForm success_url = reverse_lazy('core/frontpage') template_name = 'vendor/register_member.html' class LoginView(LoginRequiredMixin, ListView): model = Vendor template_name = 'vendor/registration/login.html' success_url = reverse_lazy('vendor/member_admin.html') class MemberAdminView(LoginRequiredMixin, ListView): model = Vendor template_name = 'vendor/member_admin.html' def get_context_data(self, **kwargs): context = super(MemberAdminView, self).get_context_data(**kwargs) context['products'] = Product.objects.all() return context class AddItemView(LoginRequiredMixin, CreateView): form_class = ProductForm template_name = 'vendor/add_item.html' success_url = reverse_lazy('vendor/member_admin.html') def form_valid(self, form): form.instance.created_by = self.request.user return super(AddItemView, self).form_valid(form) #apps/product/models.py class Category(models.Model): cat_title = models.CharField(max_length = 255) slug = models.SlugField(max_length = 255) ordering = models.IntegerField(default = 0) class Meta: ordering = ['ordering'] def __str__(self): return … -
Django - CreateView specifying a form to use from forms.py
I'm trying to use a form I have defined in forms.py within my CreateView, as I have css classes and field labels I want to apply. Documentation states declaring a form_class field within your CreateView, but trying to set it as my ModelForm gives me the error TypeError 'AssessmentForm' object is not callable class AssessmentCreateView(LoginRequiredMixin, generic.CreateView): model = Assessment form_class = AssessmentForm() ... What is the proper implementation of setting a ClassBasedView to use a ModelForm? -
Python Anywhere djago
I tried to deploy a Django app with Python Anywhere. To do this I added all of the files in a zip folder I uploaded it to the Files section and I unzipped it from the bash console. But when I run the site it returns The install worked successfully! Congratulations!You are seeing this page because DEBUG=True is in your settings file and you have not configured any URLs.. But I have uploaded the views.py so what happens? Please give me a solution. Thanks. -
how long Express.js will survive against others backend frameworks?
I have been working as a freelance web developer for a long time but now a few questions are just rolling around in my head! What is the current demand for express.js? Apart from express, nodejs has many backend frameworks... eg: koa, hapi, adonis, loopback etc... then again deno & bun (for which node's existence is threatened [I think])! So will there be demand for node/express in the future among so many competitors? Note: I work with mern and also have experience with python(flask, django), in this case should I keep express as backend or go with django + react? In short, express or django which job is more! Or if you learn which one can survive in the market for the next 5-10 years? I am very depressed -
Which Tech stack should be needed to text viewer with highlight function
I'm working on a team project with friends who started web development. We are planning a website that shows users any newspaper articles on a user-specified topic every day. We want to create a website that provides features such as highlighting when a user drags a particular phrase, and writing a note next to it. Users can store articles in their own repository as they highlighted or underlined. (I understand that Microsoft Edge provides similar functionality.) In this case, I have no idea which technology stack should be used to perform the above functions, so I ask you a question. The server is about to be implemented with Django. Microsoft Edge -
NoReverseMatch: Reverse for 'delete_url' with arguments '('',)' not found. 1 pattern(s) tried: ['delete_url/(?P<web>[0-9]+)\\Z']
Hi I'm getting an error when I run my code. I am trying to create a delete function on my webpage. Thank you for your time. My code is as follows: home.html : error is in the href tag {% for web in webs_list %} <tr> <th scope="row"> {{web.url.id}} </th> <td> {{web.url.website}} <a href="{% url 'delete_url' web.id %}" > <button type="button" style="float: right;" class="btn btn-outline-danger">Delete</button> </a> <div class="space" ></div> <button type="button" style="float: right;" class="btn btn-outline-primary" data-bs-toggle="modal" data-bs-target="#updateModal" >Update</button> </td> {% if web.status == "True" %} <td> <a class="btn btn-success">Up</a> </td> {% else %} <td> <a class="btn btn-danger">Down</a> </td> {% endif %} </tr> {% endfor %} urls.py path('delete_url/<int:web>',views.delete_url,name="delete_url"), views.py def delete_url(request,web): url = Website.objects.get(pk=web) url.delete() return redirect('monitor/home.html') -
Django Forms and Mapbox how to save data when page is refreshed
I have been struggling with this problem for a long time now and I cannot seem to find any problem similar to it with a solution. Basically the project that I am working on involves use of the Mapbox framework which displays a map of Yellowstone national park. The user is then able to click on an upload picture button which sets a boolean value either "true" or "false" for if they want to upload a picture based where on the map they click next. If this value was true and the user clicks on a spot on the map, the coordinates of the cursor is then used to place a marker with a popup containing a Django form. This form model can then be filled out the user can press submit. default map img filling out post on map img Ideally I would like the submit button to just place to filled out form within the popup and also keep the marker there. Right now whenever I hit submit, the whole page gets refreshed and the map get re-loaded and all modifications made simply disappear. The filled out form that was submitted does get added to my database though. … -
Django tenant based users
Scenerio: A global user can visit any tenant Different tenant will create different user of their own password A general user can create account in different tenant with different password Tenant superuser can create their own group with permission Using django_tenant and django_tenant_users. But can not able to do these. Need suggestion how to achieve this using django -
How can I retrieve a Word document from my Django endpoint?
I am interested in making a web application with a Vue frontend and Django backend that allows the user to upload a word document to a Django API with a configuration object to format and edit the document with python-docx. I am currently trying to download the file from the REST endpoint and keep encountering this issue. script.js:32 Error: SyntaxError: Unexpected token P in JSON at position 0 I am using fetch to make the POST request to the endpoint and I honestly think the error lies somewhere in there if not my file object handling. The application is currently without much exception handling because I just want to see if I can get this core mechanism to work so apologies on the current state of the application. script.js api call methods: { run(e) { //test data const config = { pageLimit: 9, marginSize: 1, }; const fileInputField = document.getElementById("document"); const formData = new FormData(); formData.append("config", JSON.stringify(config, null, 2)); formData.append("file", fileInputField.files[0]); fetch("http://localhost:8000/format/", { method: "POST", body: formData }) .then(response => response.blob()) .then(blob => { var a = document.createElement("a"); a.href = window.URL.createObjectURL(blob); a.download = "Test.docx"; document.body.appendChild(a) a.click(); }) .catch(error => { console.error("Error:", error); }) } }, views.py format endpoint def format(request): …