Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django local model inside other model that consists from 2 models
To make it clearer, I want to create an e-commerce app for installment stores I prepared a short HTML template at the bottom of the question I have the following model: class App_form(models.Model): #This is the head model id_customer = models.CharField(max_length=200) name = models.CharField(max_length=150, unique=True) phone_regex = RegexValidator(regex=r'^\+?1?\d{9,12}$', message="Phone number must be entered in the format: '998981234567'. Up to 12 digits allowed.") phone_number = models.CharField(validators=[phone_regex], max_length=13, unique=True) #Models which I should combine and which will be named as: products_with_period model and it should belong only and only to this App_form model warehouse = models.ManyToManyField(Warehouse) product_period = models.OneToOneField(Product_period, on_delete=models.CASCADE) def __str__(self): return self.surname #Product period class Product_period(models.Model): product_period = models.CharField(max_length=200, unique=True) product_percent = models.FloatField() product_periodvalue = models.FloatField() def __str__(self): return self.product_period #Warehouse model class Warehouse(models.Model): category_product = models.ForeignKey(Category_product, on_delete=models.CASCADE) product_name = models.CharField(max_length=200, unique=True) condition = models.BooleanField(default=False) amount = models.IntegerField() barcode = models.BigIntegerField() f_price = models.CharField(max_length=255, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.product_name What I want to achieve in my Rest Api out only from combined products_with_period model products_with_period = [{ id: 1, product_name: " ", product_fprice: " ", product_period: { "id": 2, "product_period_name": " ", "product_period_percent": " ", }, { id: 2, product_name: " ", product_fprice: " … -
django app getting error 500 on heroku, but runs fine locally
I'm getting server error 500 when I deploy my app to heroku. The logs show an issue with staticfiles, even though I'm serving static and media from an S3 bucket: ValueError: Missing staticfiles manifest entry for 'images/favicon.ico' What's odd is that run I run locally, even with DEBUG=False, the app runs fine and I verified that the images are loading from the S3 bucket (both media and static). However, for some reason heroku is unable to load from S3. Settings.py: import os import storages import django_heroku # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '***' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = (os.environ.get('DEBUG_VALUE') == 'True') #DEBUG = False ALLOWED_HOSTS = ['localhost', 'testapp.herokuapp.com', 'testapp.tv'] # Application definition # NOTE: django_cleanup should be placed last in INSTALLED_APPS. INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'taggit', 'storages', 'post.apps.PostConfig', 'ckeditor', 'sorl.thumbnail', 'django_cleanup.apps.CleanupConfig', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'testapp.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, … -
Keeps getting CSRF-related 403 Error even when using CSRF exempt decorator [duplicate]
I have just crafted a LoginView and been testing on Postman. However, it keeps throwing a 403 error saying, "CSRF verification failed. Request aborted. You are seeing this message because this site requires a CSRF cookie when submitting forms." even after I have adjusted my view like so with csrf exempt decorator: import json import jwt from psr.settings import SECRET_KEY from django.http import HttpResponse, JsonResponse from django.contrib.auth.forms import AuthenticationForm from django.contrib import messages from django.contrib.auth import login, logout, authenticate from django.contrib.auth import views as auth_views from django.views.decorators.csrf import csrf_exempt from .models import User class LoginView(auth_views.LoginView): @csrf_exempt def post(self, request): form = AuthenticationForm(data = request.POST) if form.is_valid(): user = authenticate(email=request.POST['email'], password=request.POST['password']) if user is not None: messages.add_message(request, messages.SUCCESS, "Welcome back, {}".format(user)) login(request, user) token = jwt.encode({'id': user.id}, SECRET_KEY, algorithm='HS256').decode('utf-8') return JsonResponse({'token': token}, status=200) Is there something I am missing here? Why wouldn't this decorator be enough to circumvent this csrf requirements? Thanks a lot in advance! -
Django view not sending context data to ReactJS/Axios application
It appears I have come across very strange behavior. I am building a ReactJS+Django 3.0 application. Here is the problem... I have a <form onSubmit={handleSubmit}> that wraps the form on the frontend. const handleSubmit = (e) => { e.preventDefault(); axios.post(paths.login, qs.stringify({ email: emailVal, password: passwordVal })); } This works perfectly fine in sending data to the Django view! But when I try to then pass context variable through the Django view, it just fails completely. Meaning, def login(request): data = {} ''' Handle Logging in ''' if request.method == 'POST': login_form = forms.LoginForm(request.POST) if login_form.is_valid(): user = login_form.authenticate_user() #login(request, user) return redirect('home') else: data['errorMessage'] = '' for field, errors in login_form.errors.items(): for error in errors: data['errorMessage'] += error print(data) return render(request, 'index.html', context=data) Given this, the data dictionary will be empty at first, but even when the print(data) shows that the data dictionary is populated, the context data that is sent to the index.html file is still empty. WHY MIGHT THIS BE? I've been stuck on this forever. I can work around this if I just use form submission instead of axios like this: <form method='POST'> However, I need to use axios. SOS -
Generate Additional Table For Individual Units Which Are Part Of A Collection
https://imgur.com/TPCjrkS This is a simplified version of the database Ive designed. Users can enroll in Modules, Packages, or both. Modules are individual units while Packages are collections of many units. Therefore a Package can be thought of as many Modules. Each Module a Student enrolls in has an Extra_Module_Data table (Django Through) which stores data unique to that Student/Module (eg: a boolean variable 'complete' which a teacher can set to True when his student finishes that Module). This works fine when a Student enrolls in a single Module. However, when a Student enrolls in a Package the Modules in that Package do not have an Extra_Module_Data table attached to them. I cant figure out how to attach an Extra_Module_Data table to every Module, regardless of if it is enrolled in via a Module, or a Package of Modules. class Student(models.Model): individual_modules = models.ManyToManyField(BaseModule, blank=True, through='modules.ExtraModuleData') module_packages = models.ManyToManyField(ModulePackage, blank=True) class BaseModule(models.Model): task_type = models.CharField(max_length=200) topic = models.CharField(max_length=200) class ModulePackage(models.Model): individual_modules = models.ManyToManyField(BaseModule, blank=True) name = models.CharField(max_length=200) class ExtraModuleData(models.Model): base_module = models.ForeignKey(BaseModule, on_delete=models.CASCADE) student = models.ForeignKey('users.Student', related_name='extra_module_data', on_delete=models.CASCADE, default=None) completed = models.BooleanField() Thank you. -
How to add an extra context in a Class Based View (ListView)
I am trying to add another Context in a ListView so that it can be used in the same template but it is not working and it gets an error for NoReverseMatch at / Reverse for 'user-posts' with arguments '('',)' not found. 1 pattern(s) tried: ['score/user/(?P<username>[^/]+)$'] The 1st applied context is called Items model from a Core app, the 2nd context that I want to apply is the post model from score app Here is the Views.py class HomeView(ListView): model = Item paginate_by = 12 template_name = "home.html" ordering = ['-timestamp'] def get_context_data(self, **kwargs): context = super(HomeView, self).get_context_data(**kwargs) try: context['posts'] = Post.objects.all() except Post.DoesNotExist: context['posts'] = None return context Here is the models for Post class Post(models.Model): designer = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=100) Here is the template which return the NoReverseMatch at / Reverse for 'user-posts' with arguments '('',)' not found. 1 pattern(s) tried: ['score/user/(?P[^/]+)$'] {% if posts %} <a href="{% url 'score:user-posts' post.designer.username %}"> <button type="button" class="btn btn-success btn-sm btn-block"> Check my posts</button> </a> {% else %} Show Nothing {% endif %} Here is the template which returns no errors but the if statement doesn't work instead of using {% url 'score:user-posts' post.designer.username %} I used {% url … -
How to use a {{key}} from django in javacript
Javascript cannot find element by id using {{key}} How can I access the {{key}} in my script? Script window.onload = jQuery(function ($) { var duration = document.getElementById("#timerseconds{{key}}").value; duration = 10800 - duration; display = $("#counter{{key}}"); startTimer(duration, display); }); HTML / DJANGO {% for key, value in list_cooking.items %} <li class="list-group-item"> <p>{{key}}</p> <br></br> <p>Seconds:</p><p id='counter{{key}}'>00</p> <input id="timerseconds{{key}}" type="hidden" value="{{value}}"> </li> Console jQuery.Deferred exception: Cannot read property 'value' of null TypeError: Cannot read property 'value' of null jquery.min.js:2 Uncaught TypeError: Cannot read property 'value' of null at HTMLDocument.<anonymous> (main.js:78) -
Django changing password issues
I have a Django site which authenticates users using an email and a password. Currently, users and their passwords are created in the admin panel, and then users can signin with this email and password. That all works well. The problem occurs once I attempt to change the password, as when either using the command line tool to change the user password, using my custom view, or using Django's built in view, I can no longer login as the user using the old or the new password. I'm thinking it is an error with the salting, because in the admin panel looking at users with unchanged passwords, the password field looks like so: Invalid password format or unknown hashing algorithm., but in the password field for users with passwords I attempted to change the field looks like this: algorithm: pbkdf2_sha256 iterations: 150000 salt: *********** hash: *******************************************. Login View: class LoginView(View): template_name = "account/login_template.html" def get(self, request): next_url = request.GET.get('next') if 'next' in request.GET else 'profile' if request.user.is_anonymous: form = UserLoginForm() return render(request, template_name=self.template_name, context={'form': form, "next": next_url}) return redirect(next_url) def post(self, request): form = UserLoginForm(request.POST) user = authenticate(email=form.data['email'], password=form.data['password']) if user: login(request, user) next_url = request.POST.get('next') if 'next' in request.POST … -
Why has my django site suddenly gone down? What does the log mean?
I have a Django site on a supported webhost. The site has suddenly gone down today. I'm adamant that I didn't make any file changes and haven't touched this particular site for about a month. Today it's stopped working and all the webhost technical support can do is give me the log and it's not obvious what the problem is (shown below). I get a very generic 'phusion' webserver error when I attempt to access the site 'This site can't be accessed. This issue is being looked at' or something similar, nothing useful there. My only option now is to do a complete server rewind, I'm a little bit hesitant and would prefer to know what the problem is and whether it can be fixed. Can anyone help please? App 4836 output: File "/home/electio5/electiongeek/passenger_wsgi.py", line 1, in App 4836 output: File "/home/electio5/electiongeek/electiongeek_proj/wsgi.py", line 16, in App 4836 output: File "/home/electio5/virtualenv/electiongeek/3.6/lib/python3.6/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application App 4836 output: File "/home/electio5/virtualenv/electiongeek/3.6/lib/python3.6/site-packages/django/__init__.py", line 24, in setup App 4836 output: File "/home/electio5/virtualenv/electiongeek/3.6/lib/python3.6/site-packages/django/apps/registry.py", line 114, in populate App 4836 output: File "/home/electio5/virtualenv/electiongeek/3.6/lib/python3.6/site-packages/django/apps/config.py", line 211, in import_models App 4836 output: File "/home/electio5/virtualenv/electiongeek/3.6/lib64/python3.6/importlib/__init__.py", line 126, in import_module App 4836 output: File "/home/electio5/virtualenv/electiongeek/3.6/lib/python3.6/site-packages/django/contrib/auth/models.py", line 2, in App 4836 … -
Django 3.0 MEDIA_ROOT and MEDIA_URL raise ImproperlyConfigured exception
I am developing a Django app where the users have profiles, and they can upload a profile picture, the pictures will be stored inside media/profile_pics/ and media is located in my root project's directory. I followed the Django docs [1]: https://docs.djangoproject.com/en/3.0/howto/static-files/#serving-files-uploaded-by-a-user-during-development to serve uploaded media files during development but I keep getting an exception that says: ` Exception in thread django-main-thread: File "/Users/OpenMindes/Dev/web/django/mylatestprotfolio-django/src/portfolio/urls.py", line 27, in <module> urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) File "/Users/OpenMindes/Dev/web/django/mylatestprotfolio-django/lib/python3.8/site-packages/django/conf/urls/static.py", line 22, in static raise ImproperlyConfigured("Empty static prefix not permitted") django.core.exceptions.ImproperlyConfigured: Empty static prefix not permitted My project's settings file looks like that (I hided the secret key): import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) #sekret key : i hide it # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', #own apps 'my_portfolio.apps.MyPortfolioConfig', 'blog.apps.BlogConfig', 'crud.apps.CrudConfig', 'users.apps.UsersConfig', #third party 'widget_tweaks', 'crispy_forms', 'django_cleanup', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'portfolio.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION … -
Django With electron framework
is it possible to create a Desktop App With electron framework and Django as backend , if the answer is yes how to ?? i mean can some one share some links with me please , -
How to display the list of videos in two categories 1.'currentUser' videos and 2. 'otherUsers' videos on the same page in django
The below code gives "otherUsers" videos class Test(ListView): model = VideoUpload template_name = 'videoTube.html' The below code gives "currentUser" videos class Test(ListView): model = VideoUpload template_name = 'videoTube.html' def get_queryset(self): return VideoUpload.objects.filter(user=self.request.user) In templates {% for vid in object_list %} {% if forloop.counter < 5 %} {{ vid.video }} {% endif %} {% endfor %} My requirement is to display the list of videos in two categories 1.List of 'currentUser' videos and 2.List of 'otherUsers' videos on the same html page -
Set background color of table row based on local value in view (Django)
This isn't really specific to any sort of code so I'll just describe what I'm trying to figure out how to do. I have a local value in my view that corresponds to an object id for one of my models. I want to set the background color of a row in a table created with django-tables2 if that row has a record.pk equal to that id. I think there is probably a way to do this using row_attrs by giving a row attribute to each row that is essentially a T/F value. I'm just not sure how I can do this dynamically. Any suggestions? -
Custom Sort for Column Values in Django SQLite/Python
I have a particular column in my Database(SQLite) as TEXT and the column's named 'version' and counts & values will be typically like +-----------+--------+ | version | counts | +-----------+--------+ | 2019.1.0 | 50 | +-----------+--------+ | 2019.2.0 | 100 | +-----------+--------+ | 2019.10.0 | 200 | +-----------+--------+ | 2019.11.0 | 90 | +-----------+--------+ | 2019.12.0 | 20 | +-----------+--------+ While retrieving from database, I use .order_by('version'), and the column data are retrieved in a following order +-----------+--------+ | version | counts | +-----------+--------+ | 2019.1.0 | 50 | +-----------+--------+ | 2019.10.0 |200 | +-----------+--------+ | 2019.11.0 | 90 | +-----------+--------+ | 2019.12.0 | 20 | +-----------+--------+ | 2019.2.0 | 100 | +-----------+--------+ Reason: order_by does String Sort which sorts 2019.10.0 ahead of 2019.2.0, but actually what I want is +-----------+--------+ | version | counts | +-----------+--------+ | 2019.1.0 | 50 | +-----------+--------+ | 2019.2.0 | 100 | +-----------+--------+ | 2019.10.0 | 200 | +-----------+--------+ | 2019.11.0 | 90 | +-----------+--------+ | 2019.12.0 | 20 | +-----------+--------+ Is there anyway I could handle sort in database level, or source code level as well? I am also new to python and I am not familiar with sort mechanisms as well. Any … -
The empty path didn't match any of these urls
Using the URLconf defined in first_project.urls, Django tried these URL patterns, in this order: ^$ [name='index'] admin/ The empty path didn't match any of these. This is code in urls.py from django.contrib import admin from django.urls import path from first_app import views urlpatterns = [ path('^$',views.index,name='index'), path('admin/', admin.site.urls), -
Creating a PostgreSQL database backup via psql on macOS
I'm trying to create a PostgreSQL local db dump via Terminal on macOS using psql. My next step is to upload/import my entire db to my Amazon RDS PostgreSQL db instance. Can anyone help me with the Terminal command to create a dump file 'mydbdump.sql' for my 'mydb' database. I've sorted through existing questions, searched forums, even Amazon RDS docs (above, link), and am having no luck with the commands from any of these docs. What am I doing wrong? Here is what I've tried so far (and I've gotten nothing back, not even an error): Via sudo: sudo -u postgres psql pg_dump -Fc -o -f /Users/<my_computer>/database_backup.sql mydb Via psql, connected to mydb (\c mydb;): mydb-# pg_dump dbname=mydb -f mydbdump.sql mydb-# pg_dump -U postgres -W -F t mydb > /Users/<my_computer>/database_backup.sql mydb-# pg_dump -Fc mydb > /Users/<my_computer>/database_backup.sql mydb-# pg_dump -U postgres mydb > database_backup.sql mydb-# pg_dump -Fc mydb > /Users/<my_computer>/database_backup.sql mydb-# pg_dump -U postgres -W -F t mydb > /Users/<my_computer>/database_backup.sql For reference: I'm using Django, in settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'mydb', 'USER': 'dbuser', 'PASSWORD': '<MYPASSWORD>', 'HOST': 'localhost', 'PORT': '', } } By the way, my Django app is running successfully. When I list all database relations … -
Account creation with Django + Djoser ["Unable to create account."]
I'm trying to create a user using Django with Djoser. When I try to create the user I get the error ["Unable to create account."] I'm using a CustomUser that inherits from AbstractUser: class CustomUser(AbstractUser): MAN = 'man' WOMAN = 'woman' GENDER_CHOICES = ( (MAN, 'Man'), (WOMAN, 'Woman'), ) id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) email = models.EmailField(_('Email'), unique=True,db_index=True) gender = models.CharField("Gender", max_length=30, choices=GENDER_CHOICES, blank=True, null=True) birth_date = models.DateField("Birth date", blank=True, null=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['last_name','first_name',] objects = CustomUserManager() A custom manager for user creation: class CustomUserManager(BaseUserManager): def create_user(self, email, first_name, last_name, password, **extra_fields): if not email: raise ValueError(_('email is required')) if not first_name: raise ValueError(_('first_name is required')) if not last_name: raise ValueError(_('last_name is required')) email = self.normalize_email(email) user = self.model(email=email,first_name=first_name,last_name=last_name, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, first_name, last_name, password, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_active', True) if extra_fields.get('is_staff') is not True: raise ValueError(_('superuser must have is_staff=True.')) if extra_fields.get('is_superuser') is not True: raise ValueError(_('superuser must have is_superuser=True.')) return self.create_user(email, first_name, last_name, password, **extra_fields) In my urls.py urlpatterns = [ path('admin/', admin.site.urls), path('auth/', include('djoser.urls')), path('auth/', include('djoser.urls.jwt')), ] Command to create an user: curl -X POST http://127.0.0.1:8000/auth/users/ --data 'password=xxxxxx&email=test@email.com&first_name=Charlie&last_name=Lim' When I'm trying to create the user with te last … -
Why doesn't this div triggers the function in Django HTML?
I have a Django project in which I have this HTML code in my template: <div class="upper_bar"> <div></div> <div class="stats_bar">{{ stage1_total }} recibidos, {{ stage2_total }} en preparación, {{ stage3_total }} en camino y {{ stage4_total }} entregados</div> <div id="createButton" onclick="myFunction()"><i class="fas fa-plus-circle" style="font-size:48px;"></i></div> </div> In my scripts tag, I have this: function myFunction() { alert('Function...'); } I previously had this code instead in my scripts: document.getElementById('createButton').addEventListener('click', function() { alert('message...'); document.querySelector('.bg-modal').style.display = 'flex'; } ); But it didn't work either. Does someone know why is the div called 'createButton' not working? I don't want to use a button since I'd like to only see the icon, or is there another way to just see the icon in a way that works and calls the function? -
Passing Values from JavaScript to Django view.py
Description: I have created a page. The page is running on http://127.0.0.1:8000/. There are three forms. I have one button separately. When I click on that button, all three form values need to be collected in Django view.py. But I'm having a problem with ajax request-response. The value arry1D is not getting at the Django view.py Below is the separate button. <form method="post"> {% csrf_token %} <input class="bg-yellow text-white" value="RUN" name="runModel" type="submit" onclick="sendValuesToBack()"> </form> Below is the JavaScript Method. function sendValuesToBack() { let j, i, arry1D = []; for(j=0;j!=countName;j++) { var inputs = document.getElementById("formId" + j).elements; if (!arry1D[j]) arry1D[j] = [] arry1D[j][0] = "formId" + j; console.log("---------------Form--------------------"); for (i = 0; i < inputs.length; i++) { if (inputs[i].nodeName === "INPUT" && inputs[i].type === "text") { console.log("values of form:", inputs[i].value); arry1D[j][i + 1] = inputs[i].value; } } } var tk = $(this).attr("data-token") $.ajax({ url: "/", type:"POST", data: { 'arry1D':arry1D, 'csrfmiddlewaretoken': tk}, cache:false, dataType: "json", success: function(resp){ alert ("resp: "+resp.arry1D); } }); } view.py --> function from Django if request.method == "POST" and request.is_ajax(): arry1D = request.POST.get('arry1D') return HttpResponse(json.dumps({'arry1D': arry1D}), content_type="application/json") url.py urlpatterns = [ path('admin/', admin.site.urls), path('',views.index,name="index"), path('',views.getModelAttribute,name="index"), ] -
Python requests saving broken images in kubernetes cluster pod container
I have a django application running in a docker container that downloads images from another server using python requests package. It saves the image using a method on a model like the following: class MyModel(models.Model): preview_image = models.ImageField( upload_to=user_directory_path, height_field=None, width_field=None, max_length=100, ) def user_directory_path(self, instance): return 'my/path/' def save_preview_image(self, image_url): result = requests.get(image_url) self.preview_image.save(result.url, ContentFile(result.content), save=True) self.save() MyModel.save_preview_image gets the image from a provided URL and saves in at the path provided. When I run it in my docker container locally on my system, it saves the image correctly but when I run it in a container in my Kubernetes cluster pod., it saves a broken png image, a file which fails to open. I am wondering what's wrong and if anyone has experienced this issue before. I am running it inside Google Cloud Platform's Kubernetes Engine. Any suggestions will be appreciated. -
Trying to extend a base html but not working properly
I have a form that I am trying to access when pressing a button on my navbar. I have a base template file that consists of the code for the navbar and background color and I have another template that has the code for the form. The navbar button seems to work every time I remove the {% extends 'base.html' %} but only the form shows up. I want to be able to extend the base template so the navbar background color and nav bar show up too but this is not working. code snippet from base.html <nav class="navbar navbar-expand-lg navbar-dark bg-dark"> <a class="navbar-brand" href="/">TweetyBird</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarText" aria-controls="navbarText" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarText"> <ul class="navbar-nav mr-auto"> <li class="nav-item active"> <a class="nav-link" href="/search">Search by Tweet <span class="sr-only">(current)</span></a> </li> <li class="nav-item"> <a class="nav-link" href="#">Twitter Bot</a> </li> <li class="nav-item"> <a class="nav-link" href="#">To be added</a> </li> </ul> </div> </nav> search.html % extends 'base.html' %} {%load static%} <body> <container > <form action="/searchoutput/" method="post"> {% csrf_token %} Input Text: <input type="text" name="param" required> <br><br> {{data_external}}<br><br> {{data}} <br><br> <input type="submit" value="Check tweet"> </form> </container> </body> snippet from url.py path('', views.noreq), #shows the html template for the website path('search/',views.search), path('searchoutput/',views.searchoutput), … -
How to save list of objects getting from template in django models?
im using django and i wanna save list of data in my models "Detail_equipement" : this is my models where i want to save data : class Detail_equipement(models.Model): equipements=models.ForeignKey(Equipement,on_delete=models.CASCADE,default=True) interventions=models.ForeignKey(Intervention,on_delete=models.CASCADE) QTE = models.IntegerField() and this is my template html when i send data to views : {% block content %} <div class="row"> <div class="col-md-6 grid-margin stretch-card"> <div class="card"> <div class="card-body"> <h4 class="card-title">Ajouter Intervention</h4> <form id="modal_form_signup" method="POST"> {% csrf_token %} <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title"> <i class="fa fa-lock mr-1"></i>Detail Equipement Utiliser </h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span>&times;</span> </button> </div> <div class="modal-body"> <div class="form-row"> {% for equipment in interv.equipements.all %} <div class="col-sm-6"> <div class="form-group"> <label for="modal_signup_firstname">Equipement</label> <div class="input-group"> <input type="text" id="modal_signup_firstname" name="equipements" value="{{ equipment.nom_equipement }}" class="form-control" placeholder="Equipement" disabled/> </div> </div> </div> <div class="col-sm-4"> <div class="form-group"> <label for="modal_signup_lastname">QTE</label> <div class="input-group"> <input type="text" id="modal_signup_lastname" name="qte" class="form-control" placeholder="QTE" /> </div> </div> </div> {% endfor %} </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Annuler</button> <button type="submit" class="btn btn-primary">Confirmer</button> </div> </div> </form> </div> </div> {% endblock content %} im trying to use for loop to bring all data but it not working for me it show error "GET /techniciens/terminer/7 HTTP/1.1" 200 13999 So Here is my function in views.py : def terminer(request,pk): get_interv= Intervention.objects.get(id=pk) … -
Django Checkbox Automatically Update Database
I can find lots of information on how to make a checkbox that automatically updates the database onclick using php/ajax (rather than having a user click the checkbox then press another button to submit the form), but cant find anything on doing this in Django. Is this possible? Thank you -
Developiing an Online Pentesting Tool
Thanks for considering my question. I needed to create a tool that allows users to test the vulnerability of their site. i tried sqlmap and D-Tect. However, I want to know how I can make it into a flask or django application where the sqlmap scripts will be called when a user makes a URL input. from sqlmap import sqlmap def test(): execute(sqlmap.py - d "mysql://admin:admin@192.168.21.17:3306/testdb" - f --banner --dbs --users) if __name__ == "__main__": test() I am not sure of the way the syntax would go but something related. Also, other recommendations of tools to use would also be great. Any help on this would be appreciated. Thanks. -
Get username in model with extended user
At the moment, I get the user id when I create a new article. I would like also to have the username in the model (I'm using DRF with React, so it would save me a get request just for the username). models.py: class Article(models.Model): title = models.CharField(max_length=100) user = models.ForeignKey( User, related_name='Article', on_delete=models.CASCADE) serializers.py: class ArticleSerializer(serializers.ModelSerializer): user = serializers.PrimaryKeyRelatedField( read_only=True, default=serializers.CurrentUserDefault()) class Meta: model = Article fields = ['id', 'title', 'user'] def save(self, **kwargs): kwargs["user"] = self.fields["user"].get_default() return super().save(**kwargs)