Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I update inventory product quentity, When checkout a product
I'm really struggling to update the quantity of the jewelry. My project is a e-commerce site which sells jewelry for online customers. When a customer buys jewelry, the jewelry quantity should be updated automatically. As a Example -> 10 Rings available and 2 are bought, the db should be updated as 8 remaining. But if the Ring goes below 0 then a warning should appear "Out of stock". Please help me!!! I have only few days to complete this. Inventory/models.py class jType(models.Model): jtype=models.CharField(max_length=100) def __str__(self): return format(self.jtype) class jewelry(models.Model): category = models.ForeignKey(jType, on_delete=models.CASCADE, null=True) slug = models.SlugField(blank=True, unique=True) date = models.DateField(default=datetime.now, blank=True) description = models.CharField(max_length=500, blank=True) charges = models.FloatField() stoneType = models.ForeignKey(stone, on_delete=models.CASCADE, null=True) NoOfStones = models.IntegerField() weight = models.FloatField() quantity = models.IntegerField() craftsman_id = models.ForeignKey(craftsmen, on_delete=models.CASCADE, null=True) choices = ( ('AVAILABLE', 'Item ready to be purchased'), ('SOLD', 'Item Sold'), ('RESTOCKING', 'Item restocking in few days') ) status = models.CharField(max_length=10, choices=choices, default="AVAILABLE") issues = models.CharField(max_length=100, default="No issues") image = models.ImageField(upload_to='jewelry_image/', null=True, blank=True) @property def net_price(self): return self.charges * 50 @property def total_net_price(self): return self.quantity * self.net_price def get_absolute_url(self): return "/products/list/{slug}/".format(slug=self.slug) def buy_item(self, q): # decrease quantity self.quantity -= q def __str__(self): return 'cat : {0} charges : {1}'.format(self.category, self.charges) def … -
Hosting website on a locally kept web server?
I want this site to be accessible only on the LAN network.How can I achieve this?Do I have install each and everything on the server? -
AttributeError 'str' object has no attribute 'file'
Hello am trying to get the picture downloaded and that error happens views.py def download_product(request,slug,filename): product = Product.objects.get(slug=slug) return render_to_response("products/single.html",locals(),context_instance=RequestContext(request)) and in myapp/templatetags/filename.py import os from django import template register = template.Library() @register.filter def filename(value): return os.path.basename(value.file.name) and the html template single.html is like this {% if edit %} <a href="#">Edit</a> <a href='download/{{ product.download|filename }}'>Download</a> {% endif %} {% endblock %} -
How to retrieve data from self-made restfull_api
I trying to retrieve the information from my API via Y/views.py from another app in the same project. I am receiving the following error ([WinError 10061]). Although, i am able to perform get/post/put via my json_main.js. Thanks to all who support me in this journey. Please read what is already working. I already created the following: X/Views + X/Template.html. X/Views renders information from the backend to the X/template.html. Within this template there is a JSON script(working) that performs a POST/GET/PUT to the API(working) on image click. The function ultimately results in a new record in API/Bestellingen. The information stored via this JSON function (incl. token authentication; csrf) should now be retrieved in the views.py of Y/view. I already created an example dict. that is rendered to Y/template.html I tried several JSON request methods (coreapi, urllib2, urllib3, requests), but keep receiving the error as mentioned before. As already stated: JSON.js script does work. Doing the same via POSTMAN also works. Since i am performing the same via .js and postman, I am quite sure that the variables (token, header and the request) should be ok. I will show some short snippets of already working code. Herafter i will show the code … -
display JsonResponse data in template
I want to send the jsonresponse data to the specified URL def compare(request): if request.method == 'POST': data = request.POST.getlist('brand') response_data = { 'brands': d3, 'redirect_url': 'http://127.0.0.1:8000/demo/'} return JsonResponse(response_data) its my urlpatterns: urlpatterns = [path('compare_in/', views.compare, name='compare'), path('demo/', views.demo, name='demo')] code for sending the data from template to view function ComAction() { let xhr = new XMLHttpRequest(), data = new FormData(); data.append('csrfmiddlewaretoken', getCookie('csrftoken')); brands.forEach(function (brand) { data.append('brand', brand); }); xhr.open('POST', 'compare_in/', true); xhr.onload = function () { if (xhr.status === 200) { data = JSON.parse(xhr.responseText); //alert('Data received successfully. Brands are ' + data.brands); window.location.assign({% url 'demo' %}); } else if (xhr.status !== 200) { alert('Request failed.'); } }; xhr.send(data); } def demo(request): return render(request, 'prodcutSearch/demo.html') I want to send the jsonresponse data to the http://127.0.0.1:8000/demo/ and display the data in the demo template. please give me your suggestions. -
How to put tinymce in django website as all of the forums instead of just the admin panel?
How can i put the tinymce as all of the textareas on my website and not just in the admin panel. I would like for all of my forums with a textfield to have the tinymce editor. How can i do this? -
RadioSelect widget with generic UpdateView
which is updated by UpdateView. And I wanted to add radio select to this. All solutions I have found with are forms.py, but since I use UpdateView I won't use widget in forms. Any ideas? views.py class AddPersonView(LoginRequiredMixin, UserPassesTestMixin, UpdateView) model = Trip template_name = 'tripplanner/add_new_member.html' fields = ["members"] success_url = '/' def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) def test_func(self): detailView = self.get_object() if self.request.user in detailView.members.all() or self.request.user in detailView.owners.all(): return True return False .html {% extends "tripplanner/base.html" %} {% load crispy_forms_tags %} {% load i18n %} {% block content %} <div class="content-section"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">{% trans "New member" %}</legend> {{ form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">{% trans "Add" %}</button> </div> </form> </div> {% endblock content %} -
django, passing multiple records using checkboxes
I have a table of records with a html checkbox next to each record created through a for stmt. I current functionality that allows a single Sample to be added to a Container. I've added a selectall checkbox also via javascript Currently each record also has an anchor: {% url 'depot:change_container' operation='add' pk=container.container_id fk=unassigned.sample_id %} to add it to another table, this goes via a m2m and the other table has the opposite functionality. To allow multiple records to be sent I wrap the table in a form, set the action to the above action, but how do I pass multiple records in the view? Here's my code so far: Template <div class="float-left col-md-4"> <h4 class="kap">Samples</h4> <div class="table-responsive"> <form class="" action="{% url 'depot:change_container' operation='add' pk=container.container_id fk=unassigned.sample_id %}" method="POST"> {% csrf_token %} <table class="table-striped table-dark"> <thead> <tr> <th style="padding-left:5px;"> <input type="checkbox" onclick="toggle(this);" /> </th> <th></th> <th>E.N.C.S</th> <th>Current Location</th> </tr> </thead> <tbody> {% for unassigned in unassigned_samples %} <tr> {% if unassigned not in container_contents %} <td style="padding-left:5px;"><input type="checkbox" /></td> # the checkbox method <td style="margin:10px; padding:10px;"><a href="{% url 'depot:change_container' operation='add' pk=container.container_id fk=unassigned.sample_id %}" class="badge badge-primary" role="button"> # the anchor method <i class="fas fa-arrow-left fa-2x"></i> </a></td> <td>{{ unassigned.area_easting }}.{{ unassigned.area_northing }}.{{ unassigned.context_number … -
When i added my app_name into the app/urls.py the page showing not correct
i am getting not right path after adding ap_name in my app/urls.py what is going wrong i dont know i app/urls.py--->> from django.urls import path from . import views app_name = 'blog' urlpatterns = [ path('', views.home_page, name = "home"), path('about/', views.about_page, name = "about"), path('contact/', views.contact_page, name = "contact"), path('products/<int:page_id>/', views.product_details, name = "products"), path('add-product/', views.create_product_page, name = "create_product"), path('update-product/', views.update_product_page, name = "update_product"), path('delate-product/', views.contact_page, name = "delete_product"), ] -
Django - How to serve static files on multiple endpoints?
I'm serving 2 React apps with single python backend. Right now I serve index.html with HttpsREsponse and I have included build/static in STATICFILES_DIRS. Because those files have their hash prepended, they can be mixed up. But I need a way to serve all those files inside build like manifes.json or favicon.ico. Creating a View for all of them seems like a terrible idea. I would love to serve app1/build as static/app1 and app2/build as static/app2. I have searched the Django docs and have found just how to collect static from multiple locations and anything about hosting them at multiple URLs. This is my setup right now: # settings.py STATICFILES_DIRS = [ os.path.join(APP1_DIR, 'build', 'static'), os.path.join(APP2_DIR, 'build', 'static') ] STATIC_ROOT = os.path.join(BASE_DIR, 'static') # urls.py urlpatterns = [ url(r'^app1/manifest.json$', getStaticFileView(app='app1', 'manifest.json').as_view()), url(r'^app1', getStaticFileView(app='app1', 'index.html').as_view()), url(r'^app2/manifest.json$', getStaticFileView(app='app2', 'manifest.json').as_view()), url(r'^app2', getStaticFileView(app='app2', 'index.html').as_view()), ] I'm looking for something like this: # settings.py STATICFILES_MAPPING = [ (os.path.join(APP1_DIR, 'build', 'static'), 'static/app1'), (os.path.join(APP2_DIR, 'build', 'static'), 'static/app2') ] STATIC_ROOT = os.path.join(BASE_DIR, 'static') # urls.py urlpatterns = [ url(r'^app1', getStaticFileView(app='app1', 'index.html').as_view()), url(r'^app2', getStaticFileView(app='app2', 'index.html').as_view()), ] Thanks for any ideas or directions. -
How to Optimization Memory Leakage
hi i am having an issue related to memory leakage on my server and do not know how to deal it can any one suggest me any tool or trick to debug or find memory leakage and optimize it -
How to fix "Ajax sending response multiple times to views.py in django? "
I'm passing HTML iframe source as variable to views.py via ajax response from django template but it is printing temp names as multiple times In index.html: Here im passing temp variable <iframe> tag src to ajax {%for temp in temp_list%} <iframe src='?{{temp}}' style='display:none' onload='statusVNC(this.src)'/> {%endfor%} ajax: Here i'm passing temp_name to views.py <script> function statusVNC(src){ var pageurl = '/vncform/vnc_status/'; var temp_name = src.split('?')[1]; $.ajax({ type: 'GET', url: pageurl, data: {template: temp_name}, success: function (data) { if(data != '') { alert(data.vnc_status) } } }); } </script> in views.py: Here i'm printing request.GET where it is printing temp values mutliple times, please can u suggest how to solve it? def vnc_status(request): print request.GET urls.py: from django.conf.urls import url, include import views urlpatterns = [ url(r'^$', views.index, name=' url(r'^templates/$', views.templates, name='templates'), url(r'^vnc_status/$', views.vnc_status, name='vnc_status'), url(r'^templates/edit/temp_name=(?P<temp_name>[\w\-]+)$', views.editTemplate, name='editTemplate') ] where temp_list = ['arun', 'kumar', 'a', 'a213'] -
Ordering by first foreign key in Django
Consider these two simple models: from django.db import models class Foo( models.Model ): pass class Bar( models.Model ): time = models.DateTimeField( auto_now_add=True ) foo = models.ForeignKey( Foo, on_delete=models.CASCADE related_name='bars' ) How can I order Foo objects by first related Bar object? Foo.objects.order_by('-bars.first__time') -
How to schedule task to run in background using django background tasks
I have set up a background task "date_check" but it does not run daily. I can't figure out where I've went wrong in the setup. I also got the error "TypeError: date_check() missing 1 required positional argument: 'self' when I tried to run python manage.py process_tasks. here is my model.py: ... @background(schedule=5) def date_check(self): """Will be used as a background task to make sure trips that have ended don't hog van availability.""" today = datetime.date.today() name = self.van_used if today > self.trip_start and today > self.trip_end: vans.objects.filter(vanName = name).update(available = True) def save(self, *args, **kwargs): super().save(*args, **kwargs) self.date_check(repeat=Task.DAILY) -
How to filter data in DRF from database by multiple keywords?
I'm a beginner and develop a little REST API project with Django rest framework. There are a bunch of records in PostgreSQL database with a text field and I have some lists of keywords. I'm trying to filter data which contain words from one or some my lists of keywords in this text field. Can you advise me another way around to organize filtering in DRF by using a whole list of keywords at once without entering them in a form? I'm trying to do it with django_filters Here if filter class: # filter class DataFilter(django_filters.rest_framework.FilterSet): keyword = CharFilter(field_name='description', lookup_expr='icontains') class Meta: model = Data fields = ('keyword', ) Here if view class: # view class DataList(generics.ListAPIView): def get_queryset(self): return Data.objects.filter(deadline__gte=date.today()) serializer_class = DataSerializer filter_backends = (filters.DjangoFilterBackend,) filterset_class = DataFilter But in this case, it filters only by one word which I enter in the form. -
How to make a form unbound bound?
how to make the instance passed as a parameter make the form always valid? ue = UE.objects.get(code_ue='INF401') >>>ue_form = UEForms(instance=ue) >>>ue_form.is_valid() False -
Adding more fields to the signup form
I want to know if I can add more fields to the signup form if a user checks a box. For example, if the user checks the box that says he is a photographer one more field will appear in which he can specify what type of photography he does. -
One Django Channels websocket consumer used across whole site?
I have a Django project that uses WebSockets and one consumer (ChatConsumer) for both the chat and notification portion of the application. I had routing.py set to url(r"^messages/(?P<username>[\w.@+-]+)", ChatConsumer) however because notifications are also dependent on the websocket, they need to be accessed from any page on the site. The reason is that when a user clicks on the notification, it is marked as read using socket.send(JSON.stringify(data)); Right now notifications only work when a user is on the /messages/<username>/ URL. If I change routing.py to account for the whole site, (url(r"^", ChatConsumer)), I obviously get a problem File "./consumers.py" in websocket_connect other_user = self.scope['url_route']['kwargs']['username'] 'username' Is there a simple way of resolving this? Because correct me if I'm wrong but I don't think writing a new consumer is appropriate since the notifications and chat are deeply intertwined? consumers.py class ChatConsumer(AsyncConsumer): async def websocket_connect(self, event): other_user = self.scope['url_route']['kwargs']['username'] me = self.scope['user'] thread_obj = await self.get_thread(me, other_user) self.thread_obj = thread_obj chat_room = f"thread_{thread_obj.id}" self.chat_room = chat_room # below creates the chatroom await self.channel_layer.group_add( chat_room, self.channel_name ) await self.send({ "type": "websocket.accept" }) async def websocket_receive(self, event): # when a message is recieved from the websocket print("receive", event) message_type = json.loads(event.get('text','{}')).get('type') if message_type == … -
Python-requests + Django changing the parameters structure in URL
Basicly, I've done with Python-requests and Django search feature through Google Books API with single q parameter (as shown in link below) https://developers.google.com/books/docs/v1/using#WorkingVolumes and after submiting form I'm getting list of dicts in json as I want with this single parameter, and I'm getting in json data where appers keyword "Hobbit" and URL looks like this http://127.0.0.1:8000/api?books=hobbit but when I'm trying to add special keywords provided by Google Books API like, intitle, inauthor, inpublisher, subject, etc. and trying to search for it I'm getting URL http://127.0.0.1:8000/api?books=hobbit&intitle=&inauthor=&inpublisher=&isbn=&lccn=&oclc= which only returns the data of single q parameter, because the correct URL for special keywords in Google Books API looks like this https://www.googleapis.com/books/v1/volumes?q=flowers+inauthor:keyes+subject:somesubject So as you see then correct URL got signs + against & and : against = My question is how to change this structure to correct as Google books API require? Tried to find this in python-requests docs but there are nothing about this views.py def api(request): books = { 'intitle': 'intitle', 'inauthor': 'inauthor', 'inpublisher': 'inpublisher', 'subject': 'subject', 'isbn': 'isbn', 'lccn': 'lccn', 'oclc': 'oclc' } if 'books' in request.GET: books = request.GET['books'] url = 'https://www.googleapis.com/books/v1/volumes?q=%s' % books response = requests.get(url) books = response.json() print(type(books)) with open("data_file.json", "w") as write_file: json.dump(books, … -
Invalid Salt when using bcrypt.checkpw
I am working on a user authentification app using Django. The app allows the user to create an account then login. However, the on th login side i am getting an error when checking for the user password using bcrypt.checkpw I tried printing the value of the user password and the one saved on the data base. I am using SQLite for the database by the way print(request.POST['login_password'].encode()) print(user.password) here is the output: b'87654321' b'$2b$12$bQ6tEDKh.tOJnnPAj84Xe.BZnGi9kI.Sc6Q4gFPeTLw9x53VSVQOW' I also tried: print(request.POST['login_password'].encode()) print(user.password.encode()) b'87654321' b"b'$2b$12$bQ6tEDKh.tOJnnPAj84Xe.BZnGi9kI.Sc6Q4gFPeTLw9x53VSVQOW'" To creat user: user = MasjeedUser.objects.create(first_name=request.POST['first_name'],last_name=request.POST['last_name'],password=bcrypt.hashpw(request.POST['password'].encode(), bcrypt.gensalt()),email=request.POST['email']) to query password: when i use if bcrypt.checkpw(request.POST['login_password'].encode(),user.password) i get as an error: Unicode-objects must be encoded before checking when i tried if bcrypt.checkpw(request.POST['login_password'].encode(),user.password.encode()) i get as an error: invalid salt -
Alternatives to dynamically creating model fields
I'm trying to build a web application where users can upload a file (specifically the MDF file format) and view the data in forms of various charts. The files can contain any number of time based signals (various numeric data types) and users may name the signals wildly. My thought on saving the data involves 2 steps: Maintain a master table as an index, to save such meta information as file names, who uploaded it, when, etc. Records (rows) are added each time a new file is uploaded. Create a new table (I'll refer to this as data tables) for each file uploaded, within the table each column will be one signal (first column being timestamps). This brings the problem that I can't pre-define the Model for the data tables because the number, name, and datatype of the fields will differ among virtually all uploaded files. I'm aware of some libs that help to build runtime dynamic models but they're all dated and questions about them on SO basically get zero answers. So despite the effort to make it work, I'm not even sure my approach is the optimal way to do what I want to do. I also came … -
How to fix migration model 'id' field in Django 2.2?
I have a Django model that does not contain a field for 'id' but in my MySQL instance from a previous migration it shows an 'id' field for some reason. I kept getting an error saying: You are trying to add a non-nullable field 'id' to discussions without a default; we can't do that (the database n eeds something to populate existing rows). So I went and inspected my models.py file which has no 'id' field: class Discussions(models.Model): #team_id = models.ForeignKey(Teams, null=True, on_delete=models.CASCADE) login = models.CharField(max_length=30, null=True) title = models.CharField(max_length=30, null=True) body = models.CharField(max_length=500, null=True) comments = models.CharField(max_length=30, null=True) updated_at = models.CharField(max_length=21, null=True) But it is showing up in my MySQL describe statement: +------------+--------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +------------+--------------+------+-----+---------+----------------+ | id | int(11) | NO | PRI | NULL | auto_increment | | login | varchar(30) | YES | | NULL | | | comments | varchar(30) | YES | | NULL | | | updated_at | varchar(21) | YES | | NULL | | | body | varchar(500) | YES | | NULL | | | title | varchar(30) | YES | | NULL | | +------------+--------------+------+-----+---------+----------------+ and when I … -
Django generic UpdateView returns 404 error: "No user found matching the query" when using pk
I am creating a Django web app and want to use the generic UpdateView by passing in a user's primary key. It works for the DetailView, but not the UpdateView. I've tried specifying the template_name, changing the order of paths in my urls.py file. I haven't tried using a slug yet, but I know I should be able to use a pk. views.py: class ProfileUpdate(generic.UpdateView): model = User fields = ['first_name'] template_name = 'accounts/profile_update_form.html' My urls.py is what frustrates me the most. The address http://127.0.0.1:8000/accounts/profile/5/ works fine, but http://127.0.0.1:8000/accounts/profile/5/edit/ returns a 404 error "No user found matching the query". So I know that the pk=5 exists, but doesn't work for my url ending in /edit/. urls.py: from django.urls import path,include from django.contrib.auth import views as auth_views from . import views app_name = 'accounts' urlpatterns = [ path('login/',auth_views.LoginView.as_view(template_name='accounts/login.html'),name='login'), path('logout',auth_views.LogoutView.as_view(),name='logout'), path('signup/',views.SignUp,name='signup'), path('profile/<int:pk>/',views.Profile.as_view(),name='profile'), path('profile/<int:pk>/edit/',views.ProfileUpdate.as_view(),name='profile_update'), ] profile_update_form.html: {% extends 'base.html' %} {% load bootstrap4 %} {% block content %} <div class="container"> <h2>Sign Up</h2> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {% bootstrap_form form layout='inline' %} <input type="submit" class="btn btn-primary" value="Sign Up"> </form> </div> {% endblock %} -
Getting errors when I run "python manage.py check"
Ever since I have started my job I have not been able to run my web app locally. I have been going at this for a while I still cannot get a clean python manage.py runserver or python manage.py check. I did once install Anaconda on here, is that affecting my paths? Here is the error that I am getting. (venv) BattleStationOnline 10:13:51 aggrigator$~python manage.py runserver Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/anaconda2/lib/python2.7/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line utility.execute() File "/anaconda2/lib/python2.7/site-packages/django/core/management/__init__.py", line 312, in execute django.setup() File "/anaconda2/lib/python2.7/site-packages/django/__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "/anaconda2/lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models(all_models) File "/anaconda2/lib/python2.7/site-packages/django/apps/config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "/anaconda2/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/Users/andynguyen/Desktop/aggrigator/aggrigator/accounts/models.py", line 21, in <module> from simple_history.models import HistoricalRecords File "/anaconda2/lib/python2.7/site-packages/simple_history/models.py", line 18, in <module> from django.urls import reverse ImportError: No module named urls -
Django Model Form Validation Query
In Django, a field is specified as required in a model. Can a model form exclude it and not update? Specifically, I am talking about user creation form. It doesn't ask for email but I think email is required in the model (will have to check though).