Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to load images in django reportlab
hi i am trying to load a image onto a pdf with reportlab but i keep getting OSError at /view_checklist_print/1 Cannot open resource "check_box_outline_blank.svg" This is my test i21 = False This is my view def checklist_report(reques): buffer = io.BytesIO() c = canvas.Canvas(buffer, pagesize=(8.5 * inch, 11 * inch)) def checkboxgenerator(a, b, checkdata): checked = 'check_box_FILL.svg' unchecked = 'check_box_outline_blank.svg' x_start = a y_start = b blankbox = c.drawImage(unchecked, x_start, y_start, width=120, preserveAspectRatio=True, mask='auto') checkedbox = c.drawImage(checked, x_start, y_start, width=120, preserveAspectRatio=True, mask='auto') if checkdata == False: return blankbox else: return checkedbox checkboxgenerator(20, 300, i21) c.showPage() c.save() buffer.seek(0) return FileResponse(buffer, as_attachment=False, filename=test.pdf') Please can you help me load the image correctly -
Apple SSO breaks after Django 4 upgrade
After upgrading from django 3 to django 4, the "Sign in with Apple" feature started breaking with the following error Your request could not be completed because of an error. Please try again later. The javascript, the frontend html, and the Apple ID url are all identical, and there is no useful error in the console. What is going on? -
Disable a charfield in DJANGO when I'm creating a new User
I'm trying to do a crud in Django, it's about jefe and encargados. When I am logged in as an administrator, it has to allow me to create a encargados, but not a manager, but if I log in as a manager, it has to allow me to create a new encargados. For the jefe I am using a table called users and for the admin I am using the one from the Django admin panel. Here are the models: roles = ( ('encargado', 'ENCARGADO'), ('jefe','JEFE'), ) class Usuarios(models.Model): id = models.BigAutoField(primary_key=True) nombre = models.CharField(max_length=30) rol = models.CharField(max_length=30, choices=roles, default='encargado') correo = models.CharField(max_length=30) contraseña = models.CharField(max_length=30) cedula = models.CharField(max_length=30) class Meta: db_table = 'usuarios' This is the create view class UsuarioCrear(SuccessMessageMixin, CreateView): model = Usuarios form = Usuarios fields = "__all__" success_message = 'usuario creado correctamente !' def get_success_url(self): return reverse('leer') This would be the html to create, here I put a restriction that the roles are only seen as administrator. but really what is necessary is that if I am as an administrator it only lets me select the jefe and if I am as a jefe it only lets me select encargados {% csrf_token %} <!-- {{ form.as_p … -
Django with bootstrap DateTimePicker: inputElement.dataset is undefined
When I try to add options to dateTimePicker it stops working. Website raise "Something went wrong! Check browser console for errors. This message is only visible when DEBUG=True", and when I enter the console on the browser I see this: Uncaught TypeError: inputElement.dataset is undefined and the error picks up from https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css in the datapicker-widget.js file class Topic(models.Model): speaker = models.ForeignKey(Profile, on_delete=models.SET(GUEST_ID)) seminar = models.ForeignKey(Seminar, on_delete=models.CASCADE) title = models.CharField(max_length=200) description = models.TextField(default='') speaker_name = models.CharField(max_length=200, default='') date = models.DateTimeField(null=True, blank=True) def __str__(self): return self.title class TopicCreateView(LoginRequiredMixin, CreateView): model = Topic form_class = TopicPageForm template_name = 'seminar/topic_form.html' def get_initial(self, *args, **kwargs): initial = super(TopicCreateView, self).get_initial(**kwargs) initial = initial.copy() initial['speaker'] = self.request.user.profile initial['speaker_name'] = self.request.user initial['date'] = datetime.datetime.now() return initial ... ` {% extends "seminar/base.html" %} {% load django_bootstrap5 %} {% load crispy_forms_tags %} {% block head_content %} {% endblock %} {% block content %} <div class="content-section"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Topic</legend> {{ form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Save</button> </div> </form> </div> {% endblock content %} head <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous"> <link rel="stylesheet" type='text/css' href="{% static 'users/style.css' %}"> <link rel="stylesheet" type='text/css' href="{% static 'seminar/main.css' %}"> bottom body <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.2/dist/umd/popper.min.js" … -
Trying to run a container on docker but can not access the website of the application we created
We've been using python3 and Docker as our framework. Our main issue is that while we try to run the docker container it redirects us to the browser but the website can not be reached. But it is working when we run the commands python manage.py runserver manualy from the terminal of VS code here is the docker-compose.yml file ''' version: "2.12.2" services: web: tty: true build: dockerfile: Dockerfile context: . command: bash -c "cd happy_traveller && python manage.py runserver 0.0.0.0:8000 " ports: \- 8000:8000 restart: always the docker file FROM python:3.10 EXPOSE 8000 WORKDIR / COPY happy_traveller . COPY requirements.txt . RUN pip install -r requirements.txt COPY . . and the app structure |_App_Folder |_happy_traveller |_API |_paycache |_core |_settings |_templates |_folder |_folder |_folder |_manage.py |_dockerfile |_docker-compose.yml |_requirements.txt |_readmme.md |_get-pip.py We would really apreciate the help. thank you for your time -
Reverse for 'detalle_reserva' with arguments '('',)' not found. 1 pattern(s) tried: ['reserva/(?P<reserva_id>[^/]+)/\\Z']
Please help me, I don't know why I get this error, I'm following a youtube tutorial and I don't understand why the error. i try changing the path in urls but it didn't work. I was looking for more solutions to the same problem and none of them work. models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class Reserva(models.Model): auto = models.CharField(max_length=100) fecha = models.DateTimeField(auto_now_add=True) fecha_reserva = models.DateField(null=True) hora1 = '9:00am - 10:00am' hora2 = '10:00am - 11:00am' hora3 = '11:00am - 12:00pm' hora4 = '12:00pm - 13:00pm' hora5 = '14:00pm - 15:00pm' hora6 = '15:00pm - 16:00pm' hora7 = '16:00pm - 17:00pm' hora8 = '17:00pm - 18:00pm' hora_reserva_CHOICES = [ (hora1, '9:00am - 10:00am'), (hora2, '10:00am - 11:00am'), (hora3, '11:00am - 12:00pm'), (hora4, '12:00pm - 13:00pm'), (hora5, '14:00pm - 15:00pm'), (hora6, '15:00pm - 16:00pm'), (hora7, '16:00pm - 17:00pm'), (hora8, '17:00pm - 18:00pm') ] hora_reserva = models.CharField( max_length=17, choices=hora_reserva_CHOICES, default=hora1 ) Mantención = 'Mantención' Reparación = 'Reparación' Limpieza = 'Limpieza' Servicios_CHOICES = [ (Mantención, 'Mantención'), (Reparación, 'Reparación'), (Limpieza, 'Limpieza'), ] Servicios = models.CharField( max_length=10, choices=Servicios_CHOICES, default=Limpieza, ) User = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.auto + ' -by ' + self.User.username url.py from django.contrib … -
How to install setuptools for python based project (ModuleNotFoundError: No module named 'setuptools')?
I 've a running Django project created with poetry I 'm trying to install its dependencies using poetry install using python 3.9` I 'm getting this error while installing cwd: C:\Users\Lenovo\AppData\Local\Temp\pip-req-build-1hvchk7d\ Complete output (3 lines): Traceback (most recent call last): File "<string>", line 1, in <module> ModuleNotFoundError: No module named 'setuptools' ---------------------------------------- WARNING: Discarding file:///C:/Users/Lenovo/AppData/Local/pypoetry/Cache/artifacts/0c/05/66/5aa05d2bdbafe6e3783cd138cb601eb252fdcfc29ba618431cd24deeaa/drf-access-policy-1.3.0.tar.gz. Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output. ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output. WARNING: You are using pip version 21.1.2; however, version 22.3.1 is available. You should consider upgrading via the 'C:\Users\Lenovo\AppData\Local\pypoetry\Cache\virtualenvs\vending-machine-api-l-EiZrwy-py3.9\Scripts\python.exe -m pip install --upgrade pip' command. at ~\.poetry\lib\poetry\utils\env.py:1101 in _run 1097│ output = subprocess.check_output( 1098│ cmd, stderr=subprocess.STDOUT, **kwargs 1099│ ) 1100│ except CalledProcessError as e: → 1101│ raise EnvCommandError(e, input=input_) 1102│ 1103│ return decode(output) 1104│ 1105│ def execute(self, bin, *args, **kwargs): I 've tried these solution but none worked for me : pip install --upgrade pip pip install --upgrade wheel pip install setuptools -
Django App on Heroku: Trouble Connecting to Postgres Database After Upgrade
I'm having trouble connecting (?) to a Heroku Postgres mini database after upgrading from a free Heroku Postgres database. I have a Django app using hobby Heroku dynos. With Heroku's free services coming to an end, I tried to upgrade from the free Heroku Postgres service to the mini plan. I followed the steps for the pg:copy method. Something went wrong when I tried to deprovision the primary database. The release log on my Heroku Dashboard provides this error message: Traceback (most recent call last): File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/base/base.py", line 219, in ensure_connection self.connect() File "/app/.heroku/python/lib/python3.9/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/base/base.py", line 200, in connect self.connection = self.get_new_connection(conn_params) File "/app/.heroku/python/lib/python3.9/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/postgresql/base.py", line 187, in get_new_connection connection = Database.connect(**conn_params) File "/app/.heroku/python/lib/python3.9/site-packages/psycopg2/__init__.py", line 127, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: connection to server on socket "/var/run/postgresql/.s.PGSQL.5432" failed: No such file or directory Is the server running locally and accepting connections on that socket? The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/app/manage.py", line 22, in <module> main() File "/app/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() … -
How to add python version as environment variable in poetry?
I have created a simple django project using poetry in my local machine , the pyproject.toml is the following [tool.poetry] name = "vending-machine-api" version = "0.1.0" description = "" authors = ["mohamed ibrahim"] readme = "README.md" packages = [{include = "vending_machine_api"}] [tool.poetry.dependencies] python = "^3.10" django = "^4.1.3" django-rest-knox = "^4.2.0" djangorestframework = "^3.14.0" django-model-utils = "^4.3.1" drf-access-policy = "^1.3.0" pre-commit = "^2.20.0" [build-system] requires = ["poetry-core"] build-backend = "poetry.core.masonry.api" It has my python3.10 from this machine i have created the project from I'm trying to run the project from another machine which has python version 3.9 but I 'm getting this error The currently activated Python version 3.9.6 is not supported by the project (^3.10). Is there any way to add the python version from created project to be compatible with older versions ? -
Open listView with foreignkey from another listview with Django
I am working on a product overview page in Django. For this I have three models: category, brand, product. I have created a View with ListView of the category. I loop through them to display them. I then want to open another overview of all brands within that category. How do I do this? Here are my models: class Category(models.Model): category_name = models.CharField(max_length=200) sub_category = models.CharField(max_length=200,blank=True,null=True) category_picture = models.ImageField(upload_to='category/', null=True, blank=True) def __str__(self): if self.sub_category is None: return self.category_name else: return f" {self.category_name} {self.sub_category}" class Meta: ordering = ['category_name'] class Brand(models.Model): category = models.ForeignKey('Category', on_delete=models.SET_NULL,null=True,blank=True) brand_name = models.CharField(max_length=200) brand_owner = models.CharField(max_length=200) brand_story = models.TextField() brand_country = models.CharField(max_length=200) def __str__(self): return f"{self.brand_name}" class Bottle(models.Model): category_name = models.ForeignKey('Category', on_delete=models.SET_NULL,null=True,blank=True) brand = models.ForeignKey('Brand', on_delete=models.CASCADE) bottle_name = models.CharField(max_length=255) bottle_info = models.TextField() bottle_tasting_notes = models.TextField() bottle_barcode = models.IntegerField() bottle_image = models.ImageField(upload_to='bottles/',null=True) def __str__(self): return f"{self.brand.brand_name} {self.bottle_name}" How do I open a listview of all brands within a certain category from a link of the category listview? Thank you. -
Customize/remove select box blank option in Django
Code category_options = ( ('th','Technology'), ('sc','Science'), ('f','Food'), ('t','Travel'), ('h','Health'), ('fa','Fashion'), ) class Blog(models.Model): title = models.CharField(max_length=150) description = models.TextField() category = models.CharField(choices=category_options,max_length=2) View image It creates an option at the top of the list that has no value and displays as a series of dashes: <option value="">---------</option> What is the cleanest way to remove this auto-generated option from the select box? I am expecting like this <option value="">Select category</option> Guys can you help me to update the empty dashes in django -
Create "ListField" that expands dynamic with an "add new element" button, Django
This question should maybe be split into two questions, but since the HTML solution (could) depend on the model (and vice versa) I'm putting it into one question. I have a model for recipes: from django.db import models class Recipe(models.Model): title = models.CharField("Title", max_length = 64, primary_key=True) what_to_do = models.TextField("What to do") n_persons = models.IntegerField(default = 2) what I want to to, is to add a way of storing ingredients for a recipe. My first thought was storing them in a list of dict, usgin the JSONField e.g [{"what":"egg","units":"pcs","N":2},{"what":"flour", "units":"gram", "N":200}]. Then I iterate over each ingredients in the template and list it like <div class = "container"> {% for ing in recipe.ingredients %} <li> {{ing.what}} - {{ing.N}} {{ing.units}} </li> {% endfor %} </div> which works fine. The issue is; how do I make some user-friendly way of adding a new ingredient to a recipe? Optimally in my template I would have 3 columns with fields like "what" "how much?" " units -------+----------------+------- ====== ====== ====== | | | | | ====== ====== ====== where the user can write what they would like. But the user should be able to add a new line if they want to add more … -
Django runserver_plus pyOpenSSL not installed error, although it is
So I try to run runserver_plus using ssl: python manage.py runserver_plus --cert-file cert.crt Then I get following error: CommandError: Python OpenSSL Library is required to use runserver_plus with ssl support. Install via pip (pip install pyOpenSSL). But the deal is that pyOpenSSL is already installed within my environment. Here is pip list output: asgiref (3.5.2) certifi (2022.9.24) cffi (1.15.1) charset-normalizer (2.1.1) cryptography (38.0.3) defusedxml (0.7.1) Django (3.0.14) django-extensions (2.2.5) idna (3.4) oauthlib (3.2.2) Pillow (7.0.0) pip (9.0.1) pkg-resources (0.0.0) pycparser (2.21) PyJWT (2.6.0) pyOpenSSL (19.0.0) python3-openid (3.2.0) pytz (2022.6) requests (2.28.1) requests-oauthlib (1.3.1) setuptools (39.0.1) six (1.16.0) social-auth-app-django (3.1.0) social-auth-core (4.3.0) sqlparse (0.4.3) urllib3 (1.26.12) Werkzeug (0.16.0) wheel (0.38.4) Screenshot: Thanks in forward for any help! I've tried to install different versions of pyOpenSSL, both erlier and later. Unsuccessfully. Runserver_plus starts successfully without additional parameters, but my point is to access virtual server securely. -
How to work with MultipleCheckBox with Django?
good afternoon, I'm new with django and I'm trying to make an application that registers the attendance of entrepreneurs (I'm currently working with this). There are some services that I would like to select, sometimes the same person requires more than one service per appointment. However, part of the application uses the Models and part uses the Forms, I'd like to keep the two ones separate to keep the code organized, but I have no idea how to do it, I even created a separate class just for the tuple that holds the values, but no I managed to implement, can anyone help me? Here are the codes: models.py from django.db import models from django_cpf_cnpj.fields import CPFField, CNPJField class CadastroEmpreendedor(models.Model): ABERTURA = 'ABERTURA MEI' ALTERACAO = 'ALTERAÇÃO CADASTRAL' INFO = 'INFORMAÇÕES' DAS = 'EMISSÃO DAS' PARC = 'PARCELAMENTO' EMISSAO_PARC = 'EMISSÃO DE PARCELA' CODIGO = 'CÓDIGO DE ACESSO' REGULARIZE = 'REGULARIZE' BAIXA = 'BAIXA MEI' CANCELADO = 'REGISTRO BAIXADO' descricao_atendimento = ( (ABERTURA, 'FORMALIZAÇÃO'), (ALTERACAO, 'ALTERAÇÃO CADASTRAL'), (INFO, 'INFORMAÇÕES'), (DAS, 'EMISSÃO DAS'), (PARC, 'PARCELAMENTO'), (EMISSAO_PARC, 'EMISSÃO DE PARCELA'), (CODIGO, 'CÓDIGO DE ACESSO'), (REGULARIZE, 'REGULARIZE'), (BAIXA, 'BAIXA MEI'), (CANCELADO, 'REGISTRO BAIXADO'), ) cnpj = CNPJField('CNPJ') cpf = CPFField('CPF') nome = models.CharField('Nome', … -
How to get country name and state name from pincode in django?
I want to get state name and country name from pincode. I'm doing a cargo application using django,in that while user giving his pincode automatically state name and country name gas to be displayed by default. -
Pydantic nested model field throws value_error.missing
Having following code running fine with Django and Ninja API framework. Schema for data validation: class OfferBase(Schema): """Base offer schema.""" id: int currency_to_sell_id: int currency_to_buy_id: int amount: float exchange_rate: float user_id: int added_time: datetime = None active_state: bool = True class DealBase(Schema): """Base deal schema.""" id: int seller_id: int buyer_id: int offer_id: int deal_time: datetime = None class UserExtraDataOut(UserBase): """Extended user schema with extra data response.""" offers: List[OfferBase] sold: List[DealBase] bought: List[DealBase] Endpoint with user object. Please, note, User model is not modified: @api.get("/users/{user_id}", response=UserExtraDataOut, tags=["User"]) def get_user_info(request, user_id): """Get user profile information with offers and deals.""" user = get_object_or_404(User, pk=user_id) return user Deal model: class Deal(models.Model): """Deal model.""" seller = models.ForeignKey( to=User, related_name="sold", on_delete=models.PROTECT, verbose_name="Seller" ) buyer = models.ForeignKey( to=User, related_name="bought", on_delete=models.PROTECT, verbose_name="Buyer" ) offer = models.ForeignKey( to="Offer", on_delete=models.PROTECT, verbose_name="Offer" ) deal_time = models.DateTimeField(auto_now=True, verbose_name="Time") It gives me this response: { "id": 0, "username": "string", "first_name": "string", "last_name": "string", "email": "string", "offers": [ { "id": 0, "currency_to_sell_id": 0, "currency_to_buy_id": 0, "amount": 0, "exchange_rate": 0, "user_id": 0, "added_time": "2022-11-22T18:37:47.573Z", "active_state": true } ], "sold": [ { "id": 0, "seller_id": 0, "buyer_id": 0, "offer_id": 0, "deal_time": "2022-11-22T18:37:47.573Z" } ], "bought": [ { "id": 0, "seller_id": 0, "buyer_id": 0, "offer_id": 0, "deal_time": … -
how to put my form in line orientation (horizontal). django forms
I want to put my form in horizontal.I tried to do this, but it got unformatted and disorganized MY HTML: <div class="tab-pane fade container-fluid p-2" id="profile" role="tabpanel" aria-labelledby="profile-tab"> <h6 class="m-0 font-weight-bold text-primary">Horas Adicionais</h6> <div class="row mt-4"> <div class="col"> {{ form_funcionarioadicional.management_form }} {% for fa in form_funcionarioadicional %} <div class="faform row"> <div class="col"> {{fa}} </div> </div> {% endfor %} </div> </div> </div> currently it is like this, I wanted to leave it horizontal How can I fix this in html, or in forms.py? -
What is the difference between request.POST.get and request.POST
usually I use POST or GET requests except for GET.get paginations, but I don't understand the concept there are only two possibilities POST or GET . example even if there is the same effect I do not understand the difference between request.GET.get('page') and request.GET["page"] request.POST['rate'] and request.POST.get('rate') -
Reverse for 'admin_update' with arguments '('',)' not found. 1 pattern(s) tried: ['admin_update/(?P<lesson_id>[^/]+)$']
I'm trying to pass arguments to edit table values. Would be grateful if anyone could breakdown the solution. views.py ` #@login_required(login_url='/admin_login/') def AdminManageRequests(request): lessons = Lesson.objects.all() return render(request,'admin/manage_requests.html',{'lessons':lessons}) def AdminUpdateRequests(request, lesson_id): lesson = Lesson.objects.get(pk=lesson_id) form = StudentRequestForm(request.POST or None, instance=lesson) context = { 'lesson':lesson, 'form':form } return render(request, 'admin/update_requests.html',context) ` urls.py ` path('admin_update/<lesson_id>', views.AdminUpdateRequests, name='admin_update'), ` manage_requests.html ` {% extends 'admin/admin_home_base.html' %} {% block admin_content %} <div> <h3 class="display-8" style="text-align:center"> Admin Lesson Request Management </h3> <hr class="my-4"> <p style="text-align:center"> You can view fulfilled and unfulfilled lesson requests. </p> <p class="lead" style="text-align:center"> {% include 'admin/partials/fulfilled_lessons.html' %} <br> {% include 'admin/partials/unfulfilled_lessons.html' %} </p> </div> {% endblock %} ` lessons_table_base.html ` <div class="card"> <div class="card-header"> <h5 class="card-title">{% block card_title %}{% endblock %}</h5> <div class="card-body table-responsive p-0"> <table class="table table-hover text-nowrap"> <thead> <tr> <th>Lesson ID</th> <th>Lesson Name</th> <th>Student</th> <th>Teacher</th> <th>Interval (Days)</th> <th>Duration (Minutes)</th> <th></th> </tr> </thead> <tbody> {% for lesson in lessons %} {% block lessons_content %} {% endblock %} {% endfor %} </tbody> </table> </div> </div> </div> ` fulfilled_lessons.html ` {% extends 'admin/partials/lessons_table_base.html' %} {% load widget_tweaks %} {% block card_title %} Fulfilled Requests&nbsp;&nbsp;<i class="bi-send-check-fill"></i> {% endblock %} {% block lessons_content %} {% if not lesson.is_request %} <tr> <td>{{ lesson.lesson_id }}</td> <td>{{ lesson.lesson_name … -
Cannot import 'Questions'. Check that 'questions.apps.QuestionsConfig.name' is correct
hi everybody i have a message django.core.exceptions.ImproperlyConfigured: Cannot import 'Questions'. Check that 'questions.apps.QuestionsConfig.name' is correct. apps.py in application questions dirctory from django.apps import AppConfig class OrdersConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'Questions' settings.py INSTALLED_APPS = [ 'questions.apps.QuestionsConfig', who can i solve this problem -
Specific model not visible for staff account in Django admin. Other models displaying as expected
I have several models in my project. All models are visible from the staff account if I add permissions for them, but one particular model is not displayed and I can't figure out why. This model is not displayed even if I add direct permissions to the user or add to a certain group with the necessary permissions, however, if I check the "Superuser status" box in the user settings, then this model appears. What could be the matter? -
TypeError at /admin/login/ 'NoneType' object is not iterable
TypeError at /admin/login/ 'NoneType' object is not iterable Request Method: GET Request URL: http://127.0.0.1:8000/admin/login/?next=/admin/ Django Version: 4.1.3 Exception Type: TypeError Exception Value: 'NoneType' object is not iterable Exception Location: E:\mohammad\Dijongo\myprojects\Greany\lib\site-packages\debug_toolbar\panels\templates\panel.py, line 47, in _request_context_bind_template Raised during: django.contrib.admin.sites.login Python Executable: E:\mohammad\Dijongo\myprojects\Greany\Scripts\python.exe Python Version: 3.10.1 Python Path: ['E:\mohammad\Dijongo\myprojects\Greany\src', 'C:\Program Files\Python310\python310.zip', 'C:\Program Files\Python310\DLLs', 'C:\Program Files\Python310\lib', 'C:\Program Files\Python310', 'E:\mohammad\Dijongo\myprojects\Greany', 'E:\mohammad\Dijongo\myprojects\Greany\lib\site-packages'] Server time: Tue, 22 Nov 2022 17:41:41 +0000 project repo: https://github.com/pythone-developer/Ecomerce-greany project repo: https://github.com/pythone-developer/Ecomerce-greany -
pywhatkit how to close youtube after song ends?
is it possible to close the youtube tab after the song ends? I want to implement python code into raspberry so I can manually close the tab each time -
full link for media in django-rest
I wrote this view: api_view(["GET"]) def article_grid_list(request): # fetched data from database data = Articles.objects.all().order_by("-created_date")[:11] pinned_article = Articles.objects.get(pinned=True) # serialized data pinned_data = ArticlesSerializer(pinned_article) horizontal_data = ArticlesSerializer(data[:3], many=True) small_data = ArticlesSerializer(data[3:8], many=True) card_data = ArticlesSerializer(data[8:], many=True) final_data = { "pinned":pinned_data.data, "horizontal": horizontal_data.data, "small": small_data.data, "card": card_data.data } when I print result of this route, I'm getting 'cover' field like this : "cover": "/media/article/artice_cover_NkOUuZ7vH3zEejCgV.jpg", but when I write this function like ModelViewSet I'm getting full url of cover field and I want to get full url in every reqeust modelViewSet Example : class ArticleGridList(viewsets.ModelViewSet): queryset = Articles.objects.all().order_by("-created_date") serializer_class = ArticlesSerializer I except like this : "cover": "http://localhost:8000/media/article/artice_cover_NkOUuZ7vH3zEejCgV.jpg", my app urls.py file : router = routers.SimpleRouter() router.register('articles', ArticlesViewSet) urlpatterns = [ path("article-grid-list/", article_grid_list) ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += router.urls``` -
My localhost:8000 just stopped to work. How can I get it back?
I am using ubuntu 20.04 I do not know if it matters, but I tried to see if the 8000 PORT was being used before I tried to run, and it was not. I was working on my Django project, running my localhost:8000 last night, but it stopped. Everything I have is a infinite loading. So, I returned today and I could not run my project. I do not know what happened. So, I started a new branch from the working code to check if it stopped because of me, but nothing changed. I've tried to restart and turn off my computer, I've erased my cache, I've tried in 4 different browsers (chrome, firefox, opera, brave), I've tried to re-run, and I've tried to use my local IP, but nothing happened. I am expecting to run again my project and I do not know if is related to my computer.