Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
wagtail main search add modelAdmin models
Quick question on wagtail's main search at the top of the left sidebar beneath the logo. By default that search box searches pages, images, documents, users. Two questions: Is there a way to modify that search scope so it also includes modelAdmin models? Is there a way to remove pages from the search query list so it only searches images, documents, users? I can't seem to find anything in the docs about it. I know you can search modelAdmin models once on the model admin list view, I have that working. I was just looking for a way to extend that search to be included on the main sidebar search as well. Any direction you can provide would be much appreciated. -
MultiValueDictKeyError Request Method: GET (Django)
I have recently started to learn and work on Django i came across this error multiple times sometimes it was due to repetitive use of a name in an html and sometimes it was due the part for example "variable_name=request.POST['variable_name']" I visited various sites regarding this error and was able to find a solution i.e, once i have typed in "variable_name=request.POST['variable_name']" in a function in views.py the next time i tried to POST the data again "variable_name=request.POST['variable_name']" I had to do something like this "variable_name=request.POST.get('variable-name', 'blank_or_whatever_canBeFalseAlso') The Above statement helped me solve that error I got this solution from A Thread in StackOverflow itself Quite a useful site. Now for the Question am just Curious to know whats the difference between Variable_Name=request.POST['Variable_Name'] Variable_Name=request.POST.get('Variable_Name','Whatever') Code (views.py) Is given Below: from django.shortcuts import render from . import views from datetime import date from .models import Batch, Deleted_Batch from django.utils.datastructures import MultiValueDictKeyError # Create your views here. today = date.today() Date_Batch = str(today.day)+'/'+str(today.month)+'/'+str(today.year) def Reg_Batch(request): return render(request, 'Reg_Batch.html',{'Date_Batch':Date_Batch}) def Reg_Batch_Receive(request): Region_Code=request.POST['Region_Code'] Branch_Code=request.POST['Branch_Code'] Batch_Number=request.POST['Batch_Number'] Farm_Code=request.POST['Farm_Code'] Farm_Status=request.POST['Farm_Status'] Farmer_Name=request.POST['Farmer_Name'] Farmer_Address=request.POST['Farmer_Address'] Farmer_Phone_Number=request.POST['Farmer_Phone_Number'] Farmer_Email=request.POST['Farmer_Email'] return render(request, 'Reg_Batch_Receive.html') def Reg_Batch_View(request): Region_Code=request.POST.get('Region_Code', 'Blank') Branch_Code=request.POST.get('Branch_Code', 'Blank') Farm_Code=request.POST.get('Farm_Code', 'Blank') Farm_Status=request.POST.get('Farm_Status', 'Blank') return render(request, 'Reg_Batch_View.html',{'Region_Code':Region_Code,'Branch_Code':Branch_Code,'Farm_Code':Farm_Code,'Farm_Status':Farm_Status}) def Reg_Batch_View_Receive(request): Date_Batch= '20/08/2000' Region_Code='586001' Branch_Code='586001' Batch_Number='586001' Farm_Code='5484712' … -
How to Build a Django Chained Dropdown ModelForm
I'm building an accounting app for my project, The app contains two models 1. Account and 2. Transaction The Transaction, in turn, contains the reference to other models in the project to help us identify the association. Please refer to the image attached for flow. The challenge I'm facing is keeping the whole process confined to a single transaction model and a single form. Is there a way to structure the model in such a way? Vehicle, Driver, Customer, and Booking are other models in the project, which will need relationship with transactions. -
Password hashing algorithm in Django [closed]
I have copied data from one model(Model-Maintab) to user_auth table (table for authentication), they have the same fields so appending data is not an issue. When storing in Maintab, I have used the pbkdf2_sha256.... algorithm which stores password in the backend in the format: $pbkdf2....., but when storing this data in auth_user table, this password format is not recognized. The auth_user table stores password in the format: pbkdf2_sha256....(without the '$' sign in front). The password hashing algorithm is same, so why does auth_user not consider my appended password, or what can I provide as a solution? -
Howo to solve my below issue , celery production setup error
Hi I'm trying to setup django and celery in production. Here is the my /etc/conf.d/celery file. CELERYD_NODES="w1" CELERY_BIN="/home/.../env/bin/celery" CELERY_APP="projectname" # How to call manage.py CELERYD_MULTI="multi" # Extra command-line arguments to the worker CELERYD_OPTS="--time-limit=300 --concurrency=8" # - %n will be replaced with the first part of the nodename. # - %I will be replaced with the current child process index # and is important when using the prefork pool to avoid race conditions. CELERYD_PID_FILE="/var/run/balu/%n.pid" CELERYD_LOG_FILE="/var/log/balu/%n%I.log" CELERYD_LOG_LEVEL="INFO" Here is the my celery.service file [Unit] Description=Celery Service After=network.target [Service] Type=forking User=balu Group=balu EnvironmentFile=/etc/conf.d/celery WorkingDirectory=/home/.../projecttitle ExecStart=/bin/sh -c '${CELERY_BIN} multi start ${CELERYD_NODES} \ -A ${CELERY_APP} --pidfile=${CELERYD_PID_FILE} \ --logfile=${CELERYD_LOG_FILE} --loglevel=${CELERYD_LOG_LEVEL} ${CELERYD_OPTS}' ExecStop=/bin/sh -c '${CELERY_BIN} multi stopwait ${CELERYD_NODES} \ --pidfile=${CELERYD_PID_FILE}' ExecReload=/bin/sh -c '${CELERY_BIN} multi restart ${CELERYD_NODES} \ -A ${CELERY_APP} --pidfile=${CELERYD_PID_FILE} \ --logfile=${CELERYD_LOG_FILE} --loglevel=${CELERYD_LOG_LEVEL} ${CELERYD_OPTS}' [Install] WantedBy=multi-user.target I have restarted sudo systemctl daemon-reload and when i'm trying to start celery I'm getting an error like this. Job for celery.service failed because the control process exited with error code. See "systemctl status celery.service" and "journalctl -xe" for details. Here is the complete list of error status ● celery.service - Celery Service Loaded: loaded (/etc/systemd/system/celery.service; disabled; vendor preset: enabled) Active: failed (Result: exit-code) since Tue 2020-04-21 10:13:02 IST; 10s ago … -
How to transfer your local sqlite3 data to heroku?
I made a django which works perfect,I then tried to deploy it to heroku.Everything is great but my local data.My development db was sqlite3 than I configured heroku database url in there.The data that was stored in my sqlite3.How can I transfer local data to my heroku app which uses postgres. Please can you walk me through! Here's my django database settings The database url is the heroku postgres url DATABASES = { 'default':dj_database_url.config( default=env('DATABASE_URL') ) } -
Redirect to your custom page after login- Django
Whenever I login from the Django admin site, It redirects me to the Admin Site of the django. Whereas, I want to redirect to my own custom page. How It's done? Thanks -
Django settings file not found no matter what
I searched deep and wide, but no solution has worked so far. I'm trying this with Django 1.6 in my virtual environment. In my manage.py file I have the following line: os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myproj.settings") With this, when I execute python ./manage.py runserver I get the traceback: Traceback (most recent call last): File "./manage.py", line 9, in <module> execute_from_command_line(sys.argv) File "/home/int/.local/lib/python2.7/site-packages/django/core/management/__init__.py", line 453, in execute_from_command_line utility.execute() File "/home/int/.local/lib/python2.7/site-packages/django/core/management/__init__.py", line 392, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/int/.local/lib/python2.7/site-packages/django/core/management/__init__.py", line 263, in fetch_command app_name = get_commands()[subcommand] File "/home/int/.local/lib/python2.7/site-packages/django/core/management/__init__.py", line 109, in get_commands apps = settings.INSTALLED_APPS File "/home/int/.local/lib/python2.7/site-packages/django/conf/__init__.py", line 53, in __getattr__ self._setup(name) File "/home/int/.local/lib/python2.7/site-packages/django/conf/__init__.py", line 48, in _setup self._wrapped = Settings(settings_module) File "/home/int/.local/lib/python2.7/site-packages/django/conf/__init__.py", line 134, in __init__ raise ImportError("Could not import settings '%s' (Is it on sys.path?): %s" % (self.SETTINGS_MODULE, e)) ImportError: Could not import settings 'myproj.settings' (Is it on sys.path?): cannot import name current_app Then I added sys.path.insert(0, '/home/int/Documents/myproj/myproj'), where the modules are to my manage.py file and got the same traceback as above. If I try relative import, i.e. changing that line in manage.py to os.environ.setdefault("DJANGO_SETTINGS_MODULE", ".myproj.settings") I get the error TypeError: relative imports require the 'package' argument The file settings.py is definitely in /home/int/Documents/myproj/myproj (triple-checked). So I don't know how to solve this … -
Mapping/connect issue on publishing Django website
Apologise but, I'm clueless on what to do. My boss bought this Namecheap domain, set web-app (example) "www.Monday.com" Now he asks me to set another web-app "www.Monday.com/ABC" with the Django framework. I did the following instruction given by Namecheap: https://www.namecheap.com/support/knowledgebase/article.aspx/10048/2182/how-to-work-with-python-app and did the setup on Django: https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ run ping check on DNS working run this webpage www.Monday.com/ABC(exmple) result: 404 that lead me to the clueless predicament; I don't even know where I could map wrongly or even to start to debug mapping issue If you could help I really appreciate it -
Django using include() as path() argument
I'm learning Django. In the tutorial it says: The path() function is passed four arguments, two required: route and view, and two optional: kwargs, and name. At this point, it’s worth reviewing what these arguments are for. path() argument: view When Django finds a matching pattern, it calls the specified view function with an HttpRequest object as the first argument and any “captured” values from the route as keyword arguments. We’ll give an example of this in a bit. In my opinion, the view is a function that takes a HttpRequest as argument and returns a HttpResponse. but in mysite/urls.py the path() is used like this path("polls/", include("polls.urls")), and the inclue method returns a tuple (urlconf_module, app_name, namespace), not a function. Why can include() be used here? I'll appreciate it if someone could help. -
Getting In order to allow non-dict objects to be serialized set the safe parameter to False when calling api
I'm attempting to upload a form of serialized data to create a user profile. Whenever calling the api to do this, I get the error "In order to allow non-dict objects to be serialized set the safe parameter to False". API class CustomerDetailViewset(APIView): # import pdb; pdb.set_trace() authentication_classes = [] permission_classes = [] #parser_classes = (MultiPartParser, FormParser) def post(self, request, *args, **kwargs): customer = get_user(request) if not customer: print(request.data) return JsonResponse({'invalid token'}) data = request.data.copy() data['customer'] = customer.id customer_detail = customer.customerdetail.all().first() if customer_detail: data['id'] = customer_detail.id else: data['id'] = None file_serializer = CustomerDetailUploader( data=data, context={'request': request}) if file_serializer.is_valid(): print(file_serializer.validated_data) if customer_detail: file_obj = file_serializer.update( customer_detail, file_serializer.validated_data) else: file_serializer.save() return Response(file_serializer.data, status=status.HTTP_201_CREATED) return Response(file_serializer.errors, status=status.HTTP_400_BAD_REQUEST) Serailizer class CustomerDetailUploader(serializers.ModelSerializer): current_selfie = Base64ImageField() class Meta: model = CustomerDetails fields = ('age', 'phone', 'current_selfie','customer_type','address', 'level', 'current_selfie', 'needs_help_with', 'prefered_strain_type', 'wants_to_feel', 'customer') -
django wont import model from another app
I am not sure why but django wont import model from another app. **App1** from hotels.models import Hotel class Hotel(models.Model): name = models.CharField(max_length=50) description = models.TextField(max_length=300) email = models.EmailField() website = models.CharField(max_length=30) phone_number = models.CharField(max_length=10, validators=[RegexValidator(r'^\d{1,10}$')]) def __str__(self): return self.name class RoomType(models.Model): ROOM_STANDING = ( ('REGULAR', 'REGULAR'), ('BRONZE', 'BRONZE'), ('GOLD', 'GOLD') ) room_standing = models.CharField(max_length=10, choices=ROOM_STANDING, default='REGULAR', null=True) hotel = models.ForeignKey(Hotel, on_delete=models.CASCADE, related_name='room_type_hotels') reservation = models.ForeignKey(Reservation, on_delete=models.CASCADE, related_name='room_type_reservations', null=True) is_smoking_allowed = models.BooleanField(default=False) max_capacity = models.PositiveSmallIntegerField() cost_per_night = models.PositiveSmallIntegerField() **App2** from reservations.models import Reservation class Reservation(models.Model): hotel = models.ForeignKey(Hotel, on_delete=models.CASCADE, related_name='hotel_reservations') made_by = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user_reservations') check_in = models.DateField(default=datetime.date.today) check_out = models.DateField() created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) The order I created each model: Hotel--> then Reservation (import Hotel FK) --> then RoomType (Now that I am trying to import Reservation to create a FK django wont allow me and the message below appears) here the message I get from the terminal. ImportError: cannot import name 'Hotel' from 'hotels.models' The two apps are registered in INSTALLED_APPS Any suggestion? -
Getting Value error when attempting to call api with validated user token
I'm getting this error everytime I attempt to call my api: "ValueError: Cannot query "jake thedogg": Must be "CustomerDetails" instance." I am trying to get all instances of orders from this user. def customer_get_latest_order(request): customer = get_user(request) if not customer: return JsonResponse({'invalid token'}) order = OrderSerializer(Order.objects.filter(customer=customer).order_by("-id"), many=True, context={"request": request} ).data return JsonResponse({"order": order}) Model: class OrderDetail(models.Model): order = models.ForeignKey( Order, related_name='order_details', on_delete=models.CASCADE) product_size = models.ForeignKey(ProductSize, on_delete=models.CASCADE) quantity = models.IntegerField() sub_total = models.FloatField() def __str__(self): return str(self.id) Serializers: class OrderSerializer(serializers.ModelSerializer): customer = CustomerOrderSerializer() driver = OrderDriverSerializer() dispensary = OrderDispensarySerializer() order_details = OrderDetailSerializer(many=True) status = serializers.ReadOnlyField(source="get_status_display") class Meta: model = Order fields = ("id", "customer", "dispensary", 'delivery_signature', 'order_rated', 'quantity', "driver", "order_details", "total", "status", "address", "created_at") Everytime I try to call the api I get that error. -
Allow non-superadmin users to reset the password for another user in django admin
I am working on a third party app running django 2.2.12. I have an admin with 3 kinds of users: "superadmin", "staff" and "other". When I am logged as "superadmin", when I go to the Users list and click on a user, I am able to edit them and reset their password. However, when I try to do the same as a "staff" user, I can see the user data, but can't edit anything, and there's no option to reset the password. If I try to access the URL manually (/admin/accounts/user/[USER_ID]/password/) I get a "403 Forbidden" error message. I noticed that if I override the has_perm method in the user model, it allows the "staff" user to edit the user data. However I would like to allow only the password change (if the user is not a superadmin or a staff user), without allowing "staff" users to edit other users. def has_perm(self, perm, obj=None): return True I have the impression this has to do with the Django permission system, but I re-read the docs at https://docs.djangoproject.com/en/2.2/topics/auth/default/ and couldn't figure this out yet. Thanks -
how can I use in django template
I want to apply webpack file (bundle.js) in my django project's template architecture I typed like this but html can not find my bundle.js with not found 404 <script src="../../node_modules/.bin/dist/bundle.js"></script> console.log(height); </script> help me, how can I load webpack's bundle.js in django template -
Filtering related_name field, in django
I am trying to filter related_name field with a query if it's possible. I serialize the tables. class ProjectsSerializers(serializers.ModelSerializer): class Meta: model = Projects fields = ["id", "project_id", "project_name", "tasks"] depth = 1 Above in the fields list. tasks is the related_table so in the tasks table I have task_created_at field and when I retrieve the projects table. I want to filter it by that field. def get_projects(request): projects = Projects.objects.filter(task_created_at__startswith="2020-04") serializer = ProjectsSerializers(projects, many=True) return Response(serializer.data) Of course this: task_created_at__startswith="2020-04" isn't working. Because task_created_at is not in the projects. it's in the related_name which is tasks. So how can is there a way to filter tasks with getting projects -
QuerySet with Avg
I'm having problems making a queryset for a report :/ The ChangeLog model (please see model picture below) stores every change in MedicalRequest model. I'm trying to get the time average from first record to last record in ChangeLog for a single MedicalRequest. I'm querying from customer because I'need make some reports. I already test this: customer = Customer.objects.get(pk=10) customer.medicalrequest_set.aggregate(avg=Avg(Max(changelog__timestamp), Min(changelog__timestamp))) but I'm getting 'changelog__timestamp' is not defined :( any idea? -
Adding other model data to Django admin model form
I am learning Django and I want to add additional data to the admin page when a user clicks on one of the model forms. Here are my two models that I am working with at the moment: class Event(models.Model): name = models.CharField(max_length=255) test = models.ManyToManyField(Test) applicable_devices = models.ManyToManyField(Device) class Meta: verbose_name = 'Event' verbose_name_plural = 'Events' def __str__(self): return self.name class Property(models.Model): name = models.CharField(max_length=255) description = models.CharField(max_length=255) applicable_events = models.ManyToManyField(Event) applicable_devices = models.ManyToManyField(Device) applicable_platform = models.ManyToManyField(Platform) property_type = models.CharField(max_length=20, choices=TYPE_CHOICES) expected_value = ArrayField(models.CharField(max_length=200), blank=True) def get_applicable_devices(self): device_list = [] for i in self.applicable_devices.all(): device_list.append(i.name) print(i.name) return device_list def get_applicable_platform(self): platform_list = [] for i in self.applicable_platform.all(): platform_list.append(i.name) return platform_list class Meta: verbose_name = 'Property' verbose_name_plural = 'Properties' def __str__(self): return self.name Basically what I want to happen is when I go to the admin panel and click on Events, I am given a list of all the event models that I have created. Then when I click on any event, I want to see the normal fields where I am able to edit the model, but then underneath all of that I want to see all the properties that apply to that event. -
How can I filter enum choice by enum value instead of key
Enum output [(0, A), (1, B), (2, C), (3, D), (4, E), (5, F), (6, G)] I just want to display B, C, D, E, F How can i achieve this? Thanks everyone for answering -
Django datatables.net
I am using Django and jquery datatables.net My model has more than 13000 records When it starts it shows list like datatables.net is not active and the columns is auto adjusting and after it finishes loading it takes 20sec the data it shows with datatables.net active and works perfect and show the pagination and search How should I make it only show the table from datatable.net and increase the speed What am I doing wrong? Thanks prutable.html <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <title>Hello, Table!</title> <link rel="stylesheet" href="https://cdn.datatables.net/1.10.20/css/jquery.dataTables.min.css"> </head> <body> <table id="table_id" class="display" border='2' align="center" style="width:100%"> <thead> <tr> <th>Codigo</th> <th>Descripcion</th> <th>Importe</th> <th>Stock</th> </tr> </thead> <tbody> {% for articulo in object_list %} <tr> <td>{{ articulo.cdg }}</td> <td>{{ articulo.desc }}</td> <td>{{ articulo.imp }}</td> <td>{{ articulo.stock }}</td> </tr> {% endfor %} </tbody> </table> </body> <script src="https://code.jquery.com/jquery-3.3.1.js"></script> <script src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js"></script> <script> $(document).ready(function () { $('#table_id').DataTable({ } ); }); </script> views.py class LstPreListView(ListView): template_name = "base/prutable.html" queryset = Articulo.objects.all().order_by("desc") models.py class Articulo(models.Model): cdg = models.CharField(primary_key=True, max_length=20, blank=True, null=False) desc = models.CharField(db_index=True, max_length=200, blank=True, null=True) imp = models.DecimalField(max_digits=14, decimal_places=2, blank=True, null=True) stock = models.IntegerField(blank=True, null=True) def __str__(self): return '{} '.format(self.nombre) -
Why doesn't my form remove the selected object?
I'm trying to create a form to unsubscribe newsletter subscribers, but I don't know exactly where I'm going wrong. The steps in my view all work in the command line so its hard for me to debug. When I submit the form on an existing email address the error is 'Subscriber with this email already exists', but I'm trying to delete an object not create one, and I'm a little stuck. Any help is much appreciated! My View: from subscribe.forms import SubscribeForm, UnsubscribeForm from django.shortcuts import render, HttpResponseRedirect from django.contrib import messages from .models import Subscriber from django.shortcuts import get_object_or_404 def unsubscribe(request): if request.method == 'POST': form = UnsubscribeForm(request.POST) if form.is_valid(): email = form.cleaned_data['email'] user = get_object_or_404(Subscriber,email=email) user.delete(id=user.id) messages.success(request, 'Unsubscribed') return HttpResponseRedirect('/newsletter/subscribe/') else: messages.error(request, form.errors) return render(request, 'unsubscribe.html', {'form': form}) else: form = UnsubscribeForm() return render(request, 'unsubscribe.html', {'form': form}) My forms: from django.forms import ModelForm, EmailField from .models import Subscriber class SubscribeForm(ModelForm): email = EmailField() class Meta: model = Subscriber fields = ('email',) class UnsubscribeForm(ModelForm): email = EmailField() class Meta: model = Subscriber fields = ('email',) My Model: from django.db import models # Create your models here. class Subscriber(models.Model): email = models.EmailField(max_length=75, unique=True) def __str__(self): return self.email -
redirect to profile after creating a user which auto create a profile
Apologize for being annoying,I'm a beginner programmer and working on my new project. I've made this model which create a profile when a user is created: class ExpertSignUpForm(UserCreationForm): class Meta(UserCreationForm.Meta): model = User @transaction.atomic def save(self): user = super().save(commit=False) user.is_expert = True user.save() expert = Expert.objects.create(expert=user) return user and this is the view. So what i am trying to do here is to sign a user then set his premission as a expert and then log him in which i've already done but what I'm not able to do is to redirect him into his expert details/update profile right after logging in . so if you can help me with that. Thank you in advance. Here are the views: class ExpertSignUpView(CreateView): model = User form_class = ExpertSignUpForm template_name = 'registration/signup_form.html' def get_context_data(self, **kwargs): kwargs['user_type'] = 'expert' return super().get_context_data(**kwargs) def form_valid(self, form): user = form.save() login(self.request, user) return redirect('/') <<------- the urls might help urlpatterns = [ path('',ExpertListView.as_view(), name='list'), path('Esignup/',ExpertSignUpView.as_view(), name='expert_signup'), path('Ssignup/',StudentSignUpView.as_view(), name='student_signup'), path('create/',ExpertCreateView.as_view(), name='create'), path('<str:pk>/',ExpertDetailView.as_view(), name='detail'), path('<str:pk>/update/',ExpertUpdateView.as_view(), name='update'), path('<str:pk>/delete/',ExpertDeleteView.as_view(), name='delete'), ] -
File upload doesn't work when giving the absolute path when using a a text box to upload python Django
I have a web application with Python, Django framework that allows uploading a file. the uploaded file path is shown in a textbox. When I browse and select a file it is shown as c:\fakepath\Sample.docx in the textbox and I click the upload button, Then the file upload happens hasslefree. But if I provide the absolute path in the textbox as C:\xxx\xxx\xxx\sample.docx and click the upload button, the file doesn't upload. Html code to create the upload in a textbox input id="txt" type = "text" value = "Choose File" size="40" align="center" onclick ="javascript:document.getElementById('file').click();"> python code when I try to extract the file uploaded file = request.FILES['file1'] error while giving the absolute path: raise MultiValueDictKeyError(key) django.utils.datastructures.MultiValueDictKeyError: 'file1' -
Django: export csv file with django_table2
I want to have an download button a html page that renders a django table. I followed the documentation of django2 and this post How to export .csv with Django-Tables2? was helpful but could not make the trick. I feel like I have done everything correctly (according to my beginner skills), there is no error but the download button is not there. I was wondering if someone has any help to provide on this one table.py class AnormalTable(tables.Table): class Meta: model = stock_anormal template_name = "django_tables2/bootstrap4.html" export_formats = ['csv', 'xlsx'] view.py @method_decorator(login_required, name='dispatch') class PostDetailalerte_negat(LoginRequiredMixin,APIView, tables.SingleTableMixin, ExportMixin): def get(self, request): queryset = stock_negatif.objects.all() table = NegatTable(queryset) RequestConfig(request).configure(table) export_format = request.GET.get("_export", None) if TableExport.is_valid_format(export_format): exporter = TableExport(export_format, table) return exporter.response("table.{}".format(export_format)) return render(request, 'detailstocknegat.html', {'table':table}) html snipet <div class="d-sm-flex align-items-center justify-content-between mb-4"> <h1 class="h3 mb-0 text-gray-800">ITEMS IN ALERTE SAFETY STOCK LEVEL</h1> <div> {% for format in view.export_formart %} <a href="{% export_url "csv" %}" class="d-none d-sm-inline-block btn btn-sm btn-primary shadow-sm"><i class="fas fa-download fa-sm text-white-50"></i> Generate Report</a> {% endfor %} </div> </div> <table> {% load django_tables2 %} {% render_table table %} </table> -
How to implement Django's Multiple Store Inventory tracking system
I need some opinion on what’s the best way to design a solution abound customized inventory tracking system which works on regional based stores. I have gone through lot of documents but nothing seems to be working for me. So I need some opinion from expert. Here is my use case: I am creating a inventory tracking system for a client with multiple Physical stores which are defined in different regions. Each store has multiple department so I have following models: class Location(models.Model): LocId = models.AutoField(primary_key=True) Name = models.CharField(max_length=100) ShortName = models.CharField (max_length=25) Address = models.TextField(null=True) IsPhysicalLoc = models.BooleanField(default=False) class LocationParent(models.Model): LocParentId = models.AutoField(primary_key=True) LocId = models.ForeignKey(Location, on_delete=models.CASCADE, db_column="LocId") ParentId = models.ForeignKey(Location, on_delete=models.CASCADE, db_column="LocId") Location model holds all location information. This is common model which stores information about physical location as well as region based location. Example: Region = West Coast, and store is in Hollywood. Then it will have two entries: For Region it will define as: Name= WestCoast Region, ShortName: West Coast, Address: Empty, IsPhysicalLoc=False (assuming LocId=1) For Physical store: Name=1 Hollywood; Short Name=1 Hollywood; Address: ; IsPhysicalLoc=True. (assuming LocId = 3) LocationParent table will hold the parent child relationship between Parent and Child Store, So in above …