Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
500 IIS Internal server error near Fetch Api in django
I have deployed a django web application through Microsoft IIS. The deployment seems to be successful except for the error I am getting while submitting a form. I assume it's occurring because of the URL string given in fetch API. Though I am not exactly sure what is causing the error. Seeking help for the same. P.S- The yellow highlighted part in Console.log is the hostname on which I have deployed and now accessing the web page. web.config <configuration> <system.webServer> <handlers> <add name="Python FastCGI" path="*" verb="*" modules="FastCgiModule" scriptProcessor="C:\Python\python.exe|C:\Python\Lib\site-packages\wfastcgi.py" resourceType="Unspecified" requireAccess="Script" /> </handlers> </system.webServer> <appSettings> <!-- Required settings --> <add key="WSGI_HANDLER" value="my_app.wsgi_app()" /> <add key="PYTHONPATH" value="C:\MyApp" /> <add key="DJANGO_SETTINGS_MODULE" value="my_app.settings" /> <!-- Optional settings --> <add key="WSGI_LOG" value="C:\Logs\my_app.log" /> <add key="WSGI_RESTART_FILE_REGEX" value=".*((\.py)|(\.config))$" /> <add key="APPINSIGHTS_INSTRUMENTATIONKEY" value="__instrumentation_key__" /> <add key="WSGI_PTVSD_SECRET" value="__secret_code__" /> <add key="WSGI_PTVSD_ADDRESS" value="ipaddress:port" /> </appSettings> </configuration> Console.log Console.log urls.py urls.py Logs #Software: Microsoft Internet Information Services 10.0 #Version: 1.0 #Date: 2022-05-30 06:14:28 #Fields: date time s-ip cs-method cs-uri-stem cs-uri-query s-port cs-username c-ip cs(User-Agent) cs(Referer) sc-status sc-substatus sc-win32-status time-taken 2022-05-30 06:14:28 10.9.20.237 GET / - 90 - 10.156.68.147 Mozilla/5.0+(Windows+NT+10.0;+Win64;+x64)+AppleWebKit/537.36+(KHTML,+like+Gecko)+Chrome/102.0.0.0+Safari/537.36 - 200 0 0 978 2022-05-30 06:14:29 10.9.20.237 GET /static/AIG-Logo.png - 90 - 10.156.68.147 Mozilla/5.0+(Windows+NT+10.0;+Win64;+x64)+AppleWebKit/537.36+(KHTML,+like+Gecko)+Chrome/102.0.0.0+Safari/537.36 http://pwgsascs0597001.r1-core.r1.aig.net:90/ 200 0 0 32 2022-05-30 06:14:29 … -
Django (createsuperuser) Error: That username is already taken
I am developing a Django application with Docker & PostgreSQL. I was using the same settings I will post below and all was working well, but after I had shutted down and started back (after removing volumes from Docker, and deleting pycache from folder) with: docker-compose down docker-compose up --remove-orphans When I try to create the admin (same user of the last session) it tells me: Error: That username is already taken. But, when I try to lookup for the user in PgAdmin (localhost:5050) the user does not exists, and when I try to login from the website (localhost:8000) it raise Please enter a correct username and password. Note that both fields may be case-sensitive. Dockerfile: FROM python:3.7-slim as production ENV PYTHONUNBEFFERED=1 WORKDIR /app/ RUN apt-get update && \ apt-get install -y \ bash \ build-essential \ gcc \ libffi-dev \ musl-dev \ openssl \ postgresql \ libpq-dev COPY requirements/prod.txt ./requirements/prod.txt RUN pip install -r ./requirements/prod.txt COPY manage.py ./manage.py COPY website ./website EXPOSE 8000 FROM production as development COPY requirements/dev.txt ./requirements/dev.txt RUN pip install -r ./requirements/dev.txt COPY . . docker-compose.yml version: "3.7" x-service-volumes: &service-volumes - ./:/app/:rw,cached x-database-variables: &database-variables POSTGRES_DB: postgres POSTGRES_USER: postgres POSTGRES_PASSWORD: postgres x-app-variables: &app-variables <<: *database-variables POSTGRES_HOST: postgres … -
Multiple Sites with Django and Apache - Can't get both to work at the same time
We have two sites made in Django, one is a fork of the other (same project name) so we had issues with the wrong settings.py loading for the second site in mod_wsgi. So we put mod_wsgi into Daemon mode to hopefully separate the two more so this didn't happen. One works fine when the other is either disabled or configured incorrectly. Once the second site is made to what should work, it doesn't and it brings the first one down with it, giving us an Apache 500 Error. Here is the conf.d file we have for one of them: WSGIDaemonProcess {siteName}.co.uk python-home=/var/www/vhosts/{siteName}.co.uk/venv python-path=/var/www/vhosts/{siteName}.co.uk/website/{djangoProject} WSGIProcessGroup {siteName}.co.uk WSGIScriptAlias / /var/www/vhosts/{siteName}.co.uk/website/{djangoProject}/{djangoProject}/wsgi.py WSGIPythonHome /var/www/vhosts/{siteName}.co.uk/venv WSGIPythonPath /var/www/vhosts/{siteName}.co.uk/website/{djangoProject} <VirtualHost *:80> ServerName {siteName}.co.uk ServerAlias www.{siteName}.co.uk <Directory /var/www/vhosts/{siteName}.co.uk/> Options Indexes FollowSymLinks MultiViews AllowOverride All </Directory> <Directory /var/www/vhosts/{siteName}.co.uk/website/{djangoProject}/{djangoProject}> <Files wsgi.py> Require all granted </Files> </Directory> CustomLog /var/log/httpd/{siteName}.co.uk-access.log combined ErrorLog /var/log/httpd/{siteName}.co.uk-error.log # Possible values include: debug, info, notice, warn, error, crit, # alert, emerg. LogLevel warn </VirtualHost> Note: The file is the same for the two sites, except for that {siteName} is different. {djangoProject} is the same, since one is a modified clone of the other. It also gives the error in the apache log that there was a permission … -
Can't display the children items (packets) that contain the same dev_address as the selected parent item (device) in React.js
(Please check below for screenshots) I have a relational DB where every packet belongs to only one device (through a foreign key dev_address) and a device can have many packets (many-to-one rel). I've been trying to display the packets that belong to the selected device which is in a mapped list. I'm using context to load packets and devices from the API. The stack is React-Django-MySQL. Can someone please direct/help me on the method I should use to resolve this? It's like an if statement that displays the packets that belong to X device if X device was selected. import React from "react"; import GlobalContext from "./GlobalContext"; const AppContext = (props) => { const [modules, setModules] = React.useState([]); const [devices, setDevices] = React.useState([]); const [packets, setPackets] = React.useState([]); const [fields, setFields] = React.useState([]); React.useEffect(() => { Promise.all([ fetch("http://localhost:8000/api/v1/modules") .then((res) => res.json()) .then((json) => { setModules(json); }), fetch("http://localhost:8000/api/v1/devices") .then((res) => res.json()) .then((json) => { setDevices(json); }), fetch("http://localhost:8000/api/v1/packets") .then((res) => res.json()) .then((json) => { setPackets(json); }), fetch("http://localhost:8000/api/v1/fields") .then((res) => res.json()) .then((json) => { setFields(json); }), ]); }, []); return ( <GlobalContext.Provider value={{ modules, devices, packets, fields, }} > {props.children} </GlobalContext.Provider> ); }; export default AppContext; Devices table Packets table What I want … -
Render a string containing a django template, form and svg
I'm new to django and I have a problem, I want to render a string like httpresponse does but the problem is that the string is the content of an html file containing a django template and an svg code. Httpresponse does not interpret the django template and the django csrf_token. IT just copies them as text. For example: def mysresponse(request): ch= " {% extends 'base.html' %} {% block content%}form django and svg content {%endblock%}" return httpResponse(ch) This code copies the templates {% extends 'base.html' %} {% block content%}, {%endblock%} but interprets the svg and form content except the csrf_token. Is there a way to do this please? Thank you very much -
how to connect API Printify with django
I have problems connecting to the printify api with django, I am not very practical so I would need to understand why and above all what to pass as parameters views: def home(request): payload = settings.TOKEN_PRINTIFY # ?? response = requests.get('https://api.printify.com/v1/.json') print('-----------------', response) #error 401 context = {} return render(request, 'home.html', context) the response it gives me how 401 status and I don't understand where to put that token -
Insufficient permissions for deploying ARM template using Python SDK
I've got a simple scirpt that should deploy an ARM template: credentials = ClientSecretCredential( client_id="<client-id>", client_secret="<client-secret>", tenant_id="<tenant-id>" ) template = requests.get("<template-url>").json() deployment_properties = { 'mode': DeploymentMode.incremental, 'template': template } deployment = Deployment(location="eastus", properties=deployment_properties) client = ResourceManagementClient(credentials, subscription_id="<subscription-id>") deployment_async_operation = client.deployments.begin_create_or_update_at_subscription_scope("test_deployment", deployment) deployment_async_operation.wait() When I try to run it, I get this error: Exception Details: (InsufficientPrivilegesForManagedServiceResource) The requested user doesn't have sufficient privileges to perform the operation. Code: InsufficientPrivilegesForManagedServiceResource Message: The requested user doesn't have sufficient privileges to perform the operation. The app registration I created, does have user_impersonation permission, which should do the trick. Am I missing some permissions here? Thanks for the help! -
Automaticaly wrtite logged in superuser in model
In this piece of code, admin model in Registration should written automaticaly when add new registration in admin, and cannot be changed in admin panel Also it should be hidden in admin panel or read only import django.utils.timezone from django.db import models from django.contrib.auth.models import User import datetime year = datetime.datetime.now().year month = datetime.datetime.now().month day = datetime.datetime.now().day class Rooms(models.Model): objects = None room_num = models.IntegerField(verbose_name='Комната') room_bool = models.BooleanField(default=True, verbose_name='Релевантность') category = models.CharField(max_length=150, verbose_name='Категория') price = models.IntegerField(verbose_name='Цена (сум)', null=True) def __str__(self): return f'{self.room_num}' class Meta: verbose_name = 'Комнату' verbose_name_plural = 'Комнаты' class Registration(models.Model): objects = None rooms = models.ForeignKey(Rooms, on_delete=models.CASCADE, verbose_name='Номер', help_text='Номер в который хотите заселить гостя!', ) first_name = models.CharField(max_length=150, verbose_name='Имя') last_name = models.CharField(max_length=150, verbose_name='Фамилия') admin = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='Администратор') #There should be written the of superuser which loggen in pasport_serial_num = models.CharField(max_length=100, verbose_name='Серия паспорта', help_text='*AB-0123456') birth_date = models.DateField(verbose_name='Дата рождения') img = models.FileField(verbose_name='Фото документа', help_text='Загружайте файл в формате .pdf') visit_date = models.DateField( default=django.utils.timezone.localdate, verbose_name='Дата прибытия') leave_date = models.DateField(blank=True, null=True, verbose_name='Дата отбытия', default='После ухода!') guest_count = models.IntegerField(default=1, verbose_name='Кол-во людей') room_bool = models.BooleanField(default=False, verbose_name='Релевантность', help_text='При бронирование отключите галочку') price = models.IntegerField(verbose_name='Цена (сум)', null=True) def __str__(self): return f'{self.rooms},{self.last_name},{self.first_name},{self.room_bool}' class Meta: verbose_name = 'Номер' verbose_name_plural = 'Регистрация' -
How can we override Dango ModelAdmin queryset over ModelForm queryset?
Requirement is to display M2M instances in a dropdown for different logins. Each login will be able to see only instances belonging to their own domain. Since this dropdown is a dynamic list of table row values, I want to use widget = forms.CheckboxSelectMultiple which is part of the ModelForm where we need to pass the queryset. This queryset overrides the M2M form field definition: def formfield_for_manytomany(self, db_field, request, **kwargs): It doesn't filter as per the login and displays all the objects. I don't want to use the default <Ctrl +> for selection from the dropdown. Not very good with any JS related code. Please quide. Sharing the snippets of code tried: models.py: class GroupA(models.Model): address = models.EmailField( unique=True,verbose_name='Email id of the group') mailboxes = models.ManyToManyField(Mailbox, related_name='my_mailboxes') class GroupForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['mailboxes'].widget.attrs={"style":"height:100px;"} class Meta: model = GroupA fields = "__all__" mailboxes = forms.ModelMultipleChoiceField( queryset = Mailbox.objects.all(), widget = forms.CheckboxSelectMultiple ) In admin.py class GroupAdmin(admin.ModelAdmin): form = GroupForm def formfield_for_manytomany(self, db_field, request, **kwargs): if db_field.name == "mailboxes": #if request.user.groups.filter(name__in=['customers']).exists(): kwargs["queryset"] = Mailbox.objects.filter( domain__customer__email=request.user.email) #print(kwargs["queryset"], 'qqqqqq') for k in kwargs["queryset"]: print(k, 'kkkkkkkkkk') return super(GroupAdmin, self).formfield_for_manytomany( db_field, request, **kwargs) Filtering works when we don't use the MultiCheckbox widget. Want … -
Java Script accordion functionality problem
Im making a app in django which needs a accordion. This is the following HTML code {% load static %} {% for comp in comps %} <script src="{% static 'main/app.js' %}"></script> <div class="accordion-body"> <div class="accordion"> <div class="container"> <div class="label"> {{comp.name}} {{comp.country}}, {{comp.city}} </div> <div class="content">{{comp.descr}}</div> <hr> </div> </div> </div> {% endfor %} This is the css which actually hides the content. Note Ive taken out a lot of uneccessary css like font-size and colors. .accordion .label::before { content: '+'; top: 50%; transform: translateY(-50%); } .accordion .content { text-align: justify; width: 780px; overflow: hidden; transition: 0.5s; } .accordion .container.active .content { height: 150px; } Finally this is javascript which is meant to add a Event Listener const accordion = document.getElementsByClassName('container'); accordion.addEventListener('click', function () { this.classList.toggle('active') }) The active class isnt being added. There might be a problem with linking the js with the HTML doc since when I run the app this is what I get in the command line. GET /static/main/app.js HTTP/1.1 The location is definitely correct -
Django - count how many objects are in self
I have a very simple model with the following details: class ExclusiveUser(models.Model): exclusivepass = models.CharField(max_length=4, primary_key=True, editable=False) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) date_of_birth = models.DateField(null=True) date_of_birth = models.DateField(null=True) age = models.IntegerField(editable=False) def save(self,*args, **kwargs): today = date.today() self.exclusivepass = exclusivepass_gen(self.exclusivepass.all().count()) self.age = today.year - self.date_of_birth.year - ((today.month, today.day) < (self.date_of_birth.month, self.date_of_birth.day)) super().save(*args, **kwargs) exclusivepass_gen is a simple utils.py method for generating a unique exclusivepass def exclusivepass_gen(pass_count): pass_next = 0 pass_limit = 101 if pass_count < pass_limit: pass_next = pass_count + 1 return ('E' + "{:03d}".format(pass_next)) I'm trying to get the count of all objects in the table to pass to exclusivepass_gen to generate the next number, but I get the following error when i do: 'ExclusiveUser' object has no attribute 'all' How can i count all objects in the model to pass to exclusivepass_gen method? -
Django rest framework cast foreign mysql foreign table column
please help me to convert cast foreign table(customers) first name class LoandetailListSearch(generics.ListAPIView): serializer_class = LoandetailSerializer def get_queryset(self): """ Optionally restricts the returned loan details to a search list, by filtering against a `fields` in query parameter in the URL. """ queryset = Loandetails.objects.all().exclude(broker_name__isnull=True).\ extra( { 'staff': "CONVERT(CAST(CONVERT(CONCAT(staff ) using latin1) as binary) using utf8)", 'customer__first_name': 'SELECT CONVERT(CAST(CONVERT(CONCAT(first_name ) using latin1) as binary) using utf8) as first_name FROM customers WHERE customers.id = loan_details.customer_id' }).\ extra(select={'customer__first_name': 'SELECT CONVERT(CAST(CONVERT(CONCAT(first_name ) using latin1) as binary) using utf8) as first_name FROM customers WHERE customers.id = loan_details.customer_id' }) return queryset I tried to convert and cast both methods first_name, But no luck. Thanks -
Django - get latest price for each product and put in a query set in order to render in a template
I have 3 models: class Chemicals(models.Model): id_chemical = models.AutoField(primary_key=True) id_supplier = models.ForeignKey(Suppliers, null=True, on_delete = models.CASCADE) description = models.CharField(max_length=50, blank=False, null=False) [...] class Suppliers(models.Model): id_supplier = models.AutoField(primary_key=True) company_name = models.CharField(max_length=100, blank=False, null=False) [...] class Prices(models.Model): id_chemical=models.ForeignKey(Chemicals, null=False, on_delete = models.CASCADE, related_name='prezzo') price=models.IntegerField(blank=False, null=False, default=0) price_date=models.DateField(default=datetime.date.today) I need to get the latest price by date and use it in a queryset to show it in a template. I tried this solution: def price_list(request,pk): supplier = get_object_or_404(Suppliers, pk=pk) chemicals_list = Chemicals.objects.filter(id_supplier=pk) qs=Prices.objects.all() prova=qs.values('id_chemical').annotate(latest_price=Max('price_date')) qs=qs.filter(price_date__in=prova.values('latest_price').order_by('- price_date')).filter(id_chemical__id_supplier=pk) context={'supplier': supplier, 'chemicals_list': chemicals_list, 'qs': qs, 'chem_price': chem_price} return render(request, "chemicals/price_list.html", context) Now I have what I need but if I want to show it in a template I have some problem. I tried to do this: <tbody> {% for chemical in chem_price %} <tr> <td><a href="{% url 'chemicals:single-product' pk=chemical.id_chemical %}">{{ chemical.description }}</a></td> <td>{{ qs.price }}</td> <td>{{ chemical.cov }}</td> {% endfor %} </tbody> Whit this solution, in template I see the same price for all products. I need to take some columns of my chemicals model, add latest price and show in a table row in a template. -
Making a CreateForm with choices based on database values
I am making a django project and I have a form for the User to add a Vehicle Manually that will be assigned to him. I also would like to had an option for the user to choose a vehicle based on the entries already present in the database. vehicles/models.py class Vehicle(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) nickname = models.CharField(unique = True, max_length=150) date_joined = models.DateTimeField(default=timezone.now) brand = models.CharField(max_length=150) battery = models.CharField(max_length=150) model = models.CharField(max_length=150) def __str__(self): return self.nickname def get_absolute_url(self): return reverse('vehicle-list') class Meta: db_table = "vehicles" I created a form so the user can add his Vehicles as such: vehicles/forms.py class VehicleAddFormManual(forms.ModelForm): class Meta: model = Vehicle fields = ('brand','model', 'battery', 'nickname') def __init__(self, *args, **kwargs): user = kwargs.pop('user', None) super().__init__(*args, **kwargs) self.fields['brand'] self.fields['model'] self.fields['battery'] self.fields['nickname'] The corresponding view: vehicles/views.py class AddVehicleViewManual(LoginRequiredMixin, CreateView): model = Vehicle form_class = VehicleAddFormManual def get_form_kwargs(self): kwargs = super().get_form_kwargs() kwargs['user'] = self.request.user return kwargs def form_valid(self, form): form.instance.user = self.request.user return super().form_valid(form) The html file: vehicles/templates/vehicles/vehicle_form.html {% extends "blog/base.html" %} {% block content %} {% load crispy_forms_tags %} <div class="content-section"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">New Vehicle</legend> {{ form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Submit</button> </div> </form> </div> … -
'<' not supported between instances of 'Post' and 'Post' django
when i tryed to loop the posts from the list pposts i get this err and i dont know how to fix it '<' not supported between instances of 'Post' and 'Post' TypeError at / '<' not supported between instances of 'Post' and 'Post' TypeError at / '<' not supported between instances of 'Post' and 'Post' TypeError at / '<' not supported between instances of 'Post' and 'Post' TypeError at / '<' not supported between instances of 'Post' and 'Post' #views def frontpage(request, *args, **kwargs): #loged in profile profile = Profile.objects.get(user= request.user) #check who we are following users = [user for user in profile.following.all()] #val pposts = [] qs = None #get the posts pepole we follow for u in users: p= Profile.objects.get(user=u) p_posts = p.post_set.all() pposts.append(p_posts) #my posts mposts = [] my_posts = profile.profiles_posts() mposts.append(my_posts) if len(pposts) > 0: qs = sorted(chain(*pposts), reverse=True) return render(request, 'posts/frontpage.html', {'posts': qs, 'pposts': qs }) #models class Post(models.Model): ch = [ ('pvp','pvp'), ('Default','Default'), ('bedrock','bedrock') ] xch = [ ('x1','x1'), ('x4','x4'), ('x8','x8'), ('x16','x16'), ('x32','x32'), ('x64','x64'), ('x128','x128'), ('x256','x256'), ('x512','x512'), ] vch = [ ('1.7','1.7'), ('1.8','1.8'), ('1.9','1.9'), ('1.10','1.10'), ('1.11','1.11'), ('1.12','1.12'), ('1.13','1.13'), ('1.14','1.14'), ('1.15','1.15'), ('1.16','1.16'), ('1.17','1.17'), ] author = models.ForeignKey(Profile,on_delete=models.CASCADE) title = models.CharField(max_length=150) slug = models.SlugField(null=True, editable=False) … -
django.db.utils.OperationalError: (2003, "Can't connect to MySQL server on '127.0.0.1:3307' (61)")
I got this error in the process of deploying my django app to heroku and here is the solution I figured : Change the DATABASE PORT to : '3306' and if you're still getting the error keep the port to '3307' and run your database server from Xampp. -
How to logout and destory token in PyJWT Django?
I have make a token in PyJWT like this: import jwt import datetime payload = { "id": 1, "exp": datetime.datetime.utcnow() + datetime.timedelta(minutes=1000), "iat": datetime.datetime.utcnow() } token = jwt.encode(payload, 'secret', algorithm='HS256') And sent to front and also retrive my payload like this: payload = jwt.decode(token, 'secret', algorithms=['HS256']) And now i want to destroy token in server and logout. How to do this? -
502 Bad Gateway nginx/1.18.0 (Ubuntu) DJANGO - NGINX - GUNICORN
I deleted the clinicsite file and then restored it. I restart gunicorn and nginx and the error came up And my project have this structure: gunicorn.service file [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=root Group=sudo WorkingDirectory=/root/myprojectdir ExecStart=/root/myprojectdir/myprojectenv/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ clinicsite.wsgi:application [Install] WantedBy=multi-user.target nginx.conf file user www-data; worker_processes auto; pid /run/nginx.pid; include /etc/nginx/modules-enabled/*.conf; events { worker_connections 768; # multi_accept on; } http { sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 2048; include /etc/nginx/mime.types; default_type application/octet-stream; ssl_protocols TLSv1 TLSv1.1 TLSv1.2 TLSv1.3; # Dropping SSLv3, ref: POODLE ssl_prefer_server_ciphers on; access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; gzip on; include /etc/nginx/conf.d/*.conf; include /etc/nginx/sites-enabled/*; } Do I need to share other files? -
How Can I make Image Field in Django ModelForm Required
I have a Django ModelForm with an image field and I want to add validation on empty image form field. That is, I want system validation message display when user did not select an image. I have tried but it is not working as I expected because my Validation Error Message displays only when the user selection is not an image but processes the form on none selection. In short I want to add a required attribute to the image field thereby compelling the user to select a valid image before proceeding. Here is my Model code: class ProfileUpdateForm(forms.ModelForm): class Meta: model = Profile fields = [ 'image'] def clean_image(self): image = self.cleaned_data.get('image') if not image or image == "": raise forms.ValidationError(('Invalid value'), code='invalid') return image Someone should help with solution on how best to solve this problem. -
Heroku Application Error - Giving (H=10) error
Tried lots of stackoverflow suggestion still can't get rid of this problem. Application deployed successfully but showing nothing. Error: 2022-05-30T12:04:32.860229+00:00 app[web.1]: mod = importlib.import_module(module) 2022-05-30T12:04:32.860230+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/importlib/init.py", line 126, in import_module 2022-05-30T12:04:32.860231+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level) 2022-05-30T12:04:32.860231+00:00 app[web.1]: File "", line 1050, in _gcd_import 2022-05-30T12:04:32.860231+00:00 app[web.1]: File "", line 1027, in _find_and_load 2022-05-30T12:04:32.860231+00:00 app[web.1]: File "", line 1006, in _find_and_load_unlocked 2022-05-30T12:04:32.860232+00:00 app[web.1]: File "", line 688, in _load_unlocked 2022-05-30T12:04:32.860232+00:00 app[web.1]: File "", line 883, in exec_module 2022-05-30T12:04:32.860232+00:00 app[web.1]: File "", line 241, in _call_with_frames_removed 2022-05-30T12:04:32.860232+00:00 app[web.1]: File "/app/bazaar/wsgi.py", line 16, in 2022-05-30T12:04:32.860232+00:00 app[web.1]: application = get_wsgi_application() 2022-05-30T12:04:32.860233+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application 2022-05-30T12:04:32.860233+00:00 app[web.1]: django.setup(set_prefix=False) 2022-05-30T12:04:32.860233+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/site-packages/django/init.py", line 19, in setup 2022-05-30T12:04:32.860233+00:00 app[web.1]: configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) 2022-05-30T12:04:32.860234+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/site-packages/django/conf/init.py", line 83, in getattr 2022-05-30T12:04:32.860234+00:00 app[web.1]: self._setup(name) 2022-05-30T12:04:32.860234+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/site-packages/django/conf/init.py", line 70, in _setup 2022-05-30T12:04:32.860234+00:00 app[web.1]: self._wrapped = Settings(settings_module) 2022-05-30T12:04:32.860234+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/site-packages/django/conf/init.py", line 177, in init 2022-05-30T12:04:32.860234+00:00 app[web.1]: mod = importlib.import_module(self.SETTINGS_MODULE) 2022-05-30T12:04:32.860235+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/importlib/init.py", line 126, in import_module 2022-05-30T12:04:32.860235+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level) 2022-05-30T12:04:32.860235+00:00 app[web.1]: File "", line 1050, in _gcd_import 2022-05-30T12:04:32.860235+00:00 app[web.1]: File "", line 1027, in _find_and_load 2022-05-30T12:04:32.860235+00:00 app[web.1]: File "", line 1006, in _find_and_load_unlocked 2022-05-30T12:04:32.860235+00:00 app[web.1]: File "", … -
How to use `docker compose exec` with both grep and ANSI color?
I'm only casually familiar with Docker, and how TTYs work in Linux. At work, I use commands like docker compose up to start the development stack (Postgres + Django), and docker compose exec web python manage.py ... to run Django commands during development. Conflicting problems: I can't pipe in input or grep output without adding -T. I don't know why, I just know it works with it, and not without it. I populate the DB with docker compose exec -T db psql -U username myproj < snapshot.sql because without the -T the input doesn't make it to psql. I also add -T when I have to grep the output, like: docker compose exec web python manage.py showmigrations | grep '[ ]'. However, when I use -T, it screws up ANSI coloring and formatting. Without -T: With -T: Question: What's the correct method? How do I properly connect STDIN & STDOUT without messing up color & formatting? -
Javascript, showing blob images
So I have this codes in my Django project. I am adding this with jQuery when I upload a file to html input tag which looks like: <input type="file" name="photo" accept="image/*" id="id_photo" multiple> JS (jQuery): ...append(`<img scr="${URL.createObjectURL(files[i])}" width="100px" height="100px">`) // files[i] comes from looping over multi-uploaded images html after uploading: <img scr="blob:http://127.0.0.1:8000/0929d4cc-972f-4f2b-b5ea-635020c47afa" width="100px" height="100px"> the blob image url (blob:http://127.0.0.1:8000/0929d4cc-972f-4f2b-b5ea-635020c47afa): So it actually shows the image in that url, but it looks like it can't identify the image in html. The question is why image is not shown on html? Thanks. -
Take the current admin
serializers.py class RegSerializer(serializers.ModelSerializer): admin = serializers.SlugRelatedField(slug_field='username', read_only=True) class Meta: model = Registration fields = [ 'id', 'rooms', 'first_name', 'last_name','admin', 'pasport_serial_num', 'birth_date', 'img', 'visit_date', 'leave_date', 'guest_count', 'room_bool'] models.py class Rooms(models.Model): objects = None room_num = models.IntegerField(verbose_name='Комната') room_bool = models.BooleanField(default=True, verbose_name='Релевантность') category = models.CharField(max_length=150, verbose_name='Категория') price = models.IntegerField(verbose_name='Цена (сум)', null=True) def __str__(self): return f'{self.room_num}' class Meta: verbose_name = 'Комнату' verbose_name_plural = 'Комнаты' class Registration(models.Model): objects = None rooms = models.ForeignKey(Rooms, on_delete=models.CASCADE, verbose_name='Номер', help_text='Номер в который хотите заселить гостя!', ) first_name = models.CharField(max_length=150, verbose_name='Имя') last_name = models.CharField(max_length=150, verbose_name='Фамилия') admin = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='Администратор') pasport_serial_num = models.CharField(max_length=100, verbose_name='Серия паспорта', help_text='*AB-0123456') birth_date = models.DateField(verbose_name='Дата рождения') img = models.FileField(verbose_name='Фото документа', help_text='Загружайте файл в формате .pdf') visit_date = models.DateField( default=django.utils.timezone.localdate, verbose_name='Дата прибытия') leave_date = models.DateField(blank=True, null=True, verbose_name='Дата отбытия', default='После ухода!') guest_count = models.IntegerField(default=1, verbose_name='Кол-во людей') room_bool = models.BooleanField(default=False, verbose_name='Релевантность', help_text='При бронирование отключите галочку') price = models.IntegerField(verbose_name='Цена (сум)', null=True) def __str__(self): return f'{self.rooms},{self.last_name},{self.first_name},{self.room_bool}' class Meta: verbose_name = 'Номер' verbose_name_plural = 'Регистрация' how can I make it so that the name of the user who registered nomautofdn is indicated in the admin field and without the right to change only readonly? can this be done at all? thanks in advance for your reply -
django social all auth - multiple user type
I have two Registration pages: Register as Buyer, Register as Seller. on both Pages , I've included Normal Registration and social authentication using Google and Facebook. I've added social authentication using Django all-auth, but cannot get user_role. [1][Registration Page]: after Registration : user is redirected to home page and as there is no user_role set in social authentication , one cannot access Buyer or Seller 's section. [2][Signup with Google]: After signup : User is registered as Blank Login. check home page after Google signup: MY TASK : Is to assign user_type on both the buttons: Buyer and Seller. on click button redirect user to its particular Registration Page and Login/Signup with Social Authentication and after Successful-Login Redirect User to its Page and show user_type in Django-administration-panel as: User_type: Buyer; Email:test1234@gmail.com; is_active: True -
One app in Django is enough for whole website?
I'm new to Django framework and currently working on an ecommerce website. Not sure what would be better, when creating new project and new app in Django, does a single app is enough and fine for whole website functionally(all HTML pages, user login/registration etc) or should I use separate apps in my project?