Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to iterate through an array and add an element to the end
I create a local site for myself . I have a form that creates a user in the database . Then you need to log in to your account so to speak and fill out the second form, we get an object from the database using name (field in the database ) = form. I want after getting this object, I went through the array and moved the object to the very end, so that I could then get it using -id[0] -
standard_init_linux.go:211: exec user process caused "no such file or directory"?
Dockerfile FROM python:3.7.4-alpine ENV PYTHONUNBUFFERED 1 ENV PYTHONDONTWRITEBYTECODE 1 ENV LANG C.UTF-8 MAINTAINER Nurbek Batyrzhan "foto.nurbek@gmail.com" RUN apk update && apk add postgresql-dev gcc musl-dev RUN apk --update add build-base jpeg-dev zlib-dev RUN pip install --upgrade setuptools pip RUN mkdir /code WORKDIR /code COPY requirements.txt /code/ RUN pip install -r requirements.txt COPY . /code/ #CMD ["gunicorn", "--log-level=DEBUG", "--timeout 90", "--bind", "0.0.0.0:8000", "express_proj.wsgi:application"] ENTRYPOINT ["./docker-entrypoint.sh"] docker-entrypoint.sh #!/bin/bash # Prepare log files and start outputting logs to stdout touch /code/gunicorn.log touch /code/access.log tail -n 0 -f /code/*.log & # Start Gunicorn processes echo Starting Gunicorn. exec gunicorn express_proj.wsgi:application \ --name express \ --bind 0.0.0.0:8000 \ --log-level=info \ --log-file=/code/gunicorn.log \ --access-logfile=/code/access.log \ --workers 2 \ --timeout 90 \ "$@" Getting Error standard_init_linux.go:211: exec user process caused "no such file or directory" Need help. Some saying to use dos2unix(i do not know hoe to use it.) -
Update a queryset in django
I need to update the data on the database once I get all the values of that data with current DateTime..i.e My Model: class Load_Balancing(models.Model): instance_name = models.CharField(max_length=100) instance_visit = models.DateTimeField(null=True) sequence = models.IntegerField() I want to get the value with the last sequence number inserted in the database and update its time to the current time. I tried: instances = Load_Balancing.objects.all().order_by("-sequence")[:1] a = Load_Balancing.objects.filter(sequence=instances.sequence).update(instance_visit= datetime.datetime.now()) But it's not working. -
Why is my form not being saved to admin database?
Hi I'm trying to develop a website for an online store using Django. I want to use Ajax to handle the view of my checkout form after it has been submitted. After the form is submitted, I want it to go to : return HttpResponseRedirect(reverse(str(next_page))+"?address_added=True") , i.e http://127.0.0.1:8000/checkout/?address_added=True But for some reason, it is not going there. Rather it's being redirected to http://127.0.0.1:8000/checkout/?csrfmiddlewaretoken=W4iXFaxwpdtbZLyVI0ov8Uw7KWOM8Ix5GcOQ4k3Ve65KPkJwPUKyBVcE1IjL3GHa&address=123+Main+Street&address2=&state=MA&country=USA&zipcode=55525&phone=%28877%29+314-0742&billing=on As a result, the form data is also not getting saved. I was thinking if it were because of the new version of Django. What I want to do is that after they submit the place order button, the form is going to be None, i.e disapper and then I would add a credit card form there for payment. But it is not happening. What is wrong here? Can anyone please help me out of this or is there a better way to do this? My forms.py: class UserAddressForm(forms.ModelForm): class Meta: model = UserAddress fields = ["address", "address", "address2", "state", "country", "zipcode", "phone", "billing"] My accounts.views.py: def add_user_address(request): try: next_page = request.GET.get("next") except: next_page = None if request.method == "POST": form = UserAddressForm(request.POST) if form.is_valid(): new_address = form.save(commit=False) new_address.user = request.user new_address.save() if next_page is not None: … -
Coloring specific values based on condition in Django thorugh CSS in html template
formula.py funct(): apple=[2.3,4.6,7.5] orange=[3.1,5.6,7.8] jam=list(map(lambda a,o: round((a/o),3) if o else 0, apple,orange)) return (apple,orange,jam) views.py def view(request): forma = SimpleForm(request.POST) if request.method == "POST": if forma.is_valid(): forma = forma.save() box = form.box garden=Garden.objects.get(fruit=box) formula=funct() context={'formla':formula,'garden':garden} template.html <table> <tr><th>Jam Recipe</th>{% for item in jam %}{% if item>2 %}<td class="green">{{ item }}</td> {% endif %}{% endfor %}</tr></table> css: .green {color: green;} I want to color the table in template.html in green color if values in list jame in the table more than 2. I wrote the above code, color it does not color my table some values in green. What is wrong and how to fix it ? What i am missing? Any help is appreciated. -
django formset error : "ManagementForm data is missing or has been tampered with"
I trying to do some crud using Django formset but I get this error "ManagementForm data is missing or has been tampered with", if I change the data management tag to {{ formset.management_form}} then the error is gone but nothing happens, I got no data displayed, so what to do? views.py : def view(request): achat = Achats.objects.all() form = formset_factory(AssociationForm,extra=1) formset = form(request.POST or None) if formset.is_valid(): for form in formset: print(form.cleaned_data) return render(request, 'html.html', {'Achats': achat, 'formset': formset}) forms.py : class AssociationForm(forms.ModelForm): class Meta: model = Association fields = ('Id_Achats', 'Id_Article', 'Prix_Unitaire', 'Quantite') html {% load widget_tweaks %} {% for form in formset %} <form method="POST" enctype="multipart/form-data"> {{ formset.management_data}} {% csrf_token %} <td>{% render_field form.Id_Achats class="form-control" %}</td> <td>{% render_field form.Id_Article class="form-control" %}</td> <td>{% render_field form.Prix_Unitaire class="form-control" %}</td> <td>{% render_field form.Quantite class="form-control" %}</td> <input type="submit" value="Submit"> </form> {% endfor %} -
Django - Reverse for 'processinglist' with arguments '('',)' not found. 1 pattern(s) tried: ['processing/(?P<pk>[0-9]+)/$']
I am learning Django by following some tutorials, along with Django official doc. I have an issue with reverse URL. It just does not seem to be working out for me, hence I'm looking for some help. Here's my models.py from django.db import models from django.urls import reverse class ProcessingActivityTopType(models.Model): type = models.CharField(max_length=200) def get_absolute_url(self): return reverse('processinglist', args=[str(self.id)]) def __str__(self): return self.type class ProcessingActivity(models.Model): class Meta: verbose_name_plural = 'Processing Activities' processing_toptype = models.ForeignKey(ProcessingActivityTopType, on_delete=models.CASCADE, related_name='processingactivities') processing_type = models.CharField(max_length=200) processing_purpose = models.CharField(max_length=200) processing_category = models.ManyToManyField('PersonalData', related_name='processing_category') processing_legalbasis = models.ForeignKey(LegalBasis, on_delete=models.CASCADE, related_name='legal_basis') processing_retention = models.CharField(max_length=200) processing_datasubject = models.CharField(max_length=200) processing_transfers = models.CharField(max_length=200) processing_security = models.CharField(max_length=200) def __str__(self): return self.processing_type Here's my views.py from django.shortcuts import render, get_object_or_404 from django.views import generic from .models import ProcessingActivityTopType, ProcessingActivity class ProcessingActivityListView(generic.ListView): model = ProcessingActivityTopType class ProcessingListByTopType(generic.ListView): model = ProcessingActivity def get_queryset(self): id = self.kwargs['pk'] target_toptype=get_object_or_404(ProcessingActivityTopType, pk = id) return ProcessingActivity.objects.filter(processing_toptype=target_toptype) def get_context_data(self, **kwargs): context = super(ProcessingListByTopType, self).get_context_data(**kwargs) context['processings'] = get_object_or_404(ProcessingActivityTopType, pk = self.kwargs['pk']) return context Here's my urls.py from django.urls import path, include from . import views urlpatterns = [ path('processings/', views.ProcessingActivityListView.as_view(), name='toptypes'), path('processing/<int:pk>', views.ProcessingListByTopType.as_view(), name='processinglist'), ] Here's my html template <div class="row"> {% for i in processingactivitytoptype_list %} <div class="col-md-4"> <div class="card mb-2"> <div class="card-body"> … -
Django: NoReverseMatch error when trying to pass two url parameters
I am working on a project and I am a beginner in Django. In the project, the user can create product posts and other users can upvote it. I am working on the thing that the user can delete the post created by himself. I don't know what are the best practices for it but I am trying this method. this is usersposts.html {% for product in products.all %} {% if product.hunter.username == user.username %} #extra code here--- <a class="btn btn-md btn-outline-danger btn-block font-weight-bolder h5" href="{% URL 'deletepost' user.id product.id %}">delete</a> {% endif %} {% endfor %} this is urls.py urlpatterns = [ #more URLs here---- path('deletepost/<int:user_id>/<int:product_id>/', views.deletepost, name='deletepost'), ] this is the view function for deletepost @login_required(login_url="/accounts/signup") def deletepost(request, user_id, product_id): if request.method == 'POST': user = get_object_or_404(User, pk = user_id) if user.check_password(request.POST['password']): product = get_object_or_404(Product, pk = product_id) product.delete() messages.success(request, 'post deleted successfully!') return render(request,'products/home.html') else: messages.error(request, 'password is incorrect !') return render(request,'products/deletepost.html') else: return render(request,'products/deletepost.html') this should work I think but I don't know what I am doing wrong that I am getting this error NoReverseMatch at /products/deletepost/17/4/ Reverse for 'deletepost' with arguments '(17, '')' not found. 1 pattern(s) tried: ['products\\/deletepost\\/(?P<user_id>[0-9]+)\\/(?P<product_id>[0-9]+)\\/$'] Request Method: GET Request URL: http://127.0.0.1:8000/products/deletepost/17/4/ … -
How to float the label to the left and span to the right in the line?
This is what the current code looks right now, I don't know why isn't it working any help is appreciated, Thanks! label { font-family: Segoe UI; font-size: 18px; font-weight: lighter; color: #1E1E1E; } .field1 { font-family: inherit; margin-bottom: 25px; display: flex; justify-content: space-between; } <div class="field1"> <label>Username</label> <span class="holder">{{ form.username }}</span> </div> -
am having this error in my django project
Traceback (most recent call last): File "C:\Users\HP\AppData\Local\Programs\Python\Python38-32\lib\urllib\request.py", line 1319, in do_open h.request(req.get_method(), req.selector, req.data, headers, File "C:\Users\HP\AppData\Local\Programs\Python\Python38-32\lib\http\client.py", line 1230, in request self._send_request(method, url, body, headers, encode_chunked) File "C:\Users\HP\AppData\Local\Programs\Python\Python38-32\lib\http\client.py", line 1276, in _send_request self.endheaders(body, encode_chunked=encode_chunked) File "C:\Users\HP\AppData\Local\Programs\Python\Python38-32\lib\http\client.py", line 1225, in endheaders self._send_output(message_body, encode_chunked=encode_chunked) File "C:\Users\HP\AppData\Local\Programs\Python\Python38-32\lib\http\client.py", line 1004, in _send_output self.send(msg) File "C:\Users\HP\AppData\Local\Programs\Python\Python38-32\lib\http\client.py", line 944, in send self.connect() File "C:\Users\HP\AppData\Local\Programs\Python\Python38-32\lib\http\client.py", line 1392, in connect super().connect() File "C:\Users\HP\AppData\Local\Programs\Python\Python38-32\lib\http\client.py", line 915, in connect self.sock = self._create_connection( File "C:\Users\HP\AppData\Local\Programs\Python\Python38-32\lib\socket.py", line 808, in create_connection raise err File "C:\Users\HP\AppData\Local\Programs\Python\Python38-32\lib\socket.py", line 796, in create_connection sock.connect(sa) During handling of the above exception ([WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond), another exception occurred: File "C:\Users\HP\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\HP\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\HP\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\HP\Desktop\video\vid\videodownloader\views.py", line 14, in download YouTube(url).streams.first().download(homedir +'/Downloads') File "C:\Users\HP\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pytube\streams.py", line 226, in download if skip_existing and self.exists_at_path(file_path): File "C:\Users\HP\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pytube\streams.py", line 260, in exists_at_path return os.path.isfile(file_path) and os.path.getsize(file_path) == self.filesize File "C:\Users\HP\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pytube\streams.py", line 146, in filesize self._filesize = request.filesize(self.url) File "C:\Users\HP\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pytube\request.py", line 76, in … -
Django edit the admin template for models
I am new to Django and working on a project. I have these models class Test(models.Model): name = models.CharField(max_length=255) description = models.CharField(max_length=255, blank=True) applicable_device = models.ManyToManyField(Device) applicable_platform = models.ManyToManyField(Platform) class Meta: verbose_name = 'Test' verbose_name_plural = 'Tests' def __str__(self): return self.name 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) When I go to the Event section in the Django Admin Panel I am able to edit the events. But I want to be able to see a list of all the properties that apply to it underneath where I edit the event. Is this possible? -
Django: get current URL path to use in a form
I have been stuck on this for a while now. I need to extract the current domain name of the tenant in order to use as a parameter to upload data in this tenant schema. I am struggling to make this work because of the structure of my view. This is what I have been able to do so far forms.py class ETL(forms.Form): Historical = forms.FileField() Pre_processing = forms.FileField() Supplier = forms.FileField() parameters = forms.FileField() def process_data(self, request ,*args, **kwargs): url = request.get_full_path() print(url) dbschema = remove_www(request.get_host().split(':')[0]).lower() print(url) fh = io.TextIOWrapper(self.cleaned_data['Historical'].file) fpp = io.TextIOWrapper(self.cleaned_data['Pre_processing'].file) fs = io.TextIOWrapper(self.cleaned_data['Supplier'].file) fp = io.TextIOWrapper(self.cleaned_data['parameters'].file) ........ and my view.py @method_decorator(login_required, name='dispatch') class Getfiles(LoginRequiredMixin,FormView): template_name = 'upload.html' form_class = ETL success_url = 'Home' def form_valid(self, form): form.process_data() print('data_processed well') return super().form_valid(form) with this view format, I am struggling on how to pass the request.get_hosts() inside of the view. How can I can fix it? Is this a proper way to get the schema name or is there a better way to get the tenant schema in the form? -
How do I change the location to where pip install site-package modules?
I'm using Ubuntu 18.04 and Python 3.6. Whenever I try and install pip packages, pip installs them to my home directory instead of the virtual environment where I want them. I have tried reinstalling python3, pip, and re-creating the virtual environment (as well as deactivating and reactivating it). This is roughly what happens ,I try and install modules from my requirements file, and they appear to be installed successfully ... (venv) davea@chicommons-laboratory:/var/www/html/web$ /var/www/html/web/venv/bin/python3 -m pip install -r requirements.txt Collecting asgiref==3.2.3 (from -r requirements.txt (line 1)) Using cached https://files.pythonhosted.org/packages/a5/cb/5a235b605a9753ebcb2730c75e610fb51c8cab3f01230080a8229fa36adb/asgiref-3.2.3-py2.py3-none-any.whl Collecting attrs==19.3.0 (from -r requirements.txt (line 2)) Using cached https://files.pythonhosted.org/packages/a2/db/4313ab3be961f7a763066401fb77f7748373b6094076ae2bda2806988af6/attrs-19.3.0-py2.py3-none-any.whl Collecting Babel==2.8.0 (from -r requirements.txt (line 3)) Using cached https://files.pythonhosted.org/packages/15/a1/522dccd23e5d2e47aed4b6a16795b8213e3272c7506e625f2425ad025a19/Babel-2.8.0-py2.py3-none-any.whl Collecting click==7.1.1 (from -r requirements.txt (line 4)) Using cached https://files.pythonhosted.org/packages/dd/c0/4d8f43a9b16e289f36478422031b8a63b54b6ac3b1ba605d602f10dd54d6/click-7.1.1-py2.py3-none-any.whl Collecting click-plugins==1.1.1 (from -r requirements.txt (line 5)) Using cached https://files.pythonhosted.org/packages/e9/da/824b92d9942f4e472702488857914bdd50f73021efea15b4cad9aca8ecef/click_plugins-1.1.1-py2.py3-none-any.whl Collecting cligj==0.5.0 (from -r requirements.txt (line 6)) Using cached https://files.pythonhosted.org/packages/e4/be/30a58b4b0733850280d01f8bd132591b4668ed5c7046761098d665ac2174/cligj-0.5.0-py3-none-any.whl Collecting Django==2.0 (from -r requirements.txt (line 7)) Using cached https://files.pythonhosted.org/packages/44/98/35b935a98a17e9a188efc2d53fc51ae0c8bf498a77bc224f9321ae5d111c/Django-2.0-py3-none-any.whl Collecting django-address==0.2.1 (from -r requirements.txt (line 8)) Collecting django-extensions==2.2.8 (from -r requirements.txt (line 9)) Using cached https://files.pythonhosted.org/packages/c9/9f/c780e0360fb10a36b519d015096d93311088fcec4874a9238bb8996013dc/django_extensions-2.2.8-py2.py3-none-any.whl Collecting django-mysql==3.3.0 (from -r requirements.txt (line 10)) Using cached https://files.pythonhosted.org/packages/eb/4a/62b2eb9f0b94541161b0e7d355bea89f5b2273e146f5b3a30e728adb9ce2/django_mysql-3.3.0-py3-none-any.whl Collecting django-phonenumber-field==4.0.0 (from -r requirements.txt (line 11)) Using cached https://files.pythonhosted.org/packages/1f/2d/330ae13ceef7d9b083aa61b82779daec6afe4d66ae88adf968adcc6b752c/django_phonenumber_field-4.0.0-py3-none-any.whl Collecting djangorestframework==3.11.0 (from -r requirements.txt (line 12)) Using cached https://files.pythonhosted.org/packages/be/5b/9bbde4395a1074d528d6d9e0cc161d3b99bd9d0b2b558ca919ffaa2e0068/djangorestframework-3.11.0-py3-none-any.whl Collecting Fiona==1.8.13.post1 (from -r requirements.txt … -
Using Django and Postgres to store phone numbers
I currently want to make a web app in django with a form that asks a user to input a phone number and submit, and I want that number they submit to be stored in a database using postgres. I'm having a hard time finding information on how to use post requests in django to connect to postgres. index.html <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Test Form 1</title> </head> <body> <form method="post">{% csrf_token %} {{ form.as_p }} <input type="submit" value="Send message"> </form> </body> </html> admin.py from django.contrib import admin from .models import Post admin.site.register(Post) urls.py from django.contrib import admin from django.urls import path # from main.views import first from main import views as test_app_views urlpatterns = [ path('admin/', admin.site.urls), # path('', first) path('', test_app_views.FormView1.as_view()) ] forms.py from django import forms from phone_field import PhoneField from main.models import Post class HomeForm(forms.ModelForm): phone = PhoneField() class Meta: model = Post fields = ('phone',) models.py from django.db import models from phone_field import PhoneField from django.contrib.auth.models import User class Post(models.Model): phone = PhoneField() user = models.ForeignKey(User, on_delete=models.CASCADE,) views.py from django.shortcuts import render from django.views.generic.edit import FormView from .forms import HomeForm class FormView1(FormView): template_name = 'index.html' # form_class = … -
Keep Slug uniques when they depend on another slug
My webpage has some urls like this, /<slug1>/<slug2>/slug3>/, where the slugs belong to distinct models respectively. Basically I cannot allow for slug1 to be repeated at anypoint, and that's easy I'll just use unique_slugify. However slug2 must be unique if and only if it belongs to the same slug1, so pizza/pepperoni/ and pizza/pepperoni/, are not valid if each "pepperoni" slug belongs to a different object. However if there were 2 distinct objects such that the final slug ended up being pizza/pepperoni/ and pasta/pepperoni/ that would be absolutely fine. However making the SlugField in the model be unique=True, won't allow for the slugs to be the same even if they do belong to different objects. The only workaround I've thought for this is making each slug directly dependent on its previous one, such that slug2=unique_slugify(slug1+object2.name), and then slug3=unique_slugify(slug2+object3.name). Still this makes the urls way less intuitive as you could still end up with urls that would be the same on slug3, and would need numbers or stuff like taht to be different. For instance: /spa/spanish/spanishsausage/ and /span/spanishsau/spanishsausage/, where slug3 is identical in both. Therefore is there anyway I can make slugs such that slug3 only has to be unique for 2 … -
Django User losing groups (but not permissions) upon login
We're having an issue where upon login, a user is losing all assigned groups. Example: I give User a Group through the Django Admin Page The User logs out using the Django logout function, deleting all Session data (User still has groups at this point) The User logs back in, and this is when Group is lost. Any pointers will be appreciated. -
Model is either not installed, or is abstract - Django, Python
when i am migrating the code below i get the following error ----ERRORS: users.UserStripe.user: (fields.E300) Field defines a relation with model 'settings.AUTH_USER_MODEL', which is either not installed, or is abstract. users.UserStripe.user: (fields.E307) The field users.UserStripe.user was declared with a lazy reference to 'settings.auth_user_model', but app 'settings' isn't installed.--- I understand that it relates to the fact i have 'user' in the stripe and profile class but I'm not sure how to stop the error. any guidance would be appreciated! models.py - users import stripe from django.db import models from django.conf import settings from django.contrib.auth.models import User stripe.api_key = '****************' class UserStripe(models.Model): **user = models.OneToOneField('settings.AUTH_USER_MODEL', on_delete=models.CASCADE)** stripe_id = models.CharField(max_length=120) def __str__(self): return str(self.stripe_id) class Profile(models.Model): **user = models.OneToOneField(User, on_delete=models.CASCADE)** image = models.ImageField(default='', upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile' -
URL Patterns issue with Path statements
I'm following a Django/Python online course which is a little dated using URL statements instead of path statements. I'm getting the following error. The code segment is below as well. Please help. Thanks so much! enter image description here enter image description here -
Django server fails to start in webbrowser
I am trying to run a Django Project, using PayCharm. Here what I get: And when I klick on the Link, I see the following: How can I resolve this Problem? -
django image not loading from media_root
i am making a products page for an ecommerce project, i have already successfully loaded the images using django admin into an image directory in the base root of my project. The challenge am currently facing is that when i try to display the product images on the shop products page it does not work. how do i make it work ? my setttings.py file looks like this: MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR ,'media') STATIC_URL = '/static/' STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'static','static_root') STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static_files'), ] TEMPLATE_DIRS = [ os.path.join(BASE_DIR, 'templates'), ] my urls.py file looks like this: from django.contrib import admin from django.urls import path from django.conf import settings from django.conf.urls.static import static from products.views import home, all_products_view urlpatterns = [ path('',home, name="home"), path('products/',all_products_view, name="all_products"), path('admin/', admin.site.urls), ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, ducument_root = settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, ducument_root = settings.MEDIA_ROOT) below is a code for products template where the images are supposed to be loaded {% extends "base.html" %} {% block products %} {% for product in products %} <div class="col-lg-3"> <div class="card-deck"> <div class="card p-2 mb-2"> {% for item in product.productimage_set.all %} <img src="{{ item.image.url }}'" alt=""> {% endfor %} </div> </div> </div> {% … -
Function doesn't call another function in Django views
I have a chain of functions, that i need to execute consistently like this: user_profile() -> deposit_counter() -> test() However, my test function is not executing. What is wrong with it? def user_profile(request): try: print('deposit counter') deposit_counter(request) except Profile.DoesNotExist: return render(request, "../templates/profile.html") def deposit_counter(request): deposit_object = Deposits.objects.get(id=request.user.profile.deposits.id) deposit_type_object = getattr(deposit_object, 'deposit_type') if deposit_type_object == Deposits.DEPOSIT_TYPE[0][0]: tax = 13 Deposits.objects.update(tax_rate=13) percentage = 0.11 print('i am hit') test(request, percentage, tax) def test(request, percentage, *args): deposit_object = Deposits.objects.get(id=request.user.profile.deposits.id) deposit_value_object = getattr(deposit_object, 'deposit_value') deposit_creating_date = getattr(deposit_object, 'deposit_creating_date') deposit_end_date = getattr(deposit_object, 'deposit_end_date') deposit_income = deposit_value_object * (percentage/100) * (args / 100) Deposits.objects.update(temporary_deposit_income=deposit_income, temporary_total_income=(deposit_income + deposit_value_object)) print('I am here') if deposit_creating_date == deposit_end_date: Deposits.objects.update(deposit_income=deposit_income, total_income=(deposit_income + deposit_value_object), temporary_deposit_income=None, temporary_total_income=None) Account.objects.update(current_balance=(deposit_income + deposit_value_object)) -
Django: all auth create account with email - unique constraint failed. Display message instead of giving an error
I am using djnago all-auth to create custom user accounts. When creating an account with email and password, if account with a email already exits it gives an error (UNIQUE constraint failed: account_emailaddress.email) but I would like to display message that an account with this email already exists instead of throwing an error. What is the best way to handle this? In general I would use AJAX to verify and display message for my own views but I do not know how to deal here with django all-auth package. -
PostgreSQL Function not working with WHERE clause
I am trying to make a function in postgres to make my queries faster compared to Django ORM. But the problem I am facing is results are coming when there is no WHERE clause in the query. This is the function and its call which yeilds 0 rows: CREATE OR REPLACE FUNCTION public.standard_search(search_term text, similarity_to integer) RETURNS TABLE(obj_id integer, app_num integer, app_for text, similarity integer) LANGUAGE 'plpgsql' AS $BODY$ DECLARE similarity integer; BEGIN RETURN QUERY SELECT mark.id, mark.app_num, mark.app_for::text, levenshtein($1, focusword.word) AS similarity FROM mark INNER JOIN focusword ON (mark.id = focusword.mark_id) WHERE similarity <= $2 ORDER BY similarity, mark.app_for, mark.app_num; END $BODY$; select * from public.standard_search('millennium', 4) This is the function and its call which is giving me results but is slow as the filtering is done in the function call: CREATE OR REPLACE FUNCTION public.standard_search(search_term text, similarity_to integer) RETURNS TABLE(obj_id integer, app_num integer, app_for text, similarity integer) LANGUAGE 'plpgsql' AS $BODY$ DECLARE similarity integer; BEGIN RETURN QUERY SELECT mark.id, mark.app_num, mark.app_for::text, levenshtein($1, focusword.word) AS similarity FROM mark INNER JOIN focusword ON (mark.id = focusword.trademark_id) ORDER BY similarity, trad.app_for, mark.app_num; END $BODY$; select * from public.standard_search('millennium', 4) where similarity <= 4 Can anyone shed some light on what is … -
Django/Python - How do I get a count of records in a model where an @property function is True?
I'm very new to python and django and I'm working on a version of the locallibrary project to learn some concepts. I've created a model with an @property to show when an item is overdue: @property def overdue(self): is_overdue = False if (datetime.date.today() > self.due_date) and self.status != 'c': is_overdue = True return is_overdue I would like to get a count of all items where overdue=True. In templates I can use 'overdue' as if it were a field, however, trying to use is in a view like this... num_actions_overdue = Action.objects.filter(overdue='True').count() ...throws an error: Cannot resolve keyword 'overdue' into field. Is there a simple way to count all overdue records? Thanks in advance for any help! -
How to configure django to run on apache
Been having problems for the last 3 days with this... I was able to install and run apache on CentOs machine, I can run simple html or wsgi files, my problem is when I try to run django, django project runs ok with manage.py runserver, but when configuring the wsgi.py file and the .config, I start to having problems on the website (500 error); error_log; [Mon Apr 20 09:59:59.532476 2020] [:error] [pid 31466] [client 10.5.230.111:59479] File "/srv/www/example/mysite/mysite/wsgi.py", line 14, in [Mon Apr 20 09:59:59.532591 2020] [:error] [pid 31466] [client 10.5.230.111:59479] from django.core.wsgi import get_wsgi_application [Mon Apr 20 09:59:59.532627 2020] [:error] [pid 31466] [client 10.5.230.111:59479] ImportError: No module named django.core.wsgi example.config; WSGIDaemonProcess python-home=/var/www/django/env/ python-path=/srv/www/example/mysite:/var/www/django/env/lib/python3.6/site-packages WSGIProcessGroup %{GLOBAL} WSGIScriptAlias /exam /srv/www/example/mysite/mysite/wsgi.py <Directory /srv/www/example/mysite/mysite> <Files wsgi.py> Require all granted </Files> </Directory> # Django static files, here you must specify your own path's Alias /static/ /srv/www/example/mysite/static/ <Directory "/srv/www/example/mysite/static"> Require all granted </Directory> wsgi; import os import sys import site for root, _, files in os.walk('/usr/local/lib/python3.4/site-packages/django'): for f in files: os.system('dos2unix %s' % abspath(join(root, f))) from django.core.wsgi import get_wsgi_application site.addsitedir("/var/www/django/env/lib/python3.6/site-packages") sys.path.append("/srv/www/example/mysite") sys.path.append("/srv/www/example/mysite/mysite") activate_this = "/var/www/django/env/bin/activate_this.py" with open(activate_this) as f: code = compile(f.read(), activate_this, "exec") exec(code, dict(file=activate_this)) os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings') application = get_wsgi_application() Already tried multiple things (https://www.slideshare.net/GrahamDumpleton/getting-started-with-modwsgi, …