Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Filter a combined queryset in Django Rest Framework
I created a viewset that combines different models that inherit from the same parent model (Transactions). It was working well and I could reach the endpoint. Now I am trying to add filters using django-filters, but I am getting an error: model = queryset.model AttributeError: 'list' object has no attribute 'model' The fields that I am using to filter and search belong to the parent model. Here is my viewset: class TransactionViewSet(viewsets.ReadOnlyModelViewSet): serializer_class = TransactionSerializer filter_backends = [DjangoFilterBackend, filters.SearchFilter] filterset_fields = { "company": ["exact"], } search_fields = ["id", "description"] def get_queryset(self): payment_collections = PaymentCollection.objects.all() up_front_sales = UpFrontSale.objects.all() combined_queryset = list( chain( payment_collections, up_front_sales, ) ) return combined_queryset I see that the error is that my method returns a list instead of a queryset, but I tried to use the union method instead and got raise NotSupportedError( django.db.utils.NotSupportedError: Calling QuerySet.filter() after union() is not supported. Is there a way to use the default filterset_fields and search_fields with a combined queryset? -
NameError: name '_mysql' is not defined Mac Django
I was trying to run python manage.py run server while working with Django after changing my settings.py from this: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } to this: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'storefront', } } But I was getting this error: File "/Users/aditi/.local/share/virtualenvs/storefront-4vgosAeV/lib/python3.12/site-packages/django/db/backends/mysql/base.py", line 16, in <module> import MySQLdb as Database File "/Users/aditi/.local/share/virtualenvs/storefront-4vgosAeV/lib/python3.12/site-packages/MySQLdb/__init__.py", line 24, in <module> version_info, _mysql.version_info, _mysql.__file__ ^^^^^^ NameError: name '_mysql' is not defined This is what my __init__.py looks like: try: from MySQLdb.release import version_info from . import _mysql assert version_info == _mysql.version_info except Exception: raise ImportError( "this is MySQLdb version {}, but _mysql is version {!r}\n_mysql: {!r}".format( version_info, _mysql.version_info, _mysql.__file__ ) ) I downloaded MySQL from this link, the x86 DMG option: https://dev.mysql.com/downloads/mysql/ I have Sonoma 14.3. I am running Python 3.12.7. Please let me know how I can fix this error. I tried adding this to my .zshrc file: export PATH="/usr/local/mysql/bin:$PATH" But it did not work. -
Configuring Azure AD authentication for django Local development
I am using Azure AD for authenticating access to my django application and it works fine in the DEV environement. The application is in a container reached in this url: "https://application-dev.organization.org" Azure was configured and the redirect url was provided : "https://application-dev.organization.org/auth/complete/azuread-oauth2/ I have the same application in my local environment http://application.local:8080 I would like to add Azure AD authentication to it to be able to development locall before releasing to DEV and then TEST and PROD. How to configure a local application in AZURE AD. how will the redirect work ? is there some DNS work to be done. or does Azure traceback the TCP/IP link? I tried to configure Azure AD with my local enviroment by local admin does not have a clue -
Tracing the cause of drf_spectacular.plumbing.UnableToProceedError
I have inherited a Django app in which DRF Spectacular was never fully installed. I want to get it working so I can easily see how the API has been set up. There are quite a few models and serializers, and I suspect a custom field may be the cause of this error I am getting: drf_spectacular.plumbing.UnableToProceedError There is a stack trace pointing to drf_spectacular/plumbing.py but all that tells me is that a field type hint was not able to be generated, not which field or modal or whatever caused it. In the Spectacular settings, I have debugging set up: SPECTACULAR_SETTINGS = { 'DEBUG': True, ... How else can I tell what actually went wrong? I am trying to generate the schema inside a docker container with this command: docker compose run --rm site python manage.py spectacular --color --file schema.yml -
How to list updated records in Django forms?
I have 3 child tables that all relate to a parent table via foreign key relationships. I created a form to add records to this parent table that also has these foreign key relationships. The form queries these children and show the querySet object with N records in each object. Thus, I took this approach to populating the fields as multi-choice: # Form class CreateMatch(forms.ModelForm): p_choices = [(player.id, player.gamer_tag) for player in Players.objects.all()] e_choices = [(event.id, event.name) for event in Events.objects.all()] g_choices = [(game.id, game.name) for game in Games.objects.all()] player_one = forms.ChoiceField(choices=p_choices) player_two = forms.ChoiceField(choices=p_choices) game = forms.ChoiceField(choices=g_choices) event = forms.ChoiceField(choices=e_choices) class Meta: model = Matches fields = ['player_one', 'player_two', 'player_one_score', 'player_two_score', 'game', 'event', 'round', 'losers'] This will ensure fields like player_one populates all human readable names in the form field as a dropdown. # View from .forms import CreateMatch def add_match(request): context = { "title": "Add New Event" } if request.method == 'POST': form = CreateMatch(request.POST) if form.is_valid(): post = form.save(commit=False) post.save() return redirect('add match') # Replace 'forum_home' with your actual URL name else: form = CreateMatch() return render(request, 'add_match.html', {'form': form, 'context': context}) # Parent model class Matches(models.Model): player_one = models.ForeignKey(Players, on_delete=models.CASCADE, related_name='%(class)s_player_one') player_two = models.ForeignKey(Players, on_delete=models.CASCADE, related_name='%(class)s_player_two') … -
How to properly serve static files through nginx in my django project
I've tried all possible configurations, but I don't know why nginx doesn't provide the static files for my application, that is, I always have a page without style. This is my Dockerfile: enter image description here This is my entrypoint.sh enter image description here This is my static configuration on settings.py enter image description here This is my docker-compose.yml enter image description here I have a folder in the root of my project called nginx. Inside it I have the files: Dockerfile enter image description here default.conf enter image description here I would like to understand what I'm doing wrong, I've tried other configuration structures, but nginx never serves the static files. -
When trying to authenticate user, Django presents a dropdown form of logins to update
I'm trying to code a password reset feature for a site, where the user enters their old password and new password. If the old password matches, the user's password is updated to the new password. However, I am having an error where a dropdown form asks which user I would like to update.Image of dropdown form I have no clue where the error is from. Here's a picture: The dropdown list always has the same users, even though I've created a lot more. I've tried a bunch of different ways to code a password reset view/form. I was expecting the issue to be within user authentication, but it seems to be deeper than that. -
urlpattern with arbitrary number of optional filters
In order to reflect filters in the URL, I need urlpatterns to include an arbitrary number of optional parameters, e.g.: /myview/filter1:option1/filter1:option2/filter2:option1/filter3:option5 Each filter can (potentially, depending on the type of filter) have multiple selected options, and multiple filters can be applied at one time. See MobyGames as an example of exactly what I mean. I imagine I need regex to achieve this, but I don't really know where to start. I read through the relevant docs, but didn't find anything that directly addresses this kind of pattern. -
Unable to Redirect to Next Page After Successful Login in Django
Despite entering the correct credentials, I am consistently redirected back to the login page instead of being granted access to the Products page. This issue persists even though the credentials are valid, which suggests that there might be a problem with the login and authentication process. As a result, I am unable to proceed beyond the login page. Views.py from django.shortcuts import render, redirect from django.http import HttpResponseRedirect, Http404 from .forms import UserRegisterForm, UserLoginForm,Reviews_Form from django.contrib import messages from .models import UserRegister, Review from django.contrib.auth import authenticate, login ,logout from django.contrib.auth.decorators import login_required from urllib.parse import urlparse from django.urls import is_valid_path # Create your views here. products = [ { "slug": "Mustang-GT", "About": """The Ford Mustang GT in its stunning white color is nothing short of a modern-day classic. From the moment you lay eyes on it, the Mustang's sleek and muscular design commands attention and admiration. The pristine white finish only adds to its allure, giving it a timeless, elegant look that stands out on the road. Performance: Under the hood, the Mustang GT roars to life with its 5.0-liter V8 engine, delivering a thrilling 450 horsepower. The acceleration is exhilarating, and the handling is precise, making every drive … -
Is it possible to render a column for each of a many-to-many relationship with django-tables2?
It's simple enough to get all the many-to-many relationships of a particular row - but they're rendered in the same column. Is it possible to have a column created for each one? For example, with a many-to-many relationship between Child and Year, and data for each child/year pair, I'd want a column for each Year in the table: Child 1998 1999 2000 ---------------------------- Eldest 155 162 170 Youngest 53 61 72 Middlest 80 91 103 (many to many in django-tables2 is the closest I've seen to a question about this, and I think the accepted answer is wrong; it doesn't render a column for each relationship at all.) -
NoReverseMatch: Reverse for 'chat_chatroom_changelist' not found. 'chat_chatroom_changelist' is not a valid view function or pattern name
Im triyng to register model in django admin, but i get error backend-1 | Couldnt reverse admin:chat_chatroom_changelist. Im using jazzmin for customize admin panel, and i setting up it for model JAZZMIN_SETTINGS { 'name':_('Chat'), 'model': 'chat.ChatRoom', 'url': 'admin:chat_chatroom_changelist', 'permissions': ['auth.view_user'], }, Model has been register in admin.py @admin.register(ChatRoom) class ChatRoomAdmin(admin.ModelAdmin): fieldsets = ( (None, {'fields': ('first_user', 'second_user')}), (_('Important dates'), {'fields': ('created_at', 'updated_at')}), ) list_display = ('id', 'first_user', 'second_user', 'created_at', 'updated_at') readonly_fields = ('created_at', 'updated_at') list_display_links = ('id', 'first_user', 'second_user') show_full_result_count = False def get_queryset(self, request): return super().get_queryset(request).select_related('first_user', 'second_user').order_by('-created_at') def get_history_queryset(self, request, history_manager, pk_name: str, object_id): qs = super().get_history_queryset(request, history_manager, pk_name, object_id) return qs.prefetch_related('history_user') model class ChatRoom(TimestampMixin, models.Model): first_user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='first_user') second_user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='second_user') def __str__(self): return ' / '.join([str(self.first_user), str(self.second_user)]) class Meta: db_table = 'chatrooms' app_label = 'chat' Project structure _|apps __|chat ___|admin ____|admin.py ___|models ____|chat.py ___|url.py ___|... __|... __|asgi.py __|wsgi.py _|settings __|main.py __|base.py __|jazzmin.py _|... -
Django Project on Azure, 502 error after deployment
I'm deploying a Django app on Azure Web App using Gunicorn and keep getting a 502 Bad Gateway error. Despite binding to the correct port, setting up environment variables for Key Vault, and enabling SCM_DO_BUILD_DURING_DEPLOYMENT for Oryx builds, the site never fully starts. I need to figure out why Gunicorn won't serve the app properly, even though the deployment logs seem fine. I set SCM_DO_BUILD_DURING_DEPLOYMENT=true, placed my requirements.txt in the project root so Oryx could install dependencies, and updated my startup command to gunicorn --bind=0.0.0.0:$PORT. I also configured environment variables for Key Vault, and tested collecting static files locally vs. on Azure. I expected the Azure Web App to run Gunicorn without errors. Instead, I keep getting a 502 Bad Gateway, and my logs show no direct failure message—just that the service never properly responds. -
When and where i use create_user from CreateUserManager()?
For several days now, I've been wondering why I should create my own user manager in Django, since in the end, when inheriting a built-in form, I don't refer to my created manager anyway. class CustomUserManager(BaseUserManager): def create_user(self, email, birth_date, password=None, **extra_fields): if not email: raise ValueError("You didn't entered a valid email address!") email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password, **extra_fields): extra_fields.setdefault('is_stuff', True) extra_fields.setdefault('is_superuser', True) return self.create_user(email, password, **extra_fields) I have something like this and in the end when it creates a user it doesn't go through that create_user anyway. So my two questions: Why create something for a custom user if I don't end up using it anyway because the form inherits from UserCreationForm. So, for example, form.save() does not use my manager. At what point should this create_user be executed? -
asynchronously database routing in djago and celery
I am implementing subdomain-based database routing, and it is working fine. However, when a task is executed asynchronously, the database that has been dynamically routed gets overwritten by the default one. How to handle that in Django? # middleware.py from django.db import connections from django.conf import settings from django.http import HttpResponse class SubdomainDatabaseMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): # Get subdomain from the request subdomain = request.META.get('HTTP_HOST', '').split('.')[0] subdomain = 'tenant' # Set the database connection based on subdomain if subdomain: request.subdomain = subdomain self.set_database(subdomain) else: request.subdomain = None response = self.get_response(request) return response def set_database(self, subdomain): # Dynamically set database for the subdomain database_alias = f'{subdomain}' if database_alias in settings.DATABASES: connections['default'] = connections[database_alias] else: # Default behavior if no database configured for subdomain pass -
Django "No installed app with label 'logs'" Error Even After Correcting Project Structure
I'm encountering a persistent "No installed app with label 'logs'" error in my Django project, even after seemingly correcting the project structure and INSTALLED_APPS. I've tried all the common solutions, but the issue remains. Python Version: 3.13.2 Django Version: 5.1.6 os: Windows 11 Project Structure router_log_project/ manage.py router_log_project/ (Inner project directory) __init__.py settings.py urls.py wsgi.py logs/ __init__.py models.py views.py migrations/ __init__.py env/ db.sqlite3 settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'logs', ] Steps already taken Double-checked INSTALLED_APPS: I've meticulously verified the spelling of 'logs' in INSTALLED_APPS. Verified __init__.py files: I've confirmed that __init__.py files exist in both the inner router_log_project directory and the logs app directory. Restarted the development server: I've restarted the server multiple times after making changes. Deactivated/reactivated the virtual environment: I've tried creating a fresh virtual environment. -
Where the source code files are stored by azure in case of a web app on linux for a python website?
I've created a web app on azure for a python web app. I've successfully deployed it using zip and an azure cli command. It worked and my website works now. But what's really confusing to me is that I don't see my website files via filezilla. I mean it should contain all those scripts and the database file. I'm using sqlite db there. So if I just want to upload some image manually or download a database for a backup or local work with up to date PROD database, how do I do that? The only thing that I've found there is a output.tar.gz file, which contains output.tar file, which contains all of my website files and the database file as well. But would azure server hold all the files that a website is currently using in an archive? It would slow down an app, so I don't believe that those files are up to date with actual working PROD website instance. So how can I download the database file from PROD to my local? -
django reconnect to DB when connection is lost
I have django project, Mysql DB is on a separate host, connected by TCP. I have this script: #!/usr/bin/env python from asyncio import sleep, run from django import setup as django_setup django_setup() from django.db import connections from django.contrib.auth.models import User from django.db import OperationalError, close_old_connections async def test(): while True: try: objs=User.objects.all() print(await objs.acount()) except KeyboardInterrupt: break except OperationalError as e: # Need to reconnect print(f'main(): OperationalError: {e}') #raise # (1053, 'Server shutdown in progress') # (2013, 'Lost connection to MySQL server during query') # (2006, 'Server has gone away') code=e.args[0] if code in {1053, 2006, 2013, 2026}: # Only when it's restarting, and once #await sync_to_async(conn.connect)() close_old_connections() print('After reconnect') #reconnect() else: #breakpoint() pass except Exception as e: print(f'in _round() {type(e)}') else: pass #breakpoint() print('Sleeping') await sleep(5) try: run(test()) except KeyboardInterrupt: raise except: print('In run(main())') breakpoint() pass Then I use tcpkill to interrupt the connection: tcpkill 'dst port 3306' How do I instruct django to reconnect? I doesn't do it automatically, close_old_connection doesn't work, the output is then like this: 3 Sleeping 3 Sleeping main(): OperationalError: (2013, 'Lost connection to MySQL server during query') After reconnect Sleeping main(): OperationalError: (2013, 'Lost connection to MySQL server during query') After reconnect Sleeping … -
When deployed to the server (in production), the Gemini API server's streaming responses are not received
It works fine locally. In the production environment, non-streaming responses work well. When I send a Gemini API request directly from the AWS server using curl, the streaming works perfectly. However, when I run the backend server with Gunicorn, the Gemini API streaming does not work. I tried using both gevent and eventlet for the worker class, but neither worked. It doesn't seem to be an issue with the nginx configuration, since streaming responses to the client are sent correctly. The problem only occurs when the server calls the outer API. Actually, everything worked fine when I first set up the server. But ever since I set up the CI/CD pipeline, (I just tried to use github actions and install requirements remote) external API streaming doesn't work. Since it's a Django codebase, even deleting the virtual environment and reinstalling, or installing using the requirements.txt from before the CI/CD build (when it was working fine), doesn't resolve the issue. What should I do? What I got from gunicorn logs [2025-02-14 14:29:50 +0000] [5235] [CRITICAL] WORKER TIMEOUT (pid:5283) Feb 14 14:29:50 ip-172-31-13-205 gunicorn[5283]: response: Feb 14 14:29:50 ip-172-31-13-205 gunicorn[5283]: GenerateContentResponse( Feb 14 14:29:50 ip-172-31-13-205 gunicorn[5283]: done=False, Feb 14 14:29:50 ip-172-31-13-205 gunicorn[5283]: iterator=<_StreamingResponseIterator>, … -
Django-admin makemessages does not detect ngettext strings from .html files (but it detects gettext strings)
Django-admin makemessages does not detect ngettext strings from .html files (write in jinja2), but it is able to detect them in .py files. However, the same command normally detects gettext strings everywhere (including in .html files). I tried django-admin makemessages -l en --ignore="*/site-packages/*" --ignore="*/django/*" and my code in .html is {{ ngettext( '%(num)d lesson', '%(num)d lessons', 3) | format(num=3) }} -
BrowsableAPIRenderer doens't have a file upload field
I'm trying to have an image upload field, so I could upload multiple images per post. But it seems like it doesn't have a file upload field, let alone that would allow and save multiple files. views.py class PostsViewSet(ModelViewSet): queryset = Post.objects.all() serializer_class = PostSerializer permission_classes = [IsAuthenticated, IsOwnerOrReadOnly|IsAdminUser] filter_backends = (filters.DjangoFilterBackend,) filterset_class = PostFilter parser_classes = [JSONParser, MultiPartParser, FileUploadParser] renderer_classes = [JSONRenderer, BrowsableAPIRenderer] serializers.py class PostImageSerializer(serializers.ModelSerializer): class Meta: model = PostImage fields = ('image',) class PostSerializer(serializers.ModelSerializer): author = UserSerializer(read_only=True) comments = CommentSerializer(many=True, read_only=True, source='comment_set') likes_count = serializers.SerializerMethodField() images = PostImageSerializer(source='postimage_set', many=True, read_only=True) class Meta: model = Post fields = "__all__" def create(self, validated_data): validated_data["author"] = self.context["request"].user images_data = self.context.get('view').request.FILES print(validated_data) post = Post.objects.create(text=validated_data.get('text'), author=validated_data.get('author')) for image_data in images_data.values(): PostImage.objects.create(post=post, image=image_data) return post models.py class Post(models.Model): id = models.AutoField(primary_key=True) text = models.TextField(max_length=165) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return f'{self.author} posts "{self.text}"' class PostImage(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE) image = models.ImageField(upload_to='images/', blank=True) and it looks like this Where's error? -
How do I save a Historical field on a non-historical model in Django Simple History?
I have something like a ContractTemplate shared for all clients which is 'versioned' through django-simple-history. I have a ClientContract that I want to attach a HistoricalContractTemplate as a field, so I can tell what the ContractTemplate looked at the time the ClientContract was created. class ContractTemplate(models.Model): text = models.TextField() # Create table 'HistoricalContractTemplate' which stores all changes history = HistoricalRecords() class ClientContract(models.Model): client_text = models.TextField() contract_template_version = ???? # <------ And after I set up the model right, how do I use it? def update_client_contract(contract_template_that_will_get_stale): # ... update other client contract fields newest_history_record_of_this_contract_template = ??? # <--- client_contract.contract_template_version= newest_history_record_of_this_contract_template -
Django - multiple models in one view
I have scoured the StackOverflow pages and none of the solutions to this problem are working for me. I have two models in the same app and am trying to display data from both models in the same template using class based DetailView. This is my code, but the only thing that displays is the data from the Project model. models.py from django.db import models class Project(models.Model): project_name = models.CharField(max_length=100) project_location = models.CharField(max_length=100) def __str__(self): return self.project_name class Well(models.Model): project_name = models.ForeignKey(Project, on_delete=models.CASCADE) well_name = models.CharField(max_length=100) def __str__(self): return self.well_name views.py class ProjectDetailView(DetailView): model = Project template_name = 'project/project_detail.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['projects'] = Project.objects.all() context['wells'] = Well.objects.all() return context html {{ project.project_name}} {{ well.well_name}} What am I missing? The Django docs for TemplateView only show how to display data from one model, not two. -
How Can I Get Django Global Notifications Via Channels To Work?
I have spent the last month or so on and off trying to get the django channels notification to work. I can't get notifications to work but the chat works as expected. Here is my code... Consumers.py class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): self.is_group_chat = 'group_name' in self.scope['url_route']['kwargs'] if self.is_group_chat: group_name = self.scope['url_route']['kwargs'].get('group_name') self.group_name = group_name.replace('_', ' ') # Replace underscores with spaces try: self.group_chat = await database_sync_to_async(GroupChat.objects.get)(name=self.group_name) except GroupChat.DoesNotExist: await self.close() return self.chat_group = f'group_{self.group_name.replace(" ", "_")}' else: self.recipient_username = self.scope['url_route']['kwargs'].get('recipient_username') self.sender = self.scope['user'] self.conversation_group = self.get_conversation_group_name( self.sender.username, self.recipient_username ) # Convert recipient_username to a User object and assign it to self.recipient try: self.recipient = await database_sync_to_async(get_user_model().objects.get)(username=self.recipient_username) except get_user_model().DoesNotExist: await self.close() return # Join the group if self.is_group_chat: await self.channel_layer.group_add( self.chat_group, self.channel_name ) else: await self.channel_layer.group_add( self.conversation_group, self.channel_name ) await self.accept() def get_conversation_group_name(self, user1, user2): return f'chat_{sorted([user1, user2])[0]}_{sorted([user1, user2])[1]}' async def disconnect(self, close_code): if self.is_group_chat: await self.channel_layer.group_discard( self.chat_group, self.channel_name ) else: await self.channel_layer.group_discard( self.conversation_group, self.channel_name ) async def receive(self, text_data): text_data_json = json.loads(text_data) timestamp = timezone.now().isoformat() sender = self.scope['user'] sender_full_name = await self.get_user_full_name(sender) # Fetch full name message = text_data_json.get('message', '') attachment = text_data_json.get('attachment', None) message_type = text_data_json.get('type') # Ensure sender full name is calculated sender_full_name = await self.get_user_full_name(sender) if … -
exclude specific urls from nginx redirect
I'm trying to exclude two URLs from nginx redirect (http to https). Traffic from Nginx is sent to guincorn and the URLs are generated dynamically by the Django view. My current base nginx configuration for the site is below. All non http requests are sent to https using this. server { listen 80; listen [::]:80 default_server; server_name mydomain.org; return 301 https://$server_name$request_uri; } server { listen 443 ssl default_server; listen [::]:443 ssl default_server; ssl_certificate ....; ssl_certificate_key ....; root /app/ioc; server_name mydomain.org; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { alias /path/static/; } location / { proxy_pass http://unix:/run/gunicorn.sock; proxy_set_header Host $http_host; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header X-Forwarded-For $remote_addr; proxy_redirect off; } } Now, I'm trying to exclude both this/endpoint1.txt and this/endpoint2.txt from the redirects. endpoint1.txt and endpoint1.txt are dynamically generated by the django view so they are not actual text files on the server. Trying to do something like this results in 404 error location /this/endpoint1.txt { root /path/app; add_header Content-Type text/plain; } Also, when I do something like this: location /this/endpoint1.txt { proxy_pass http://127.0.0.1:80; } I get 504 Gateway Time-out error. I'm binding gunicorn like this "0.0.0.0:8000" -
Best way to implement date with optional day/month?
There are several ways to do this, each with their own advantages and disadvantages. Boolean fields for day/month: Advantages: cheap ordering, easy formatting, easy validation Disadvantages: have to provide a default month/day, ordering may not behave as expected depending on needs date = models.DateField() date_has_month = models.BooleanField() date_has_day = models.BooleanField() Separate IntegerFields Advantages: relatively cheap ordering, flexible ordering with not_null option etc Disadvantages: complicates date validation, must order on several fields, must compose date from several fields date_year = models.IntegerField() date_month = models.IntegerField() date_day = models.IntegerField() CharField Advantages: no need for extra fields, 1:1 with user input (depending on validation) Disadvantages: relatively expensive ordering, ordering is inflexible, validation may be complicated date = models.CharField() My question is: are there more (dis)advantages not listed? Are there other ways to achieve this that I haven't thought of?