Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I have problem when I try to put my project developed by django in a conteiner docker:
this is my dockerfile FROM python:3.10 # Establece el directorio de trabajo en /app WORKDIR /app # Copia el archivo requirements.txt al contenedor en /app/ COPY requirements.txt /app/ # Crea y activa el entorno virtual RUN python -m venv venv RUN /bin/bash -c "source venv/bin/activate" # Instala las dependencias RUN pip install --no-cache-dir -r requirements.txt # Copia el contenido del directorio actual al contenedor en /app/ COPY . /app/ # Indica que la aplicación se ejecutará en el puerto 9005 EXPOSE 9005 # Define la variable de entorno para Django ENV DJANGO_SETTINGS_MODULE=Arriendos_Backend.settings # Instala Gunicorn RUN pip install gunicorn CMD ["gunicorn", "-c", "gunicorn_config.py", "Arriendos_Backend.wsgi:application"] like you noticed Im trying to build the project with gunicorn but the HTML doesn´t work enter image description here I try to take off the static files but the problem is still present -
ArrayField custom widget similar to JSONFieldWedget
I want to display the content of an ArrayField in a Django admin panel similar to how a JSONField is displayed using JSONFieldWidget My model's array field is a bit long to use something like: django-better-admin-arrayfield I will not be saving or updating anything via Django admin panel. -
can you remove old migrations file after changing models location django
I am currently refactoring a django project. It had a few apps with unrelated models (ex: customer in the product app) that I decided to consolidate into a single core app. I use the third method shown in this article: https://realpython.com/move-django-model/#the-django-way-rename-the-table. Everything worked well and I didn't lose any data, but now I have some empty apps that have a lot of migrations files. I would like to delete those apps to have a cleaner project structure. Would deleting the migrations break everything? I do have multiple backups of the database in case something goes wrong. -
All messages sent at once at the end of all iterations django layers
I want to send messages to client side by websocket one by one. Instead they are sent at the end of all iterations at once. I use AsyncWebsocketConsumer, so it should be fine. Another important things is that i need to access my consumer method to send data outside of TaskStatusConsumer class, so I use channel groups. My consumers.py file: class TaskStatusConsumer(AsyncWebsocketConsumer): async def connect(self): path = [el for el in self.scope['path'].split('/') if el] self.id_config = path[-1] self.group_name = f"task_{self.id_config}" await self.channel_layer.group_add( self.group_name, self.channel_name ) await self.accept() async def disconnect(self, close_code): await self.channel_layer.group_discard( self.group_name, self.channel_name ) async def websocket_receive(self, event): for fr in range(1, 3): print(f'start fr {fr}') await send_task_status(self.id_config, 'pending', fr) print(f'end fr {fr}') time.sleep(1) async def task_status(self, message): print('start task status') data = { 'task_id': message['type'], 'status': message['status'], } await self.send(json.dumps(data)) print('end task status') Function that sends task status to group: async def send_task_status(id_config, status, iteration): channel_layer = get_channel_layer() print(f'start send task status') await channel_layer.group_send( f"task_{id_config}", { 'type': 'task_status', 'status': status, 'iteration': iteration } ) print(f'end send task status') So at this picture you can see that sending messages to client starts after sending data to group: -
In the latest vers Django 5.0.1 i can't use files in the Static folder. The settings are correct, maybe there is a conflict with the template folder?
In the latest version of Django 5.0.1, I'm having problems using css and js contained in a Static folder. I have already read several similar questions (be careful, they are old) and I also read the official Django documentation, none of them were able to help me. My code seems to be set up correctly, but it doesn't work. It means that perhaps the problem is something else, perhaps there is a conflict with the template folder (explained later). The static folder is located in this path App1/static. So the css I would like to use is located in App1/static/css/style.css So I'm using: <link rel="stylesheet" type="text/css" href="{% static 'css/style.css' %}"> PROBLEM: The css does not apply when i open the web page. Furthermore, if I try to click on the link above the css, I receive a joke that says "It was not possible to open 'style.css' %} and asks me to create the file. The path of the file that will be created will be App1 > templates > {% static 'css > style.css' %}. Why in templates? MY SETTINGS ARE INDEX.HTML I'm using {% load static %} at the beginning of index.html I show you my 2 attempted … -
Adding dynamic url in a reverse function in django
I'm building a blog app, and when posting a comment, and a reply to a comment, the page redirects to the top of the post page, I want it to redirect into the comment\reply that was posted, or scroll into it if you will. for example, when posting, I want it to go to http://127.0.0.1:8000/post/first#comment-12 to implement something like this: return HttpResponseRedirect(reverse(f'post_page#comment-{str(comment.id)}', kwargs={ 'slug': slug })) views.py if request.POST: comment_form = CommentForm(request.POST) if comment_form.is_valid: if request.POST.get('parent'): parent_id = request.POST.get('parent') parent = Comments.objects.get(id=parent_id) if parent: comment_reply = comment_form.save(commit=False) comment_reply.parent = parent comment_reply.post = post comment_reply.save() else: comment = comment_form.save(commit=False) post_id = request.POST.get('post_id') post = Post.objects.get(id=post_id) comment.post = post comment.save() return HttpResponseRedirect(reverse('post_page', kwargs={ 'slug': slug })) urls.py urlpatterns = [ path('', views.index, name='index'), path('post/<slug:slug>', views.post_page, name='post_page') ] -
Trying to get the esm-bundler to render my templates in-browser
I'm looking for some advice on using the runtime compiler to render Vue 3 elements in the browser with Django 5.0.1. Django handles the backend and uses static html files to display the information to the user. With Vue 2, I was able to set runtimeCompiler: true, but this isn't supported with Vue 3 and Vite. I followed this discussion in the Vite repo on GitHub as it describes the problem I'm having, but after making all the necessary changes, the Vue components don't get rendered in the browser. If I inspect the element in the developer console, I can see the element that should be displayed on the screen, it's nested in a #document_fragment element. I seem to be missing a step that I can't seem to find in the documentation. Can anyone share any insight as to what I am missing or share any resources that might give me the information I need? Any resources I've found so far were either Vue 2 related or didn't solve my issue. I've included all the relevant code snippets but if you need to see anything else please let me know. Thanks in advance! Element in the developer console: <template> #document_fragment … -
How to conficure django LOGGING with azure-log-analytics?
I have a Django app, I want to log to azure log analytics LOGGING = { "version": 1, "disable_existing_loggers": False, "handlers": { 'azure_log_analytics': { 'level': 'DEBUG', 'class': 'azure.loganalytics.handlers.LogAnalyticsHandler', 'workspace_id': os.environ.get('LOG_ANALYTICS_WORKSPACE_ID', None), 'workspace_key': os.environ.get('LOG_ANALYTICS_WORKSPACE_KEY', None), }, }, "loggers": { "API": { "handlers": ["azure_log_analytics"], "level": "INFO", "propagate": False, }, } } ValueError: Cannot resolve 'azure.loganalytics.handlers.LogAnalyticsHandler': No module named 'azure.loganalytics.handlers' -
Pagination with Django and Nuxt 3
I use Django for backend and nuxt3 for frontend My problem is that: Error when I use pagination in Django: Failed to load resource: the server responded with a status of 500 (Internal Server Error) But without activating pagination, it shows my content without any problem I want to work without page refresh and ajax pagination Thank you my code : index.vue <template> <h1>test</h1> <div v-for="portfolio in portfolios" :key="portfolio.id"> <h1>{{ portfolio.title }}</h1> </div> <div class="pagination"> <ul class="inline-flex"> <li> <button class="c-pointer"> <svg><use href="#arrowbefore"></use></svg> </button> </li> <li> <button class="c-pointer"> <svg><use href="#arrownext"></use></svg> </button> </li> </ul> </div> </template> <script setup> const { public: {apiURL} } = useRuntimeConfig(); const { data: portfolios, refresh } = await useFetch(`${apiURL}/portfolio`); </script> views.py class PortfolioApiViewPagination(PageNumberPagination): page_size = 1 class PortfolioApiView(generics.ListCreateAPIView): queryset = Portfolio.objects.all() serializer_class = PortfolioSerializer pagination_class = PortfolioApiViewPagination settings.py REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', 'PAGE_SIZE': 8 } Please tell me the best solution -
Django: Basic auth on only certain URL paths?
I would like to password-protect only certain parts of my Django app with basic-auth. I'd like to protect all URLs except anything under /api. I'm trying to use the django-basicauth package to do this. I've configured it as follows. My app has three parts: /api /candc /places In candc/localsettings.py I've added: BASICAUTH_USERS = { "myuser": "mypass" } The candc/urls.py file looks like this: urlpatterns = [ path('', include('places.urls')), path('api/1.0/', include('api.urls')), ] Then in my places/views.py file, I've added decorators to the URLs I want to protect, like this: from basicauth.decorators import basic_auth_required @basic_auth_required( def index(request): template = loader.get_template('index.html') return HttpResponse(template.render({}, request)) However, my app is asking for basic-auth protect on URLs under /api as well. (In fact it's not even showing the dialog, just returning 403s for any requests.) How can I configure this so URLs under /api are not password-protected, but everything else is? -
Django CSRF token not saving to browser cookies in Production environment, but working in Development environment
We have created a Django application to create a Shopify Application. We are having issues with out production environment we AJAX calls to the Django application are failing because the CSRF token is not being saved to cookies and therefore nothing gets parsed in the AJAX call headers. We have followed the Django documentation and added {% csrf_token %} in the <head> tag of our base.html file which all other html files reference. Because this is a Shopify App, this app is embedded into a iFrame in Shopify but I am not sure this is the culprit as its the same in our development environment. There does seem to be cookies in the browser from our domain, just not the csrf token: We can't find a solution to why this is happening. We have had to mark our functions dispatch with @csrf_exempt which we don't want to have to do moving forward. For example: @csrf_exempt def dispatch(self, *args, **kwargs): return super().dispatch(*args, **kwargs) -
In production, Django doesn't change language. I use Docker. But flags and admin panel language changes
Project works good in development but doesn't in production. My Dockerfile is like that FROM python:3.11.4 ENV PYTHONUNBUFFERED 1 ENV DJANGO_SETTINGS_MODULE=mysite.settings WORKDIR /app COPY . /app RUN pip install -r requirements.txt RUN apt-get update && \ apt-get install -y gettext RUN apt-get install -y locales locales-all ENV LC_ALL en_US.UTF-8 ENV LANG en_US.UTF-8 ENV LANGUAGE en_US.UTF-8 RUN sed -i 's/# en_US.UTF-8 UTF-8/en_US.UTF-8 UTF-8/g' /etc/locale.gen RUN locale-gen RUN LANG=en_US.UTF-8 python manage.py collectstatic --noinput EXPOSE 8080 CMD ["gunicorn", "--config", "gunicorn_config.py", "mysite.wsgi:application"] My settings.py LANGUAGES = [ ('az', gettext_noop('Azerbaijani')), ('en', gettext_noop('English')), ('ru', gettext_noop('Russian')), ] LANGUAGE_CODE = 'az' TIME_ZONE = 'Asia/Baku' USE_I18N = True When i try to makemessages, this occures UnicodeDecodeError: skipped file requirements.txt in . (reason: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte) processing locale en_US.UTF-8 processing locale en -
Django - CSRF verification failed in Cloud Run
I am following this tutorial from Google codelabs. When trying to login to the admin panel, I am getting a CSRF verification failed. The tutorial is about deploying a fresh empty django project to Cloud Run. There's already a provided settings.py and I tried replacing it with this block to no avail: # SECURITY WARNING: It's recommended that you use this when # running in production. The URL will be known once you first deploy # to Cloud Run. This code takes the URL and converts it to both these settings formats. CLOUDRUN_SERVICE_URL = env("CLOUDRUN_SERVICE_URL", default=None) if CLOUDRUN_SERVICE_URL: ALLOWED_HOSTS = [urlparse(CLOUDRUN_SERVICE_URL).netloc] CSRF_TRUSTED_ORIGINS = ['https://django-cloudrun-yd43yjf7ya-uc.a.run.app'] SECURE_SSL_REDIRECT = True SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https") else: ALLOWED_HOSTS = ["*"] I've also tried hardcoding the CLOUDRUN_SERVICE_URL to the url provided on deployment, https://django-cloudrun-yd43yjf7ya-uc.a.run.app but it didn't work. With and without the slash at the end. Also did a sanity check by writing a simple hello world view to check if my changes are really getting through. -
django is not showing image in the browser and no error is shown in the inspect element
enter image description here [2]2 the complete images of the my first practice project is given here no erroe is shown in the browser. what to do? -
why django not able to pic or get uploaded images from database?
this is my index.html code {% load static %} <!DOCTYPE html> <html lang="en"> <head> <title>{% block title %}Bank{% endblock %}</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <link href="{% static 'money/styles.css' %}" rel="stylesheet"> </head> <body id="bg" style="background-image: url('{% static "money/bg.jpg"%}')"; style="background-image: url('{% static "money/bg.jpg"%}')";> <div class="indexdiv"> <h1 class="indextitle">Gautam Bank</h1> <div class="indexsign"> {% if user.is_authenticated %} Signed in as <strong>{{ user.username }}</strong>. {% else %} Not signed in. {% endif %} </div> <ul class="nav"> <li class="nav-item"> <a class="nav-link" href="{% url 'balance' %}">Balance</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'send' %}">Send Money</a> </li> <li class="nav-item"> <a class="nav-link history-link" href="{% url 'history' %}">Transaction History</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'loan' %}">Apply for Loan</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'login' %}">Logout</a> </li> </ul> <hr> </div> <div class="indeximg"> {% if user_profile and user_profile.image %} <img height="138" width="152" src="{{ user_profile.image.url }}" alt="User Profile Image"> {% else %} <img height="138" width="152" src="{% static 'money/pic.jpg' %}" alt="Default Image"> {% endif %} </div> {% block body %} {% endblock %} </body> </html> ****this is my views.py code **** from django.shortcuts import render from django.contrib.auth import authenticate, login, logout from .models import User,Transaction,BankAccount, UserProfile from django.urls import reverse from django.db import IntegrityError from django.core.exceptions import ValidationError from … -
python manage.py collectstatic on Aws Elasticbeanstalk ends with error: TypeError: expected string or bytes-like object, got 'NoneType'
I try to setup Django website on AWS EB. I have running environment and S3 Bucket. I created superuser for my project and migrated it to postgresql database. The problem is I cannot run collectstatic. This is error message I get: Traceback (most recent call last): File "/var/app/current/manage.py", line 22, in <module> main() File "/var/app/current/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/var/app/venv/staging-LQM1lest/lib64/python3.11/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/var/app/venv/staging-LQM1lest/lib64/python3.11/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/var/app/venv/staging-LQM1lest/lib64/python3.11/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/var/app/venv/staging-LQM1lest/lib64/python3.11/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/var/app/venv/staging-LQM1lest/lib64/python3.11/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 187, in handle collected = self.collect() ^^^^^^^^^^^^^^ File "/var/app/venv/staging-LQM1lest/lib64/python3.11/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 114, in collect handler(path, prefixed_path, storage) File "/var/app/venv/staging-LQM1lest/lib64/python3.11/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 338, in copy_file if not self.delete_file(path, prefixed_path, source_storage): ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/var/app/venv/staging-LQM1lest/lib64/python3.11/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 248, in delete_file if self.storage.exists(prefixed_path): ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/var/app/venv/staging-LQM1lest/lib64/python3.11/site-packages/storages/backends/s3.py", line 514, in exists self.connection.meta.client.head_object(Bucket=self.bucket_name, Key=name) File "/var/app/venv/staging-LQM1lest/lib64/python3.11/site-packages/botocore/client.py", line 553, in _api_call return self._make_api_call(operation_name, kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/var/app/venv/staging-LQM1lest/lib64/python3.11/site-packages/botocore/client.py", line 946, in _make_api_call api_params = self._emit_api_params( ^^^^^^^^^^^^^^^^^^^^^^ File "/var/app/venv/staging-LQM1lest/lib64/python3.11/site-packages/botocore/client.py", line 1072, in _emit_api_params self.meta.events.emit( File "/var/app/venv/staging-LQM1lest/lib64/python3.11/site-packages/botocore/hooks.py", line 412, in emit return self._emitter.emit(aliased_event_name, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/var/app/venv/staging-LQM1lest/lib64/python3.11/site-packages/botocore/hooks.py", line 256, in emit return self._emit(event_name, kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/var/app/venv/staging-LQM1lest/lib64/python3.11/site-packages/botocore/hooks.py", line 239, in _emit response = handler(**kwargs) ^^^^^^^^^^^^^^^^^ File "/var/app/venv/staging-LQM1lest/lib64/python3.11/site-packages/botocore/handlers.py", … -
why the django custom middleware not able to catch the exception?
I have written a custom django middleware to do retries and catch exception if there is any connection related issues between two servers. Below is the code snippet. from requests.adapters import Retry, RetryError, HTTPAdapter, MaxRetryError, ConnectTimeoutError, ProtocolError, ResponseError from requests.sessions import Session from django.http import HttpResponseServerError class RetryCal: def __init__(self, get_response): self.get_response = get_response @staticmethod def process_request(request): try: session = Session() retries = Retry(total=5, backoff_factor=2, status_forcelist=[500, 502, 503, 504]) session.mount('https://', HTTPAdapter(max_retries=retries)) request.retry_session = session except Exception as e: raise e def __call__(self, request): RetryCal.process_request(request) try: response = self.get_response(request) return response except (ProtocolError, OSError) as err: raise ConnectionError(err, request) except MaxRetryError as e: if isinstance(e.reson, ConnectTimeoutError): return HttpResponseServerError("Connection timeout error...") if isinstance(e.reson, ResponseError): raise RetryError(e, request=request) raise ConnectionError(e, request) Below is the placement of the custom middleware 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', # custom retry middleware. 'integ.api_retry_custom_middleware.RetryCal', belo this custom middleware I do have other default one's as well. The problem is I am not sure if this is working. I have a access token, In that I added some garbage characters and tried to hit my endpoints. I did see an exception as seen below Internal Server Error: /api/acct/ [24/Jan/2024 14:23:39] "GET /api/acct/ HTTP/1.1" 500 5348 But I can see this error even … -
How to use Django's GeneratedField to keep count of related objects?
Let's say I have the following models: class Shop(models.Model): ... @property def products_count(self): return Product.objects.filter(shop=self).count() class Product(models.Model): shop = models.ForeignKey(Shop, on_delete=models.CASCADE) ... The products_count property is being used to get the number of products in a shop. With the release of Django 5 and generated fields, is there a way to use this to store the count instead? Or am I misunderstanding the use of generated fields? -
Yeild usnig in async function in python Django
In my Django channels (websocket) i want to return data of for loop every time it gets a values using yield. if text_data: received_message = json.loads(text_data) OPEN BOX if received_message.get('open_box', False): rounds = await self.get_boxes_from_database(received_message) for r in rounds: response_data = await self.open_box_operation(received_message, r) data = self.send_group_notification({'type': 'OPEN-BOX', 'data': response_data}) yield data but i am getting error TypeError: object async_generator can't be used in 'await' expression async def receive(self, text_data): -
Celery crash with redis.exceptions.ResponseError: UNBLOCKED
I am using Celery with Django and Redis for everyday tasks. It works actually, but sometimes celery crashes with redis.exceptions.ResponseError, which i can't allow. I saw solution with configuring redis authentication, but it didn't work for me (or i did something wrong). celery auth log [2024-01-24 08:49:17,548: INFO/MainProcess] Connected to redis://default:**@redis:6379/0 error [2024-01-24 08:51:10,365: CRITICAL/MainProcess] Unrecoverable error: ResponseError('UNBLOCKED force unblock from blocking operation, instance state changed (master -> replica?)') Traceback (most recent call last): File "/usr/local/lib/python3.12/site-packages/celery/worker/worker.py", line 202, in start self.blueprint.start(self) File "/usr/local/lib/python3.12/site-packages/celery/bootsteps.py", line 116, in start step.start(parent) File "/usr/local/lib/python3.12/site-packages/celery/bootsteps.py", line 365, in start return self.obj.start() ^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/celery/worker/consumer/consumer.py", line 340, in start blueprint.start(self) File "/usr/local/lib/python3.12/site-packages/celery/bootsteps.py", line 116, in start step.start(parent) File "/usr/local/lib/python3.12/site-packages/celery/worker/consumer/consumer.py", line 742, in start c.loop(*c.loop_args()) File "/usr/local/lib/python3.12/site-packages/celery/worker/loops.py", line 97, in asynloop next(loop) File "/usr/local/lib/python3.12/site-packages/kombu/asynchronous/hub.py", line 373, in create_loop cb(*cbargs) File "/usr/local/lib/python3.12/site-packages/kombu/transport/redis.py", line 1344, in on_readable self.cycle.on_readable(fileno) File "/usr/local/lib/python3.12/site-packages/kombu/transport/redis.py", line 569, in on_readable chan.handlers[type]() File "/usr/local/lib/python3.12/site-packages/kombu/transport/redis.py", line 962, in _brpop_read dest__item = self.client.parse_response(self.client.connection, ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/redis/client.py", line 553, in parse_response response = connection.read_response() ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/redis/connection.py", line 524, in read_response raise response redis.exceptions.ResponseError: UNBLOCKED force unblock from blocking operation, instance state changed (master -> replica?) docker-compose services: redis: image: redis:latest container_name: redis restart: on-failure volumes: - ./redis.conf:/usr/local/etc/redis/redis.conf ports: … -
Idea about full stack e-commerce applications
I want to develop e- commerce web application using 3 database 1) mongodb for store user's information 2) my SQL all products, category,price, product title I want store in my SQL database 3) cloudinary for image store I want application like Amazon My question is which technology I can use 1)react+ django 2) react + express 3)next.js Please give detail idea about this project For my e-commerce applications can I use inbuilt admin or can I develop my own admin.. -
Dango: list index out of range after, after 10 loops even though there is more left in the list
Suppose to take entry from a form entry for a list of cards. Then split each entry into a list after a new line. No matter what is in the form text area box, it reaches out of range after 9 entries. Have tried multiple different card examples, no matter what is there will always crash after 9 entries. def new_deck(request): form = mtgForm() current_user = request.user add_deck = Decks(deck_name=request.POST['Deck_Name'], user_id=current_user.id) add_deck.save() decks_id = add_deck.deck_id if request.method == "POST": current_user = request.user cards_from = request.POST['cards'] cards_from_form = cards_from.split("\r\n") cards_from_form[:] = [x for x in cards_from_form if x] for i, dataa in enumerate(cards_from_form): amount_of_cards = ''.join(x for x in dataa if x.isdigit()) pattern = r'[0-9]' ccards_name = re.sub(pattern, '', dataa).lstrip() ccards = Card.where(name=f'"{ccards_name}"').all() #ccard_id = ccards[0:1].number ccard_name = ccards[0].name ccard_type = ccards[0].type ccard_cost = ccards[0].mana_cost ccard_toughness = ccards[0].toughness ccard_power = ccards[0].power ccard_rarity = ccards[0].rarity ccard_set = ccards[0].set ccard_color_idenity = ccards[0].color_identity add_cards = cards(card_name=ccard_name, card_type=ccard_type, card_cost=ccard_cost, card_toughness=ccard_toughness,card_power=ccard_power,card_rarity=ccard_rarity,card_set=ccard_set,card_color_idenity=ccard_color_idenity,deck_id=decks_id) add_cards.save() return HttpResponse("Cards added to deck") else: return render(request, "form.html", {"form": form}) -
Limit editing access to a model in the Django admin panel
this is my model class Profile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) first_name = models.CharField(_('نام'), max_length=255) last_name = models.CharField(_('نام خانوادگی'),max_length=255) image = models.ImageField(_('تصویر'),null=True, blank=True) description = models.TextField(_('توضیحات'),) created_date = jmodels.jDateTimeField(_('تاریخ ایجاد'), auto_now_add=True) updated_date = jmodels.jDateTimeField(_('تاریخ آخرین به روز رسانی'),auto_now=True) USERNAME_FIELD = 'user' REQUIRED_FIELDS = [] def __str__(self) -> str: return self.user.email class Meta: ordering = ['-updated_date'] verbose_name = 'پروفایل' verbose_name_plural = 'پروفایل ها' @receiver(post_save, sender=User) def save_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) In the admin panel, I want only the profile owner and super user to have access to edit that profile I don't know where and what changes I should make -
How to allow custom/catch-all domains in nginx?
I want each user to be able to point their own domain names at my Django server. My current nginx config file in /etc/nginx/sites-available/ looks like this: upstream app_server { server unix:/home/zylvie/run/gunicorn.sock fail_timeout=0; } server { if ($host = www.zylvie.com) { return 301 https://$host$request_uri; } # managed by Certbot server_name www.zylvie.com; return 301 $scheme://zylvie.com$request_uri; listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/zylvie.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/zylvie.com/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } server { server_name zylvie.com; keepalive_timeout 60; client_max_body_size 4G; access_log /home/zylvie/logs/nginx-access.log; error_log /home/zylvie/logs/nginx-error.log; location /robots.txt { alias /home/zylvie/staticfiles/robots.txt; } location /favicon.ico { alias /home/zylvie/staticfiles/favicon.ico; } location /static/ { alias /home/zylvie/staticfiles/; } location /media/ { allow all; auth_basic off; alias /home/zylvie/zylvie/media/; } # checks for static file, if not found proxy to app location / { try_files $uri @proxy_to_app; } location @proxy_to_app { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; proxy_connect_timeout 600; proxy_send_timeout 600; proxy_read_timeout 600; send_timeout 600; fastcgi_read_timeout 60; proxy_pass http://app_server; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/zylvie.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/zylvie.com/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } … -
How to increase custom count value without forloop.counter in django template?
Here is my code to increment count value. i have set variable count and assign default is 1. <div class="main-content"> {% with count=1 %} {% for element in responses %} <!-- TYPE: section --> {% if element.type == "section"%} <div class="wrapper"> <div class="input-wrapper"> <div class="question"> <h3>{{element.label}}</h3> </div> <div class="description"> {{element.instruction}} </div> </div> <hr class="grey-hr" /> </div> <!-- type: time --> {% elif element.type == "time"%} <div class="wrapper"> <div class="input-wrapper"> <div class="question"> <span class="number">{{count}}. </span> <span>{{element.label}}</span> {% if element.isRequired %} <span style="color: #f44336">*</span> {% endif %} </div> <div class="answer"> <p>{{element.answer}}</p> </div> </div> <hr class="grey-hr" /> </div> {% endif %} {% with count=count|add:1 %} {% endwith %} {% endfor %} {% endwith %} </div> I have to increment count value without forloop.counter.It should not be increment please suggest what i'm missing.