Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Unable to access / var / tmp in Subprocess via Django
I created a script that outputs the execution result of a shell script to a Web screen using Django and subprocess of python. Specifically, the following two scripts were created. test.py #!/usr/bin/python import sys,os import subprocess import syslog command_list = ['/bin/sh', '/var/tmp/test.sh'] proc = subprocess.Popen(args=command_list, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=os.path.dirname(command_list[0]), shell=False) result = proc.communicate(input=None) print str( result ) test.sh #!/bin/bash echo "begin" cat /var/tmp/data.txt data.txt data1 data2 Unit tests were performed on the two scripts, and they were confirmed to work properly. However, when I used test.py via Django, test.sh's "cat" command and data.txt existed, “Cat: /var/tmp/data.txt: No such file or directory” is displayed. What is the cause? version python 2.7.13 Django 1.11.20 -
Why do I get 'detail: not found' for primary key formatted as '12-345.78'?
When I try to display detail info calling e.g. /api/products/12-345.67/, I get detail: Not found. as a response. As you can see, product IDs are formatted as 12-345.67. My first suspect was the RegEx validator (listed below), but it works the same way with or without it. Model, serializers, viewsets and URLs are defined this way: # models.py: class Product(models.Model): product_id = models.CharField(max_length=9, primary_key=True) name = models.CharField(max_length=40) is_active = models.BooleanField(default=True) def __str__(self): return self.product_id # serializers.py: class ProductSerializer(serializers.ModelSerializer): product_id = serializers.RegexField(regex='^\d{2}-\d{3}\.\d{2}$', max_length=9, min_length=9, allow_blank=False) name = serializers.CharField(min_length=6, max_length=50, allow_blank=False) class Meta: model = Product fields = '__all__' class ProductViewSet(viewsets.ModelViewSet): queryset = Product.objects.all() serializer_class = ProductSerializer lookup_field = 'product_id' # urls.py: router = routers.DefaultRouter() router.register(r'products', ProductViewSet, basename='products') (...) urlpatterns = [ path('api/', include(router.urls)), (...) -
angular or python django which is best for developing web application?
angular or python Django which is best for developing web applications? what is the difference is there for both? The advantages and disadvantages of both? which is fast? -
Return the progress to the template each value change in Django
I want to show the progress of the task going in the back-end in order let the user know that the work is still in progress. I have ajax call to a function to get the final value. In back end it will take lot of time to complete the job, but each time i have the progress of the job in one variable i want to show the values of this variable in the front end. For example my ajax function is def ajax_call(request): j = 0 for i in range(1,10000): j += i res = {'data': j} return JsonResponse(res, safe=False) As we know it will return the final value of j. But i want to show the value of j in the front end in each change. Is there any simple way to do this using celery or something -
How to send mail to selected users
Here i have a view which will either sends email to selected users or delete the selected users.The deleting the selected users is working fine but sending email to selected to users is not working. I tried these ways for sending email to selected email. with first approach Exception Type: AttributeError Exception Value: 'str' object has no attribute 'email' and also i want to remove the selected users from session if email sends to the users and restart the session again which is not happening here with this code With second approach it says invalid email address. First Approach def selected_users(request): selected_users = get_user_model().objects.filter(id__in=request.POST.getlist('users')) #tring to store selected users in session initial = {'users':[]} session = request.session.get('users',initial) if selected_users: for user in selected_users: session['users'].append(user.email) request.session['users'] = session print('hello',request.session['users']) # here i want to restart session either email sends or not to the user if selected_users and request.method == 'POST' and 'delete_selected' in request.POST: selected_users.delete() messages.success(request, 'deleted') return redirect('view_users') elif request.method == 'POST' and 'mail_selected' in request.POST: form = SendMailForm(request.POST or None) config = EmailConfiguration.objects.order_by('-date').first() backend = EmailBackend(host=config.email_host, port=config.email_port, username=config.email_host_user, password=config.email_host_password, use_tls=config.email_use_tls) if form.is_valid(): sub = form.cleaned_data['sub'] msg = form.cleaned_data['msg'] for user in request.session['users']: email = EmailMessage(subject=sub, body=msg, from_email=config.email_host_user, to=[user.email], connection=backend) … -
Is there any way to get the step-by-step solution in SymPy on my project?
Is there any function or code that can be implemented in my project to run the step by step solution work like sympy gamma [ referce:- see-steps button in sympy gamma]. -
How can I use '{{' , '}}' letter for plain text on template?
The problem was shown when I wanted to explain syntaxes of Django templates on my html document. However, {{ or {% letters are recognized and by the template engine, so I couldn't use them for just plain string. How can I make Django template engine to bypass that letters? I have already tried to use some letters, like backslash \ or Django template's comment function {# #}. First, backslash was not worth at all. Second, comment function makes bypassing everything inside the function. It is an example of my situation: <p>A variable outputs a value from the context, which is a dict-like object mapping keys to values. Variables are surrounded by {{ and }} like this:</p> <p>My first name is {{ first_name }}. My last name is {{ last_name }}.</p> I expected the output have to be like: A variable outputs a value from the context, which is a dict-like object mapping keys to values. Variables are surrounded by {{ and }} like this: My first name is {{ first_name }}. My last name is {{ last_name }}. But actually, it was like: A variable outputs a value from the context, which is a dict-like object mapping keys to values. … -
Django - Increasing the quantity of each products in cart
I added two products with variations in a cart i could not be able to increase the quantity of the second product. When i click on the quantity '+' sign of the second product it automatically increases the first product quantity. I have been stocked for days trying to fixed this problem but i failed. Someone help me! (sorry for the punch of codes). MODEL: class Item(models.Model): title = models.CharField(max_length=250) price = models.IntegerField() discount_price = models.IntegerField(null=True, blank=True) description = HTMLField() category = models.CharField(choices=CATEGORY_CHOICES, max_length=2) label = models.CharField(choices=LABEL_CHOICES, max_length=1) slug = models.SlugField(unique=True,max_length=250) def __str__(self): return self.title def get_absolute_url(self): return reverse("product-detail", kwargs={ 'slug': self.slug }) def get_add_to_cart_url(self): return reverse("add-to-cart", kwargs={ 'slug': self.slug }) def get_remove_from_cart_url(self): return reverse("remove-from-cart", kwargs={ 'slug': self.slug }) class VariationManager(models.Manager): def all(self): return super(VariationManager, self).filter(active=True) def sizes(self): return self.all().filter(category='size') def colors(self): return self.all().filter(category='color') VAR_CATEGORIES = ( ('size', 'size'), ('color', 'color'), ('package', 'package'), ) class Variation(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE) category = models.CharField(max_length=120, choices=VAR_CATEGORIES, default='size') title = models.CharField(max_length=120) active = models.BooleanField(default=True) objects = VariationManager() def __str__(self): return self.title def get_add_to_cart_url(self): return reverse("add-to-cart", kwargs={ 'slug': self.slug }) def get_remove_from_cart_url(self): return reverse("remove-from-cart", kwargs={ 'slug': self.slug }) class OrderItem(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) ordered = models.BooleanField(default=False) item = models.ForeignKey(Item, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) … -
Celery tasks don't send email to admins on logger critical messages
My celery tasks don't send an email to application admins each time I call logger.critical. I'm building a Django application The current configuration of my project, allows the admins of the application to receive an email each time a logger.critical message is created. This was pretty straight forward to set up. For some reason, which I'm not figuring out, the code that runs inside a celery task, does not have the same behavior. Does celery actually event allow this to be done? Am I missing some configuration? Does anyone got this problem and was able to solve it? Using: Django 1.11 Celery 4.3 Thanks for any help. -
Bitnami Django - No 'Access-Control-Allow-Origin' header is present on the requested resource
I have installed django(shopify app) on aws using bitnami. Everything is working fine but when i send xmlhttp request from shopify store to django i get CORS error- Access to XMLHttpRequest at 'https://django-app-url' from origin 'https://store_url' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. I have enabled cors on django- as earlier i was using openlite on aws and it was working. After moving to bitnami i started getting error- cors headers installed- pip3 install django-cors-headers and cors headers added in settings.py in middleware and installed apps Also added in /opt/bitnami/apps/django/django_projects/Project/conf httpd.conf Header set Access-Control-Allow-Origin "*" -
How to create Interactive charts in python
Could someone recommend a way to generate interactive charts using python library? Also if there is any existing library or any other way for features like, fetching/displaying the data in a table format when the chart is clicked I've tried using Bokeh, however it doesn't fulfill the complete requirement i.e. displaying the data in a table format when the chart is clicked ## Sample code from bokeh.core.properties import value from bokeh.io import show, output_file from bokeh.plotting import figure output_file("bar_stacked.html") fruits = ['Apples', 'Pears', 'Nectarines', 'Plums', 'Grapes', 'Strawberries'] years = ["2015", "2016", "2017"] colors = ["#c9d9d3", "#718dbf", "#e84d60"] data = {'fruits' : fruits, '2015' : [2, 1, 4, 3, 2, 4], '2016' : [5, 3, 4, 2, 4, 6], '2017' : [3, 2, 4, 4, 5, 3]} p = figure(x_range=fruits, plot_height=250, title="Fruit Counts by Year", toolbar_location=None, tools="hover", tooltips="$name @fruits: @$name") p.vbar_stack(years, x='fruits', width=0.9, color=colors, source=data, legend=[value(x) for x in years]) p.y_range.start = 0 p.x_range.range_padding = 0.1 p.xgrid.grid_line_color = None p.axis.minor_tick_line_color = None p.outline_line_color = None p.legend.location = "top_left" p.legend.orientation = "horizontal" show(p) -
How to solve Read-only file system problem?
I've upgraded to the last OS on MAC (Catalina), but now I have problem with virtualenv, python and django. When I do source ve37/bin/activate it's fine, but when I then do python manage.py runserver I get error as follow OSError: [Errno 30] Read-only file system: '/data' The full error is as follows: Traceback (most recent call last): File "manage.py", line 11, in <module> execute_from_command_line(sys.argv) File "/Users/my_name/Projects/my_project/ve37/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/Users/my_name/Projects/my_project/ve37/lib/python3.7/site-packages/django/core/management/__init__.py", line 325, in execute settings.INSTALLED_APPS File "/Users/my_name/Projects/my_project/ve37/lib/python3.7/site-packages/django/conf/__init__.py", line 57, in __getattr__ self._setup(name) File "/Users/my_name/Projects/my_project/ve37/lib/python3.7/site-packages/django/conf/__init__.py", line 44, in _setup self._wrapped = Settings(settings_module) File "/Users/my_name/Projects/my_project/ve37/lib/python3.7/site-packages/django/conf/__init__.py", line 107, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/Users/my_name/Projects/my_project/ve37/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/Users/my_name/Projects/my_project/Autralis/Autralis/__init__.py", line 2, in <module> from .celery import app as celery_app File "/Users/my_name/Projects/my_project/Autralis/Autralis/celery.py", line 4, in … -
Many-to-many field value show as user specific in django template and i am using update(Generic view)
I have create model used many to many field and other one is user as foreign key so i wanna to show on many to many field as per user. I have create model: class Deal(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True, related_name='userdeal', on_delete=models.SET_NULL) name = models.CharField(max_length=256, null=True, blank=True) image = models.ImageField(upload_to='images/',blank=True, null=True,) product = models.ManyToManyField(Product,blank=True,) store = models.ManyToManyField(Store,blank=True, ) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) discount = models.IntegerField(blank=True, null=True,) location = models.CharField(max_length=200,blank=True, null=True,) is_active = models.BooleanField(default=True) toDate = models.DateTimeField(blank=True, null=True,) fromDate = models.DateTimeField(blank=True, null=True,) description = models.TextField(blank=True, null=True,) price = models.IntegerField(blank=True, null=True,) conditioned = models.TextField(blank=True, null=True,) def __str__(self): return self.name def get_absolute_url(self): return reverse('Deallist', kwargs={'pk': self.pk}) view: class DealUpdate(SuccessMessageMixin, UpdateView): model = Deal template_name = 'company/create_deal.html' form_class = DealForm success_url = reverse_lazy('Deallist') success_message = "%(name)s was updated successfully" def get_success_message(self, cleaned_data): return self.success_message % dict( cleaned_data, name=self.object.name, ) def form_valid(self, form): form.instance.user = self.request.user return super(DealUpdate, self).form_valid(form) forms.py: class DealForm(forms.ModelForm): class Meta: model = Deal widgets = { 'name': forms.TextInput(attrs={'class': 'form-control','placeholder':'Enter Name'}), 'description': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Enter Description'}), 'price': forms.NumberInput(attrs={'class': 'form-control', 'placeholder': 'Enter Price'}), 'discount':forms.NumberInput(attrs={'class': 'form-control', 'placeholder': 'Enter Price'}), 'conditioned': forms.Textarea(attrs={'class':'form-control','placeholder':'Enter term and condition'}), 'toDate':forms.TextInput(attrs={'class': 'form-control datepicker','id':"date_timepicker_end", 'placeholder': 'Enter expire date and time'}), 'fromDate': forms.TextInput(attrs={'class': 'form-control datepicker', 'id': "date_timepicker_start",'placeholder': 'Enter … -
How to send password reset email?
Here I am trying to send password reset email with dynamic email configuration but it is not working proeprly.I think the problem is because of not passing dynamic backend connectinon=backend but I didn't know how can i do this? How can I send password reset email to user with this email configuration? models.py class EmailConfiguration(models.Model): email_use_tls = models.BooleanField(default=True) email_host = models.CharField(max_length=250,default='smtp.gmail.com') email_host_user = models.CharField(max_length=250,default="your@email.com") email_host_password = models.CharField(max_length=250,default='pass_word') email_port = models.PositiveSmallIntegerField(default=587) date = models.DateTimeField(auto_now_add=True) urls.py path('password-reset/', CustomPasswordResetView.as_view(),name='password_reset'), path('password-reset/done/',auth_views.PasswordResetDoneView.as_view(template_name='.... views.py class CustomPasswordResetView(PasswordContextMixin, FormView): config = EmailConfiguration.objects.order_by('-date').first() backend = EmailBackend(host=config.email_host, port=config.email_port, username=config.email_host_user, password=config.email_host_password, use_tls=config.email_use_tls) # email = EmailMessage(from_email=config.email_host_user, # connection=backend) # email.send() email_template_name = 'password_reset_email.html' extra_email_context = None form_class = EmailValidationOnForgotPassword <b>from_email = config.email_host_user connection = backend</b> html_email_template_name = None subject_template_name = 'organization/password_reset.html' success_url = reverse_lazy('password_reset_done') template_name = 'password_reset.html' title = 'Password Reset' token_generator = default_token_generator @method_decorator(csrf_protect) def dispatch(self, *args, **kwargs): return super().dispatch(*args, **kwargs) def form_valid(self, form): opts = { 'use_https': self.request.is_secure(), 'token_generator': self.token_generator, 'from_email': self.from_email, 'email_template_name': self.email_template_name, 'subject_template_name': self.subject_template_name, 'request': self.request, 'html_email_template_name': self.html_email_template_name, 'extra_email_context': self.extra_email_context, } form.save(**opts) return super().form_valid(form) -
How to do admin login programmatically in django or wagtail?
How can i do login and get direct admin access programmatically in django or wagtail. I want programmatically access to superuser login access in django or wagtail. Such kind of implementation is there or not? -
Form validation is fails when I use multi forms in a class based view
When I use single form there is no problem but when I used multi-forms in a class based view it's getting validation failed and skip to the else condition. I tried to fix with previous solution provided in stack overflow but couldn't able to solve it. -
how can i create custom is owner permissions in django class based view
hi i am currently making a classified site like gumtree etc, however i am having major issues with creating custom permissions. i have two situations. first one is i only want the owner of a profile be able to see their own profile, so user1 can only view user1s profile and no one else. second situation is i only want the author of an post be able to have edit and delete functionality, and everyone else is read only. if someone can give me a solution for this in class based views i will be very greatful. both profile and post are obviously different models, both using a detailview. any help on this will be appricated, thanks guys. -
Django: ManyToManyField saves choices that I don't put checks
I'm trying to develop a chat application with Django which a user can invite some other users to a closed chat room and make communications. But I would like to make it that the user cannot invite other users who are already in other active chat rooms. So when creating a chat room I would like to show only users who don't belong to any other active rooms, which resulted in the following codes. models.py from django.db import models from django.utils import timezone from .models import User, Topic class Room(models.Model): manager = models.ForeignKey(User, related_name='room_manage', on_delete=models.CASCADE) users = models.ManyToManyField(User, related_name='room_user', null=False) topic = models.ForeignKey(Topic, related_name='room', on_delete=models.CASCADE) create_time = models.DateTimeField(default=timezone.now, editable=False) is_active = models.BooleanField(default=True) def __str__(self): return "Created time: " + str(self.create_time) views.py from django.contrib.auth.decorators import login_required from django.shortcuts import redirect from django.template.response import TemplateResponse from .forms import RoomForm from .models import Room @login_required def room_add(request): room = Room() room.manager = request.user room_form = RoomForm(request.POST or None, instance=room) if room_form.is_valid(): room_form.save() return redirect('room:room-list') return TemplateResponse(request, 'room/form.html', {'form': room_form}) forms.py from django.forms import ModelForm, ModelMultipleChoiceField, CheckboxSelectMultiple from .models import User, Room class RoomForm(ModelForm): players = ModelMultipleChoiceField( widget=CheckboxSelectMultiple, queryset=User.objects.all().difference( User.objects.filter(room_user__is_active=True) ) ) class Meta: model = Room fields = ['players', 'topic',] The problem I … -
My static content isn't loading in my homepage
My homepage isn't loading my static content (css and img). It has a image in the middle but I have an empty blank space on it and my menu bar doesn't have a style, it looks very simple. 1 > That's how my index page looks like And this is my index html. {% load static %} <!DOCTYPE html> <html> <title>Inicio</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css"> <link href="https://fonts.googleapis.com/css?family=Manjari&display=swap" rel="stylesheet"> <link rel="stylesheet" type="text/css" href="estilomd.css"> <script defer src="https://use.fontawesome.com/releases/v5.0.6/js/all.js"></script> <style> body, html { height: 100%; font-family: "Manjari", sans-serif; } .bgimg { background-position: center; background-size: cover; <img src="{% static "img/taurus.png" %}" alt="My image"/> min-height: 55%; } </style> <body> <div class="search-box"> <input type="text" name="" class="search-txt" placeholder="Haz una búsqueda"/> <a class="search-btn" href="#"> <i class="fas fa-search"></i> </a> </div> <nav class="navegacion"> <ul class="menu"> <li><a href="index.html">Inicio</a> <li><a href="musculacion.html">Musculación</a> <li><a href="pilates.html">Pilates</a> <li><a href="zumba.html">Zumba</a> <li><a href="promo.html">Promos 2019</a> <li><a href="#">Profesores</a></li> <li><a href="contacto.html">Contacto</a></li> <li><a href="{% url 'registro' %}">Registrarse</a></li> <li><a href="{% url 'ingresar' %}">Iniciar Sesión</a></li> </ul> </nav> <header class="bgimg w3-display-container w3-grayscale-min" id="home"> <div class="w3-display-bottomleft w3-center w3-padding-large w3-hide-small"> </div> <div class="w3-display-middle w3-center"> </div> <div class="w3-display-bottomright w3-center w3-padding-large"> <span class="w3-text-white">Dirección: Calle Falsa 123</span> </div> </header> <div class="w3-sand w3-grayscale w3-large"> <div class="w3-container" id="about"> <div class="w3-content" style="max-width:700px"> <h5 class="w3-center w3-padding-64"><span class="w3-tag w3-wide">Acerca de nosotros</span></h5> … -
Why am I getting a circular import error with django?
This question seems to be asked before but none of the answers I came across solve my issue. I'm getting the following error when I try running the server with python manage.py runserver: django.core.exceptions.ImproperlyConfigured: The included URLconf 'tutorial.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. The error goes away if I change models.py so that my Item class does not extend models.Model. These are the relevant files: models.py from django.db import models from django.contrib.auth.models import User class Item(models.Model): name = models.CharField(max_length=255) owner = models.ForeignKey(User, on_delete=models.CASCADE) price = models.DecimalField(decimal_places=2) def __str__(self): return self.name serializers.py from rest_framework import serializers from django.contrib.auth.models import User, Group from .models import Item class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ('url', 'username', 'email', 'groups') class GroupSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Group fields = ('url', 'name') class ItemSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Item fields = ('url', 'name', 'owner', 'price') urls.py from django.urls import include, path from rest_framework import routers from tutorial.quickstart import views router = routers.DefaultRouter() router.register('users', views.UserViewSet) router.register('groups', views.GroupViewSet) router.register('items', views.ItemViewSet) urlpatterns = [ path('', include(router.urls)), path('api-auth/', include('rest_framework.urls', namespace='rest_framework')) ] -
How to Prevent SIGINT in one Heroku process from causing others to shut down?
I have a Django project that consists of four separate Heroku processes. The Procfile is included here: jobs: python manage.py sync_hacker_news web: gunicorn project.wsgi --log-file - rqworker_default: python manage.py run_worker rqworker_high: python manage.py run_worker --high web starts a web server, and rq_worker_* start high and low-priority Redis queue workers for async tasks. jobs is the problematic task. It's responsible for calling the following management command: import logging from apscheduler.schedulers.background import BackgroundScheduler from django.core.management.base import BaseCommand from django_apscheduler.jobstores import (DjangoJobStore, register_events, register_job) from subscriptions import autocomplete from subscriptions.notifications import schedule scheduler = BackgroundScheduler() scheduler.add_jobstore(DjangoJobStore(), "default") logger = logging.getLogger(__name__) @register_job(scheduler, "interval", minutes=5) def async_hacker_news_sync(): logger.info("Sync new data from Hacker News API.") autocomplete.get_accounts.delay() schedule.delay() class Command(BaseCommand): help = "Sync usernames and notifications with Hacker News." def handle(self, *args, **kwargs): register_events(scheduler) scheduler.start() print("Scheduler started!") My intent is for this command to register a task with django_apschedulerto query the HackerNews API every 5 minutes. The problem is that once this command runs, it terminates (which is expected) and results in SIGINT getting called. This causes web and rq_worker_* tasks to shut down as well. (venv) jamestimmins@Jamess-MBP-3 ~/P/hacker-subscribe-prod> heroku local -p 8000 [OKAY] Loaded ENV .env File as KEY=VALUE Format 6:46:01 PM web.1 | [2019-10-20 18:46:01 … -
Search Box in Django
i want add search bar to my Django Project , but what i need to do is , create search bar that allow users search in my website pages , i have designed website for download apps and games so i need allow user to search in my pages , such as , " gta v " and when the user search i want to move to result page , how to do that ? *note : i want this design when user search for anything ,,, bellow is the link for my design https://www.photobox.co.uk/my/photo/full?photo_id=502253546680 and THANKS -
How do I call images from '/media/' using relative URLs in Django?
I want to call logo.png and favicon.ico that are stored in the media/tmp folder using {% media 'tmp/logo.png' %} With my current configurations, I can call .css and .js files from the static folder with no problem, but I don't understand what goes wrong when calling from media. I have the following configurations in settings.py: STATIC_URL = '/static/' MEDIA_URL = '/media/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static_in_env')] STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_ROOT = os.path.join(BASE_DIR, 'media') And this is my folder configuration: myproject ├── myproject ├── blog (app) ├── media │ └── tmp │ ├── logo.png │ └── favicon.ico ├── static ├── static_in_env └── templates This is the error message I get: Invalid block tag on line 21: 'media'. Did you forget to register or load this tag? When I try: <link rel="shortcut icon" type="image/png" href="{% media tmp/favicon.ico %}"> and <img src="{% media tmp/logo.png %}" class="custom-logo"> -
Cannot set second pythonpath for second site in uwsgi, django 2.2
I have 2 projects that I need to keep very separate, each is in their own directory. My first site will load normally but my second site errors with Invalid HTTP_HOST header: 'domain.onion'. You may need to add 'domain.onion' to ALLOWED_HOSTS and list the pythonpath and env for my first site. Python Path: ['/home/www/nerds.tech/nerds/', Which is invalid. It should have the pythonpath and setting for the second site. /home/www# ls -l drwxrwxr-x 6 www-data www-data 4096 Oct 21 00:55 nerds.tech drwxrwx--- 4 www-data www-data 4096 Oct 21 00:54 secret drwxr-xr-x 2 www-data www-data 4096 Oct 21 01:01 uwsgi-ini each with their own .ini file /home/www# ls -l uwsgi-ini/ total 8 -rwxrwx--- 1 www-data www-data 671 Oct 21 00:57 suwsgi.ini -rwxr-xr-x 1 www-data www-data 947 Oct 21 00:57 uwsgi.ini . /home/www# cat /home/www/uwsgi-ini/uwsgi.ini [uwsgi] master = true vacuum = true die-on-term = true uid = www-data gid = www-data socket = /tmp/uwsgi.sock chdir = /home/www/nerds.tech/nerds pidfile=/tmp/uwsgi-master.pid virtualenv = /home/www/nerds.tech/venv pythonpath = /home/www/nerds.tech/nerds module = nerds.wsgi:application . /home/www# cat /home/www/uwsgi-ini/suwsgi.ini [uwsgi] master = true die-on-term = true uid = www-data gid = www-data vacuum = true chmod-socket = 660 socket = /tmp/suwsgi.sock chdir = /home/www/secret/exchange pidfile=/tmp/uwsgi-master.pid virtualenv = /home/www/secret/venv pythonpath = /home/www/secret/exchange … -
IntegrityError at /add_to_cart/ NOT NULL constraint failed:
I have a view which adds the items to the cart view, but when I try to add the items to the cart Item model rising an error I have created a model Item to capture the selected items Here is my models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class Product(models.Model): product_title = models.CharField(null=True, blank=True,max_length=200) product_price = models.IntegerField(null=True, blank=True,) product_image = models.ImageField(upload_to='cart/products/', null=True, blank=True) def __str__(self): return self.product_title class Cart_Bucket(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) create_date = models.DateTimeField(null=True, blank=True,verbose_name='create_date', auto_now=True) checked_out = models.BooleanField(default=False, verbose_name='checked_out') def __unicode__(self): return unicode(self.create_date) class Item(models.Model): cart = models.ForeignKey(Cart_Bucket, verbose_name='cart', on_delete=models.CASCADE) quantity = models.PositiveIntegerField(verbose_name='quantity') product = models.ForeignKey(Product, verbose_name='product', related_name='product', on_delete=models.CASCADE) def __str__(self): return u'%d units' % (self.quantity) I want to see the added items on the cart page