Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: How Can I print the values from checkboxes to a new template?
I am creating a web application that will serve as a grocery store. The way I set it up is so the customer can come onto the website, click on the items that they would like to purchase, and then click a submit button to purchase those items. The problem I cannot figure out right now is to take the selected values and print them onto a different page. """models.py""" class Post(models.Model): title = models.CharField(max_length=100) Price = models.DecimalField(max_digits=4, decimal_places=2,default=1) Sale = models.DecimalField(max_digits=4, decimal_places=2,default=1) quantity = models.IntegerField(default=1) author = models.ForeignKey(User, on_delete=models.CASCADE) category = TreeForeignKey('Category',null=True,blank=True, on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) views.py class PostListView(ListView): model = Post template_name = 'blog/home.html' # <app>/<model>_<viewtype>.html context_object_name = 'posts' def inventory(request): products = request.POST.getlist('products') for product in products: a = Post.objects.get(title=products) a.quantity = a.quantity -1 a.save() print(products) return redirect('list') urls.py path('user/<str:username>', UserPostListView.as_view(), name='user-posts'), path('inventory', views.inventory, name='inventory'), home.html {% extends "blog/base.html" %} {% block content %} <form action="{% url 'inventory' %}" method="POST" id="menuForm"> {% csrf_token %} {% for post in posts %} {% if post.quantity > 0 %} <article class="media content-section"> <div class="media-body"> <div class="article-metadata"> <a class="mr-2">{{ post.category }}</a> </div> <h2><a class="article-title" >{{ post.title }}</a></h2> <p class="article-content"> Price: ${{ post.Price }}</p> <p … -
Do we need to create virtual environment if we are using docker, in django project?
Do we need virtual environment if we are using docker, in django project? -
Django/Bootstrap Formatting Issue
I am working through some beginner Django tutorials to build a basic polling website. I have everything working, but I can't get the formatting to display properly on my "results" page for the polls. How my page looks: https://i.stack.imgur.com/AuB6q.png The votes are being displayed, but you can't see them due to the formatting: https://i.stack.imgur.com/QgMgr.png How it is supposed to look: https://i.stack.imgur.com/PmCOb.png Below is my code on my results.html: {% extends 'base.html' %} {% block content %} <h1 class="mb-5 text-center">{{ question.question_text }}</h1> <ul class="list-group mb-5"> {% for choice in question.choice_set.all %} <li class="list-group-item"> {{ choice.choice_text }} <span class="badge badge-success float-right">{{ choice.votes }} vote{{ choice.votes | pluralize }}</span> </li> {% endfor %} </ul> <a class="btn btn-secondary" href="{% url 'polls:index' %}">Back To Polls</a> <a class="btn btn-dark" href="{% url 'polls:detail' question.id %}">Vote again?</a> {% endblock %} Any ideas on what I have wrong? -
What is force_bytes in django? Why we have to use it?
Hi there i am creating my project and i found a function force_bytes() in django. I don't know what are its uses. I've use it to send activation email to user. message = render_to_string('useraccounts/email_auth/email_verify.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': default_token_generator.make_token(user), }) -
How to return count value for corresponding query row in python django render template?
views.py def stu_view(request): ug = department.objects.all().filter(mode='UG') pg = department.objects.all().filter(mode='PG') for ug_cunt in ug: cnt = ug_reg.objects.filter(department = ug_cunt.pk).count() print(cnt) return render(request, "Student/stu_view.html", {"ug":ug, "pg":pg,"vl":cnt}) stu_view.html <table class="table table-bordered"> <thead> <tr> <th scope="col">Sl.No</th> <th scope="col">Programme</th> <th scope="col">Registered</th> </tr> </thead> <tbody> {% for dpt in ug %} <tr> <th scope="row">{{forloop.counter}}</th> <td>{{dpt.department}}</td> <td>{{vl}}</td> </tr> {% endfor %} </tbody> </table> **models.py** class ug_reg(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) gender = models.CharField(max_length=50) dob = models.DateField() department = models.ForeignKey(department, on_delete = models.CASCADE) address = models.CharField(max_length=50) stu_ph_ug = models.ImageField(null=True, blank=True) def __str__(self): return f"{self.pk} - {self.first_name} - {self.last_name} - {self.gender} - {self.dob} - {self.department} - {self.address} - {self.stu_ph_ug}" My question is how to return the count value based on a department like 2,1,1 but it was returned only 1,1,1 not increment the value, how will do it? -
Can't install GDAL on Heroku: Missing header files
I have been trying to deploy my Django app to Heroku but it keeps failing due to errors connected to Gdal. I ran into different problems in the process and found several suggestions, but none of them worked. Some things I tried:# Added several packages to Aptfile following different suggestions on SO and GitHub, but no success. Moved GDAL out of requirements.txt file since that seemed to cause additional errors. Also tried installing an older version of GDAL @ 2.2.0 since some comment suggested the system version should not be older than the Python package. Added environment variables as per this answer: https://gis.stackexchange.com/questions/28966/python-gdal-package-missing-header-file-when-installing-via-pip/64244#64244 I keep getting error messages about missing header files: Collecting GDAL==3.2.0 Downloading GDAL-3.2.0.tar.gz (602 kB) Building wheels for collected packages: GDAL Building wheel for GDAL (setup.py): started Building wheel for GDAL (setup.py): finished with status 'error' ERROR: Command errored out with exit status 1: command: /app/.heroku/python/bin/python -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-nttph3yx/GDAL/setup.py'"'"'; __file__='"'"'/tmp/pip-install-nttph3yx/GDAL/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d /tmp/pip-wheel-z6r3jxu4 cwd: /tmp/pip-install-nttph3yx/GDAL/ Complete output (71 lines): WARNING: numpy not available! Array support will not be enabled running bdist_wheel running build running build_py creating build creating build/lib.linux-x86_64-3.8 creating build/lib.linux-x86_64-3.8/osgeo copying osgeo/gnm.py -> build/lib.linux-x86_64-3.8/osgeo copying … -
how can i make more beautifull looks of form in forms.py in django?
default looks of form is so old, how can i make more nice looked form in tamplate from forms.py i made a form.py: class chg_pass(ModelForm): class Meta: model = Teacher_login_informa fields = ['Teacher_pass'] then views.py: from .forms import chg_pass def update_change_password(request): form = chg_pass() context = {'form':form} return render(request, 'change_password.html', context) in change_password.html tamplate: <form class="container pt-5" action="" method="POST">{% csrf_token %} {{form}} <button type="submit" class="btn btn-outline-success btn-sm">Submit</button> </form> -
Unable to open netsuite odbc on server
I have deployed the django project on ubuntu 20.04, nginx , gunicron. A part of the code is not able to run on the server it gives error ('01000', "[01000] [unixODBC][Driver Manager]Can't open lib '/opt/netsuite/odbcclient/lib64/ivoa27.so' : file not found (0) (SQLDriverConnect)") While the file is available :- xxxx@XXXXXX:/opt/netsuite/odbcclient/lib64$ ls ddtrc27.so ivmgan27.so ivmghu27.so ivoa27.so libicudata.so.42 libivoa27m.so libodbc.so openssl810.so ivldap27.so ivmgapi27.so ivoa27.ini libddicu27.so libicuuc.so.42 libodbcinst.so odbccurs.so It is working fine in the local server. And even in the Server terminal. But it gives error after starting nginx, gunicron service on the domain url. Everything else is working fine. Below output is from the server terminal ```usingh@NC-PH-0940-24:~$ python3 Python 3.8.5 (default, Jul 28 2020, 12:59:40) [GCC 9.3.0] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import pyodbc >>> host = 'xxxxx' >>> uid = "xxxxx" >>> role_id = 'xxxxx' >>> pwd = "xxxxx" >>> account_id = "xxxxx" >>> pyodbc.connect('DRIVER={NetSuite};Host='+host+';Port=1708;Encrypted=1;Truststore=/opt/netsuite/odbcclient/cert/ca3.cer;SDSN=NetSuite.com;UID='+uid+';PWD='+pwd+';CustomProperties=AccountID='+account_id+';RoleID='+role_id+'') <pyodbc.Connection object at 0x7f920414e2d0> >>> ``` The same code has been used inside the django project and it gives error when checking on domain(URL) after starting the nginx, gunicorn services. I have tried checking the available drivers using ```odbcinst -j`` the driver is available. Given +777 permission to the directory … -
How do i use the same email for user and profile model
I have two forms, one for signup and another for creating users. The difference is that the one for signup uses email verification while the one for adding patient does not. I noticed that whenever ii add patient the email that is saved to only my profile model and not my user model. This problem allows another user to use the same email address. i notice the same problem If i add users through the authorization section in the admin panel, the first name, last name and email field only save to the user model and not the profile model. models.py from django.db import models from django.contrib.auth.models import User from django.contrib.auth import get_user_model from django.db.models.signals import post_save from django.dispatch import receiver from django.conf import settings from django.utils.text import slugify from django.contrib.auth.models import AbstractBaseUser get_user_model().objects.filter(is_superuser=True).update(first_name='Super', last_name='User') # superusers = User.objects.filter(is_superuser=True) class Profile(AbstractBaseUser): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) last_name = models.CharField(max_length=100, blank=True) first_name = models.CharField(max_length=100, blank=True) middle_name = models.CharField(max_length=100, blank=True) last_name = models.CharField(max_length=100, blank=True) next_of_kin = models.CharField(max_length=100, blank=True) dob = models.DateField(max_length=10, blank=True,null=True) state = models.CharField(max_length=100, blank=True) password = models.CharField(max_length=100, blank=True) email = models.EmailField(max_length=150) signup_confirmation = models.BooleanField(default=False) address = models.CharField(max_length=255, null=True) country = models.CharField(max_length=255, null=True) phonenumber = models.CharField(max_length=20, null=True) appointment_with = models.ManyToManyField(User, related_name='appontment_with', … -
Pass variable through social authentication url
Before authenticating an user with Google in my page, I have an input that users can fill in with a special name, let's call this name variable nombrelink. When the user fills in the input and clicks submit, I send a fetch post request to the server to check wether that name is already taken or not. The problem is: when the person completes that input and THEN tries to sign up with google, I can't find a way to insert nombrelink into the database of the recently google created user. This is what happens on the server, to check wether the input name (nombrelink) is already taken or not. def landing(request): if request.method == "POST": content = json.loads(request.body) creator = Creador.objects.filter(url_name=content['nombrelink']).first() if not creator: content.update({"nadie": "nadie"}) return JsonResponse(content) else: return JsonResponse(content) return render(request, 'app1/landing.html') So in summary what the code should be doing is: The user fills in the input with a name that gets stored in nombrelink If nombrelink is not taken, then the user can register via google allauth nombrelink gets added to my google created user model I'm failing to implement point 3 -
Django writing custom upload handler to upload folder
Currently Django only supports uploading of files, but I would like to upload folders / subdirectories. I searched around and read that I would need to write a custom upload handler to support this. But I am not sure how to achieve this. I have read that Django doesn't support uploading of folder due to the way it takes the base name: def set_name(self, name): # Sanitize the file name so that it can't be dangerous. if name is not None: # Just use the basename of the file -- anything else is dangerous. name = os.path.basename(name) # File names longer than 255 characters can cause problems on older OSes. if len(name) > 255: name, ext = os.path.splitext(name) ext = ext[:255] name = name[:255 - len(ext)] + ext self._name = name -
combining multiple queryset based on conditions Django
I am using Djangofilterbackend and DjangoRestFramework. I am using url parameters to get the value and use it for my condition of which field should I filter. I have 30 possible parameters that a user can use. I am trying to combine filters based on if - else condition. This is the only solution I can think of. If you have any solution for this. please help me. U am just new to django This is my code. class NumberInFilter(filters.BaseInFilter, filters.NumberFilter): pass class ProductFilter(filters.FilterSet): manufacturer__in = NumberInFilter(field_name='manufacturer', lookup_expr='in') class Meta: model = Products fields = ['category', 'product_partnumber'] class ProductsView(viewsets.ModelViewSet): queryset = Products.objects.all() serializer_class = ProductsSerializers filter_backends = [filters.DjangoFilterBackend] filterset_class = ProductFilter def get_queryset(self): queryset = Products.objects.all() freq = self.request.query_params.get('specs', None) inloss = self.request.query_params.get('inloss', None) if freq is not None: queryset = queryset.filter(specifications__specification_id__exact=18, specifications__value__exact=freq) if inloss is not None: queryset = queryset.filter(specifications__specification_id__exact=28, specifications__value__exact=inloss) return queryset def create(self, request, *args, **kwargs): many = True if isinstance(request.data, list) else False serializer = ProductsSerializers(data=request.data, many=many) if serializer.is_valid(): serializer.save() product=serializer.data else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) return Response(product, status=status.HTTP_201_CREATED) my queryset are not combining. it just getting the last true on if statement. This is my model class Products(models.Model): product_partnumber = models.CharField(max_length=255) image_link = models.URLField(default=None, blank=True, null=True) … -
Related model cannot be resolved. Django, Djoser
I'm trying to extend the default Django User model and add custom fields in my authentication app, but when I try to run py manage.py migrate it prompt's an error saying it cannot find the 'authentication.User model. Btw I am using Djoser for my authentication. I get this error: >py manage.py migrate Operations to perform: Apply all migrations: admin, auth, authentication, authtoken, contenttypes, sessions Running migrations: Applying authentication.0001_initial...Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "D:\DJANGO-PROJECTS\chat_app\chat_app_env\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "D:\DJANGO-PROJECTS\chat_app\chat_app_env\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "D:\DJANGO-PROJECTS\chat_app\chat_app_env\lib\site-packages\django\core\management\base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "D:\DJANGO-PROJECTS\chat_app\chat_app_env\lib\site-packages\django\core\management\base.py", line 369, in execute output = self.handle(*args, **options) File "D:\DJANGO-PROJECTS\chat_app\chat_app_env\lib\site-packages\django\core\management\base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "D:\DJANGO-PROJECTS\chat_app\chat_app_env\lib\site-packages\django\core\management\commands\migrate.py", line 231, in handle post_migrate_state = executor.migrate( File "D:\DJANGO-PROJECTS\chat_app\chat_app_env\lib\site-packages\django\db\migrations\executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "D:\DJANGO-PROJECTS\chat_app\chat_app_env\lib\site-packages\django\db\migrations\executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "D:\DJANGO-PROJECTS\chat_app\chat_app_env\lib\site-packages\django\db\migrations\executor.py", line 245, in apply_migration state = migration.apply(state, schema_editor) File "D:\DJANGO-PROJECTS\chat_app\chat_app_env\lib\site-packages\django\db\migrations\migration.py", line 124, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "D:\DJANGO-PROJECTS\chat_app\chat_app_env\lib\site-packages\django\db\migrations\operations\models.py", line 92, in database_forwards schema_editor.create_model(model) File "D:\DJANGO-PROJECTS\chat_app\chat_app_env\lib\site-packages\django\db\backends\base\schema.py", line 322, in create_model sql, params = self.table_sql(model) File … -
Vue - turning off requests to /sockjs-node/info
I run Django and Vue together and the combination works fairly well. Django runs on http 8000 and webpack dev server chugs along on port 3000, JS or Vue changes get compiled automatically and I just have to reload the page (this is not an SPA app). Life is good. The only annoying bit is repeat requests like this: http://localhost:8000/sockjs-node/info?t=1607750560606 Now, Django doesn't find that resource so its log clutters up with 404. I actually coded a 410 instead, but, no Vue is just going to ping that 410 #urls.py url("^sockjs-node/info", views.nodeinfo), #views.py def nodeinfo(request): return HttpResponseGone() Now, I have tried to look for this. The answers on the Vue forum are multiple and most involve changing to vue.config.js, located next to package.json. After trying 2 or 3 of the suggestions, most of which don't seem to make much sense (a localhost question ends up with a "fix" consisting of a devserver entry pointing to 0.0.0.0 for example), none of them work. None of the threads I have seen seem to hold very authoritative answers. Or, more likely, I can't find the correct answer in all the noise that is being posted. I won't be running node in production, will … -
Why Is Django Not Serving My Static Folder In Development?
I am trying to serve some files from the static folder so a js script that runs in one of my templates can require it. Unfortunately, it seems to be picking which files to serve. (or something) It is not serving my js file, breaking my app. Another problem is that sometimes the favicon becomes missing before the first request is cached. I’ve noticed before in a deployed version of this app that I had to refresh the page after the first load. This is the output from the first request in the current development version: (python terminal output from the first request) ]09/Dec/2020 23:31:19] "GET /requestmap/ HTTP/1.1" 200 390 [09/Dec/2020 23:31:19] "GET /static/main.js HTTP/1.1" 404 1748 Not Found: /favicon.ico [09/Dec/2020 23:31:19] "GET /favicon.ico HTTP/1.1" 404 5727 (chrome conosole log from the first request): GET http://localhost:8000/static/main.js net::ERR_ABORTED 404 (Not Found) favicon.ico:1 GET http://localhost:8000/favicon.ico 404 (Not Found) ...and the output from the second request: (in the python console) [12/Dec/2020 04:05:53] "GET /requestmap/ HTTP/1.1" 200 390 [12/Dec/2020 04:05:54] "GET /static/main.js HTTP/1.1" 404 1761 (in the browser console) http://localhost:8000/static/main.js net::ERR_ABORTED 404 (Not Found) When I get the admin page all of the CSS and images seem to load fine, but any file that … -
Creating Proper Django Paths
Each group needs its own url in order to view, however, my understanding of constructing URL paths seems incomplete. What I currently have for each path containing "slug" does not work. I am attempting to make the final URL look along the lines of ".../groups/posts/in/group_name". urls.py app_name = 'groups' urlpatterns = [ path('', views.ListGroups.as_view(), name='all'), path('new/', views.CreateGroup.as_view(), name='create'), path('posts/in/<slug:groups>', views.SingleGroup.as_view(), name='single'), path('join/<slug>', views.JoinGroup.as_view(), name='join'), path('leave/<slug>', views.LeaveGroup.as_view(), name='join'), ] views.py from .models import Group, GroupMember # Create your views here. class CreateGroup(LoginRequiredMixin, generic.CreateView): fields = ['name', 'description'] model = Group class SingleGroup(generic.DetailView): model = Group class ListGroups(generic.ListView): model = Group class JoinGroup(LoginRequiredMixin, generic.RedirectView): def get_redirect_url(self, *args, **kwargs): return reverse('groups:single', kwargs={'slug':self.kwargs.get('slug')}) def get(self, request, *args, **kwargs): group = get_object_or_404(Group, slug=self.kwargs.get('slug')) try: GroupMember.objects.create(user=self.request.user, group=group) except IntegrityError: messages.warning(request, 'You are a already a member') else: messages.success(request, 'You are now a member') return super().get(request, *args, **kwargs) class LeaveGroup(LoginRequiredMixin, generic.RedirectView): def get_redirect_url(self, *args, **kwargs): return reverse('groups:single', kwargs={'slug':self.kwargs.get('slug')}) def get(self, request, *args, **kwargs): try: membership = GroupMember.objects.filter( user=self.request.user, group__slug=self.kwargs.get('slug') ).get() except GroupMember.DoesNotExist: messages.warning(request, 'You are not in this group') else: messages.success(request, 'You have successfully left this group') return super().get(request, *args, **kwargs) models.py User = get_user_model() register = template.Library() # Create your models here. class Group(models.Model): name = … -
Display particular data fields according to condition if there is data in the list in Django?
I am working on a project where the customer can order online for printing service on the product page I am providing all data about the product. And on the product page, I want to display the list of options if the data related to that product is available otherwise I want to hide that section if there is no data related to that product is available. *views.py def product(request, id): products = Product.objects.get(prod_ID=id) # initializing empty list sizeslist = [] AqutousCoatingProductlist = [] try: #trying to fetch data if it is available for that product sizesmap = SizeProductMapping.objects.filter(prod_id=id) sizeslist = [data.size_id.prod_size for data in sizesmap] except AttributeError as e: pass try: #trying to fetch data if it is available for that product AqutousCoatingProductmap = AqutousCoatingProductMapping.objects.filter(prod_id=id) AqutousCoatingProductlist = [data.aqutous_coating_id.prod_size for data in AqutousCoatingProductmap] except AttributeError as e: pass # sizeslist = SizeProductMapping.objects.filter(prod_id=id).values('size_id__prod_size') return render(request, "GalaxyOffset/product.html", {'products': products, 'sizeslist': sizeslist, "AqutousCoatingProductlist": AqutousCoatingProductlist}) product.html <div class="col-8"> <div class="card mx-2 my-2 border border-secondary"> <div class="row my-2"> {% if sizeslist is not null %} <!--trying to display this section if the sizelist is not null--> <div class="col-4 ml-4 mt-2"> <h4>Sizes : </h4> </div> <div class="col-4 mr-4 mt-2"> {% for s in sizeslist %} <input … -
Changing "extra" value in modelformset_factory using django form
Inside my views.py I have got a line of code, that has an extra value, that tell us a number of image fields, that I am able to use. ImageFormSet = modelformset_factory(Image, form=ImageForm, extra=3) Is there a way to change that extra fixed value from the form view? So when I click button add more it would change the value to +1. -
Keep duplicates when merging query sets (Django)
queryset = Profile.objects.none() for num in temp1: queryset |= Profile.objects.filter(subjects_key__contains='-'+str(num)+'-').exclude(user=self.request.user) So currently this code queries every value in the given temp1 array. Essentially I want to build a dynamic or query functionality regardless of the length of this array. It works well, but the only problem is I want to preserve the duplicates as I will need to access the count of them later. Thank you! TLDR: How can I keep duplicates when merging a query set? -
solve data in django
Iam try to write a for with data:[{'type': 'vSmart', 'name': 'vSmart', 'image': 'images/vsmart.png', 'count': 1, 'detailView': 'dialog', 'detailsURL': '/dataservice/device?personality=vsmart', 'statusList': [{'status': 'error', 'name': 'Error', 'detailView': 'dialog', 'detailsURL': '/dataservice/device?personality=vsmart&status=error', 'color': 'fa7c7d', 'icon': 'images/device/device-error.png', 'count': 0}, {'status': 'warning', 'name': 'Warning', 'detailView': 'dialog', 'detailsURL': '/dataservice/device?personality=vsmart&status=warning', 'color': 'f2ce60', 'icon': 'images/device/device-warning.png', 'count': 0}, {'status': 'normal', 'name': 'Normal', 'detailView': 'dialog', 'detailsURL': '/dataservice/device?personality=vsmart&status=normal', 'color': 'b0e276', 'icon': 'images/device/device-normal.png', 'count': 1}, {'status': 'new', 'name': 'Discovered device', 'detailView': 'dialog', 'detailsURL': '/dataservice/device?personality=vsmart&status=new', 'color': '7c8afa', 'icon': 'images/device/device-new.png', 'count': 0}]}, {'type': 'vbond', 'name': 'vbond', 'image': 'images/vbond.png', 'count': 1, 'detailView': 'dialog', 'detailsURL': '/dataservice/device?personality=vbond', 'statusList': [{'status': 'error', 'name': 'Error', 'detailView': 'dialog', 'detailsURL': '/dataservice/device?personality=vbond&status=error', 'color': 'fa7c7d', 'icon': 'images/device/device-error.png', 'count': 0}, {'status': 'warning', 'name': 'Warning', 'detailView': 'dialog', 'detailsURL': '/dataservice/device?personality=vbond&status=warning', 'color': 'f2ce60', 'icon': 'images/device/device-warning.png', 'count': 0}, {'status': 'normal', 'name': 'Normal', 'detailView': 'dialog', 'detailsURL': '/dataservice/device?personality=vbond&status=normal', 'color': 'b0e276', 'icon': 'images/device/device-normal.png', 'count': 1}, {'status': 'new', 'name': 'Discovered device', 'detailView': 'dialog', 'detailsURL': '/dataservice/device?personality=vbond&status=new', 'color': '7c8afa', 'icon': 'images/device/device-new.png', 'count': 0}]}, {'type': 'vEdge', 'name': 'vEdge', 'image': 'images/vedge.png', 'count': 4, 'detailView': 'dialog', 'detailsURL': '/dataservice/device?personality=vedge', 'statusList': [{'status': 'error', 'name': 'Error', 'detailView': 'dialog', 'detailsURL': '/dataservice/device?personality=vedge&status=error', 'color': 'fa7c7d', 'icon': 'images/device/device-error.png', 'count': 0}, {'status': 'warning', 'name': 'Warning', 'detailView': 'dialog', 'detailsURL': '/dataservice/device?personality=vedge&status=warning', 'color': 'f2ce60', 'icon': 'images/device/device-warning.png', 'count': 0}, {'status': 'normal', 'name': 'Normal', 'detailView': 'dialog', 'detailsURL': '/dataservice/device?personality=vedge&status=normal', 'color': 'b0e276', 'icon': 'images/device/device-normal.png', … -
Django datetime missing on edit page
i make a datetime input, but the problem when i make edit page, the datetime field empty.. views.py #update vechile armada def edit_vechile(request, no_pol): armada = Vechile.objects.get(no_polisi=no_pol) vechileform = VechileForm(instance=armada) if request.method == 'POST': vechileform = VechileForm(request. POST,request.FILES, instance=armada) if vechileform.is_valid(): vechileform.save() return redirect('arm-list') else: print(vechileform.errors) context = { 'vechileform': vechileform } return render(request, 'store/edit_arm.html', context) . models.py class Vechile(models.Model): no_polisi = models.CharField(max_length=10, unique=True) tanggal_stnk = models.DateField(null=True) . forms.py class VechileForm(forms.ModelForm): class Meta: model = Vechile fields = ['no_polisi','tanggal_stnk'] widgets = { 'no_polisi': forms.TextInput(attrs={'class': 'form-control', 'id': 'no_polisi'}), 'tanggal_stnk': forms.DateInput(attrs={'type': 'date', 'required':'true'}), . here my template edit_arm.html <form action="#" method="post" novalidate="novalidate" enctype="multipart/form-data"> {% csrf_token %} <div class="form-group row"> <label for="tanggal_stnk" class="col-sm-2 col-form-label">Tanggal STNK<a style='color:red'>*</a></label> <div class="col-sm-10"> {{ vechileform.tanggal_stnk }} </div> </div> </form> And here screenshoot of my edit page : Other field are return to edit page.. but why datefield missing on edit page ? Thanks -
Django sometimes does not cascade on delete
I have the following relevant models class GameOddORM(models.Model): game = models.ForeignKey(GameORM, on_delete=models.CASCADE, related_name='odds') # ... objects = GameOddQuerySet.as_manager() class Meta: constraints = [ models.UniqueConstraint(fields=['game', ...], name='unique_game_odd_idx') ] db_table = 'game_odds' class GameOddDifferenceORM(models.Model): game_id = models.BigIntegerField(null=False) left_odd = models.ForeignKey(GameOddORM, on_delete=models.CASCADE, related_name='left_odd_diff') right_odd = models.ForeignKey(GameOddORM, on_delete=models.CASCADE, related_name='right_odd_diff') value = models.FloatField() class Meta: constraints = [ models.Index(fields=['game_id'], name='diff_by_game_idx') ] db_table = 'game_odds_difference' Sometimes calling GameOddORM.objects.filter(...).delete() (there are no subqueries) results in the following exception django.db.utils.IntegrityError: (1451, 'Cannot delete or update a parent row: a foreign key constraint fails (`betsbot_db`.`game_odds_difference`, CONSTRAINT `game_odds_difference_left_odd_id_1043dadb_fk_game_odds_id` FOREIGN KEY (`left_odd_id`) REFERENCES `game_odds` (`id`))') That error is telling me a row of game_odds can't be deleted because there is a foreign key in game_odds_difference referencing it. Well I set ON DELETE CASCADE in GameOddsDifferenceORM model, so that error should not happen, in fact it happens just sometimes. That makes me think it's a concurrency issue because GameOddORM insertions and deletions are concurrent. Is Django failing to emulate ON DELETE CASCADE because after deleting the rows of game_odds_difference new rows may be added in between? The database has no triggers and I am not making raw queries. I am using Django 2.2.12, mysqlclient 1.4.6, MySQL 8.0.21, InnoDB database engine and Python … -
Ideas on how I can plot points in leaflet map near my location
I am trying to develop a web app that gets the users location and plots shops within a certain radius. I've hit a wall with how I can plot more points over just the users location. I will show some files I feel are the most relevant. I am using Leafletjs and I have a model called Shop that is populated with data I generated on https://overpass-turbo.eu/. I was following this tutorial (https://realpython.com/location-based-app-with-geodjango-tutorial) but im not sure how I would plot these points on the map, it suggests using the GeoLocation API but im curious if there is another way views.py from world.forms import LoginForms from django.shortcuts import render, redirect from django.contrib import messages from .forms import UserRegistrationForm from django.http import JsonResponse from django.contrib.auth.decorators import login_required from . import models from django.contrib.gis.geos import Point def index(request): template = 'base.html' user = LoginForms() if user.is_valid(): user.save() render(request, "registration/login.html", {'form': user}) return redirect(template) else: return render(request, "registration/login.html", {'form': user}) def register(request): if request.method == 'POST': # if the form has been submitted form = UserRegistrationForm(request.POST) # form bound with post data if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request, f'Account created for {username}!') return redirect('login') else: form = UserRegistrationForm() return render(request, 'registration/register.html', {'form': … -
Django server reload doesn't work for every .py file
I'm starting the django server with python manage.py runserver The output is following Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). In my django app I have a file named services.py and one is called schedules.py. When I make changes in the services.py file the reload works as expected, in schedules.py file changes do not lead to a server reload. Why is that? As a further information in my schedules.py file I have a schedule, which is not working: from django_q.tasks import schedule schedule('api.shared.tasks.send_order_reminder', schedule_type='I', repeats=-1) Having the same code in the services.py file creates a schedule -
django object destructuring and delete
I'm making an ecommerce web app with django. My issue is on the payment, I'm trying to remove the product or change a boolean field on that product. Usually handling shopping carts stock has been easier, but these products are cards and need to be unavailable asap. Please take a look, anything helps! I'm not doing a good job of destructuring these objects, theres a manytomany field on Payment. So they're accessible Models class Payment(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE, related_name='payments') payment_method = models.CharField(max_length=20, choices=( ('Paypal', 'Paypal'), )) timestamp = models.DateTimeField(auto_now_add=True) successful = models.BooleanField(default=False) amount = models.FloatField() raw_response = models.TextField() stocks = models.ManyToManyField(Product) def __str__(self): return self.reference_number def out_stock(self): return self.stocks - 1 @property def reference_number(self): return f"PAYMENT-{self.order}-{self.pk}" def get_price(self): return self.product.price views class ConfirmOrderView(generic.View): def post(self, request, *args, **kwargs): order = get_or_set_order_session(request) body = json.loads(request.body) payment = Payment.objects.create( order=order, successful=True, raw_response=json.dumps(body), amount=float(body['purchase_units'][0]['amount']["value"]), payment_method='Paypal' ) order.ordered = True order.ordered_date = datetime.date.today() order.save() tick = payment.stocks print(tick) products = Product.objects.filter() return JsonResponse({"data": "Success"})