Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Recebendo "Login timeout expired" MS SQL Server + Python Django
Tenho um banco de dados SQL Server instalado no windows e gostaria de acessa-lo através do código que estou desenvolvendo em minha máquina virtual que roda Ubuntu (python + django + django-pyodbc-azure + pyodbc) Tentei praticamente todos os procedimentos que encontrei em minhas pesquisas mas não obtive sucesso. O banco de dados está acessível através da rede local uma vez que consigo acessa-lo através de um app no celular. O que me leva a crer que pode ser um problema relacionado ao ambiente ubuntu ou alguma configuração do vmware. A conexão com a rede dessa máquina virtual está no modo bridge": Windows: 10.0.1.190 Ubuntu: 10.0.1.191 Essa é a configuração que estou colocando no settings.py DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'HOST': "10.0.1.190", 'USER': "usuario", 'PASSWORD': "senha", 'NAME': "nomedobanco", 'PORT': "1433", 'OPTIONS': { 'driver': 'ODBC Driver 17 for SQL Server', } } } Este é o erro que estou recebendo: django.db.utils.OperationalError: ('HYT00', '[HYT00] [Microsoft][ODBC Driver 17 for SQL Server]Login timeout expired (0) (SQLDriverConnect)') Ping do ubuntu pro windows: ''' rpinheiro@ubuntu:~$ ping 10.0.1.190 PING 10.0.1.190 (10.0.1.190) 56(84) bytes of data. From 10.0.1.191 icmp_seq=1 Destination Host Unreachable From 10.0.1.191 icmp_seq=2 Destination Host Unreachable ''' Alguma ideia? -
How do I use AJAX to both create and edit new posts using the same html template (with Python & Django)?
I'm trying to switch to saving a form with AJAX instead of just Python/Django (I'm an absolute newb, so please forgive my idiocy). Here's what I'm trying to achieve: urls.py: from django.urls import path from . import views urlpatterns = [ path('', views.blurb_new, name='blurb_new'), path('blurb/new/', views.blurb_new, name='blurb_new'), path('blurb/<int:pk>/edit/', views.blurb_edit, name='blurb_edit'), ] views.py (the relevant part): @login_required def blurb_new(request): if request.method == "POST": form = BlurbForm(request.POST) if form.is_valid(): blurb = form.save(commit=False) blurb.author = request.user blurb.save() return redirect('blurb_edit', pk=blurb.pk) else: form = BlurbForm() return render(request, 'mysite/blurb_edit.html', {'form': form}) @login_required def blurb_edit(request, pk): blurb = get_object_or_404(Blurb, pk=pk) if request.method == "POST": form = BlurbForm(request.POST, instance=blurb) if form.is_valid(): blurb = form.save(commit=False) blurb.author = request.user blurb.last_edited_date = timezone.now() blurb.save() return redirect('blurb_edit', pk=blurb.pk) else: form = BlurbForm(instance=blurb) return render(request, 'mysite/blurb_edit.html', {'form': form, 'blurb': blurb}) blurb_edit.html (the relevant parts): <form id="myform" method="POST" class="blurb-form">{% csrf_token %} <input id="blurb-name" name="title" {% if form.title.value != None %}value="{{ form.title.value }}"{% endif %} /> <textarea name="text" id="my-textarea"> {% if form.text.value != None %} {{ form.text.value }} {% else %} Type your blurb here. {% endif %} </textarea> <button type="submit">Save</button> </form> Before I used AJAX, views.py was totally doing its job (except for that pesky, unwanted page refreshing). Because I hate the way … -
How to create and start a form Select field, without it being in the model?
I have reviewed many of the questions related to this topic, in this forum and in Spanish, I have followed the steps, and it does not work for me, on something that seems so simple, at first. I have Django 2.2.6 with a form that needs the selected value of a Select field, which is not in the model, and acquires a list of values (tuples of two) created from the view. Upon entering the form, throw this error: "__init __ () received an unexpected keyword argument 'carpetas'", in the FotoArtForm class, in the super () line. This is my code: models.py class FotoArt(models.Model): nombre = models.CharField(max_length=50) foto = models.ImageField(upload_to='fotos/articulos/', null=True, blank=True) class Meta: ordering = ['nombre'] verbose_name = _('Foto Artículo') verbose_name_plural = _('Fotos Artículos') def __str__(self): return self.nombre def get_absolute_url(self): return reverse('detalle-fotoArt', args=[str(self.id)]) views.py class FotoArtActualizar(LoginRequiredMixin, UpdateView): model = FotoArt form_class = FotoArtForm Ruta = os.path.join(MEDIA_ROOT, 'fotos', 'articulos') def get_form_kwargs(self): kwargs = super(FotoArtActualizar, self).get_form_kwargs() kwargs['carpetas'] = self.get_folders_list(self.Ruta) return kwargs def get_folders_list(self, ruta): foldersList = [] for _, listaSubDir, _ in os.walk(ruta): for dName in listaSubDir: foldersList.append((dName, dName)) return foldersList forms.py class FotoArtForm(forms.ModelForm): guardar_en_carpeta = forms.ChoiceField(choices=(), required=True) def __init__(self, *args, **kwargs): super(FotoArtForm, self).__init__(*args, **kwargs) self.foldersList = kwargs.pop('carpetas', None) self.fields['guardar_en_carpeta'].choices = … -
Outerref and Subquery not retrieving datetime data
I have a use case where I am trying to calculate the total value of some transactions given amount and historical price, with the following models: class Transaction(models.Model): ... asset = models.ForeignKey('Asset', ...) amount = models.FloatField() date = models.DateTimeField() ... class Price(models.Model): ... asset = models.ForeignKey('Asset', ...) price = models.FloatField() date = models.DateTimeField() ... What I am trying to do, it get all the Transactions, through a query and annotate the historical price through a Subquery : from django.db.models.expressions import Subquery, OuterRef price_at_date = Price.objects.filter( date=OuterRef('date'), asset=OuterRef('asset')).values('price') transactions = Transaction.objects.filter(...).annotate(hist_price=Subquery(price_at_date)) This returns None for hist_price. I suspect it has something to do with the fact that the datetimes do not match, (different time but same date). I tried to replace any combination of date by date__date but this still does not work and returns None in hist_price. Any idea how I can get the historical price for the same date (but not time) though the Django ORM / query ? Thank you! -
Django OneToOneField self-referential in save method
I have the following (simplified version): class Model: reference = models.OneToOneField(to='self', on_delete=..., related_name='referenced_field') Now, on another instance of Model I do: a = Model.objects.create(...., reference=Model.objects.get(id=request.POST.get('reference_id')) Now, I've modified the save method so that when I edit object a I can update a common field that's reflected in reference. def save(.....): self.referenced_field.common_field = .... However, this raises a DoesNotExist saying the referenced_field reverse relationship is non-existent.... And yet I'm staring at the filled out field in the database. Bug or am I missing something? -
Adding an inline in the Django admin that is a ManyToMany which is using a custom through table
I am using django-ordered-model to add order to my models. I've had to use a custom through table so that things are ordered correctly. Everything is working fine at the moment except when it comes time to add the many to many relations to the admin. I would like to be able to select the toppings in the Pizza object view in the admin. # models.py from django.db import models from ordered_model.models import OrderedModel class Topping(models.Model): name = models.CharField(max_length=255) class ToppingThroughModel(OrderedModel): pizza = models.ForeignKey('Pizza', on_delete=models.CASCADE) topping = models.ForeignKey('TestTable', on_delete=models.CASCADE) order_with_respect_to = 'pizza' class Meta: ordering = ('pizza', 'order') class Pizza(models.Model): name = models.CharField(max_length=255) toppings = models.ManyToManyField('Topping', through='ToppingThroughModel', blank=True) I thought something like the following would work, but it does not. # admin.py from django.contrib import admin from app.models imprort Pizza, Topping class ToppingInline(admin.TabularInline): model = Pizza.toppings.though extra = 1 class PizzaAdmin(admin.ModelAdmin): inlines = [ToppingInline] -
Was creating model.manager and I believe I deleted the database
I am using Django 2.2.7, python 3.7.4 and windows 10. I am following django docs to create a project. I wanted to create a Queryset but I want to use my field names vs objects. By following tutorial, I created model.Manager (or so I thought). I executed python manage.py makemigrations and python manage.py migrate but in the migration file it appears I have deleted fields and maybe the DB, I'm not sure. What I was attempting is: DB name :district change the two field names ("congressional_district and zcta) from "objects" and instead use their names in the Manager model to call specifically. Did I confuse myself? from django.db import models class district(models.Model): congressional_district = models.IntegerField(default=0) zcta = models.IntegerField(default = 0, primary_key=True) #can integers be limited like Charfields? congressional_district = models.Manager() zcta = models.Manager() def __str__(self): return f'{self.congressional_district} {self.zcta}' ``` Migration file operations = [ migrations.AlterModelManagers( name='district', managers=[ ('congressional_district', django.db.models.manager.Manager()), ], ), migrations.RemoveField( model_name='district', name='congressional_district', ), migrations.RemoveField( model_name='district', name='zcta', ), migrations.AddField( model_name='district', name='id', field=models.AutoField(auto_created=True, default=django.utils.timezone.now, primary_key=True, serialize=False, verbose_name='ID'), preserve_default=False, ), ] -
Using Celery with Split Settings Folder
I inherited a project and the folder structure is confusing to me. I've used celery and django together before, but I always had one settings file and the structure was different. I'm having issues making this run and the documentation uses the traditional folder structure. Help would be greatly appreciated. Folder structure |Project |app1 |app2 |tasks.py |settings |__init__.py |apps.py |dbs.py |middleware.py |celery_config.py |__init__.py |celery.py |manage.py |urls.py |views.py |wsgi.py settings.apps.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'app1', 'app2' ] settings.celery_config.py BROKER_URL = 'redis://localhost:6379' CELERY_RESULT_BACKEND = 'redis://localhost:6379' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' Project.__init__.py from __future__ import absolute_import, unicode_literals # This will make sure the app is always imported when # Django starts so that shared_task will use this app. from .celery import app as celery_app __all__ = ('celery_app',) celery.py from __future__ import absolute_import, unicode_literals from .settings import celery_settings from celery import Celery import os # set the default Django settings module for the 'celery' program. os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings.celery_settings") app = Celery('eiu') # # Using a string here means the worker doesn't have to serialize # # the configuration object to child processes. # # - namespace='CELERY' means all celery-related configuration keys # # should have a … -
Nginx reverse proxying to Django receiving `upstream prematurely closed connection while reading response header from upstream`
At the risk of infuriating the community I'm not going to include any config as, while I'm sure it's relevant, I'm trying to understand the theory behind this phenomenon. Some teammates and I maintain a webserver for internal use. In the/our world of internal tools things are never productized. We typically are doing whatever is necessary to deliver some value to our co-workers. Stakes and available resources are low. As such we've committed a cardinal sin in standing up a Python 2 Django server on its own. No WSGI middleware, no additional processes. I've seen the admonitions but we've done what we've done. I recently stood up an Nginx instance in front of this abomination to give us the ability to "hot-swap" instances of our web application with zero downtime. I still did not insert anything in between. Nginx is simply reverse-proxying, over localhost http to the Django instance listening on a localhost non-standard port. After this change we started seeing bursts of 502s from Nginx. There are a few pages that are "live" in that they do some polling to check for updates to things. As such, there is "a lot" of traffic for the number of users we … -
django signals not working on usercreation
I created a signals supposed to create a profile for each created users in my signals.py file but it's not working. i've tried to check if there's an error with the command "python manage.py check" but that seems not to work as well... i've been on this for a whole 3hours..please help a friend. models.py from django.db import models from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) profile_pic = models.ImageField(default='default.jpg', upload_to='profile_pics') def __str__(self): return f"{self.user.username}'s profile " signals.py from django.db.models.signals import post_save from django.dispatch import receiver from django.contrib.auth.models import User from .models import Profile @receiver(post_save, sender=User) def create_profile(sender, created, instance, **kwargs): if created: Profle.instance.create(user=instance) @receiver(post_save, sender=User) def create_profile(sender, instance, **kwargs): instance.profile.save() apps.py from django.apps import AppConfig class UsersConfig(AppConfig): name = 'users' def ready(self): import users.signals what am i doing wrong -
I cannot import a function within the same file in Django
{% load static %} <!DOCTYPE html> <html> <head> <link rel="stylesheet" type="text/css" href="{% static 'css/calcu.css' %}"> </head> <form id="calci_form" method="get" action="operation"> <label class="l1">Number 1</label><input type="text" name="num1" class="tb1" value="{{fvalue}}"> <label class="l2">Number 2</label><input type="text" name="num2" class="tb2" value="{{svalue}}"> <label class="l3">Result</label><input type="text" class="tb3" name="user_input" value={{result}}> <input type="submit" name="sym" class="btn1" value="Calculate"> </form> </html> the above is my html page in Django - calculate.html I am new to django and I am just trying to add a function to print the sum of two numbers. the function is in add.py - def add(a,b): return a + b The function I am calling this from is in views.py - from django.shortcuts import render from django.http import HttpResponse from django.http import HttpResponseRedirect from django.shortcuts import redirect from add import add # Create your views here. def home(request): return render(request, "calculate.html") def operation(request): if 'sym' in request.GET: first = int(request.GET['num1']) second = int(request.GET['num2']) res = add(first,second) context = { 'fvalue': first, 'svalue': second, 'result': res, } return render(request,'calculate.html', context) now the add.py is in the same folder as views.py. However it says "The site can't be reached" Don't know what to do. -
Django PasswordChangeView throws "The password is too similar to the email address." error
I trying to create URL where users can change their passwords. This error is kinda weird, because I don't even have field for email in my registration form. In my registration form I asked user only for username and password. Also, I don't change standart User model. If someone need any code parts to help me, write what do you need. I don't even know what should I attach because have no idea what is going wrong. -
django-storages S3boto3 upload status
I'm using django-storages to upload several files using a Model with a FileField in Django Rest Framework. Everything works fine, the frontend aplication just waits until the upload finish and the promise is resolved i the fron while in the backend a database registry is save in the database. But when the files are too large or there is network issues, the promise just time out and the upload sometimes is done and sometimes is not, and sometimes it uploads the file without loading the link to the database. Is there any way to generate a progress indicator that shows me the upload status, I could request for the status with my frontend aplication, with a recursive request instead of a Promise that is timed out. Is there is any other sugestion i am open to hear one. -
Heroku versus AWS
I am trying to deploy a personal website (python django based framework) which contains text and few images. Can someone tell if their are any advantages and disadvantages of deploying to heroku versus AWS. PS: I have deployed it on AWS but the images are not loading. So I am considering Heroku but not sure if I should use Heroku or AWS would be more stable. -
How can I print this Django raw SQL query? Preferably to a table
I have been working on a Django app to help us clean up some old Tableau workbooks. It gives users a front end web ui to decide which books to keep and which to delete. I'm going to be handling a lot of this by way of SQL and Django. Here is the SQL query I have written: from django.db import connection username = str("lastname, firstname") def dictfetchall(cursor): # Returns all rows from a cursor as a dict desc = cursor.description return [ dict(zip([col[0] for col in desc], row)) for row in cursor.fetchall() ] def query(): cursor = connection.cursor() cursor.execute("SELECT Owner_Name,Owner_Email,Id,Name FROM tableau_books WHERE Owner_Name = %s", (username,)) results = dictfetchall(cursor) for item in results: print(item) Right now, this function just queries the fields I want and prints them in a legible way. Here is my view where I'm calling it: def dashboard(request): if request.method == 'POST' and 'run_script' in request.POST: # import function to run from main_app.queries import query # call function query() return render(request, 'dashboard.html') Lastly, here is my button I'm using to actually run the code in html: <form method="post"> {% csrf_token %} <button type="submit" name="run_script">Find Workbooks</button> </form> Is there an easy way to, instead of printing … -
How to increase quantity for each multiple items with the same slug url
How does one increases the quantity for each multiple item with the same slug url? When i added two items with the same slug url to cart, then i try to increase the quantity it only increases the first item in cart and not the second item. enter image description here Models.py class Item(models.Model): title = models.CharField(max_length=250) image = models.ImageField(null=True) price = models.IntegerField() old_price = models.IntegerField(null=True, blank=True) description = HTMLField() category = models.CharField(choices=CATEGORY_CHOICES, max_length=2) label = models.CharField(choices=LABEL_CHOICES, max_length=1) slug = models.SlugField(max_length=250, unique=True) timestamp = models.DateTimeField(auto_now_add=True) active = models.BooleanField(default=True) class Meta: ordering = ['-timestamp'] db_table = 'items' verbose_name_plural = 'Items' def __str__(self): return self.title class OrderItem(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) ordered = models.BooleanField(default=False) item = models.ForeignKey(Item, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) variation = models.ManyToManyField(Variation) def __str__(self): return f"{self.quantity} of {self.item.title}" Views.py def update_cart(request, pk, slug): item = get_object_or_404(Item, pk=pk) print(item) if request.method == 'POST': pk = request.POST.get('pk', None) #retrieve id qty = request.POST.get('quantity', None) order_item_qs= OrderItem.objects.filter( item=item, user=request.user, ordered=False ) if order_item_qs.exists(): item = order_item_qs.first() item.quantity = qty item.save() return redirect("shop:order-summary") Urls.py path('update-cart/<int:pk>-<slug:slug>/', update_cart, name='update-cart'), Order-sumarry template: <form method="POST" action="{{ order_item.item.get_update_cart_url }}"> {% csrf_token %} <p> <input type="button" value="-" class="minus"> <input type="number" value="{{ order_item.quantity }}" name="quantity" id="qty1" class="quantity_class" min="1" required> <input type="button" … -
unique_together in a model.Models vs uniquetogethervalidator of serializers
If i have a model A with (field1 and field2 are fields of model) `unique_together = ('field1', 'field2')` in Meta class and a serializer which is a model serializer on model A, then why should I or why should not I use Uniquetogethervalidator in Meta of serializer. Why we need this validator if we already have condition in Model? Or what is difference between using a unique_constraint in model and uniquetogethervalidator in serializer ? -
for loop with an integer in django's templates tags
In my Django template {{review.stars}} is an integer from 1 to 5, but instead of showing a simple number I want to show a number of star icons equal to the {{review.stars}} integer. I should write something like: for n in range(1, review.stars+1): add star icon but obviously I can't write something like that in Django template tags. What's the pythonic way to run a loop a variable number of times? -
Django dynamically add fields without creating new model instances
I'm attempting to create a form that allows someone to enter multiple phone numbers. I'd like to make it possible to click a button to add an additional field to the form but I am not quite sure how to do that. I looked at FormSets but I don't want to create a new model instance every time someone adds a new phone number. Thanks in advance -
django-objects tag filter
I'm calling a post.objects.all object on my html page. on the same page last-post. I made a filter for this but I get an error. calling the last 3 posts I want to do I can't type .objects.order_by () because it's probably an object. views.py : posts=post.objects.all() context = { 'posts': posts, 'category':category, } return render(request, "post/post-list.html", context) html: {%for post in posts|lasted %} filter.py @register.filter def lasted(post): return post.objects.order_by('post_date')[:3] AttributeError at /post/index/ 'Page' object has no attribute 'objects' Request Method: GET Request URL: http://127.0.0.1:8000/post/index/ Django Version: 2.2.7 Exception Type: AttributeError Exception Value: 'Page' object has no attribute 'objects' Exception Location: C:\Users\Barbaros\Desktop\All\env\lib\site-packages\django\template\defaultfilters.py in lasted, line 73 Python Executable: C:\Users\Barbaros\Desktop\All\env\Scripts\python.exe Python Version: 3.7.4 Python Path: ['C:\\Users\\Barbaros\\Desktop\\All', 'C:\\Users\\Barbaros\\Desktop\\All\\env\\Scripts\\python37.zip', 'C:\\Users\\Barbaros\\Desktop\\All\\env\\DLLs', 'C:\\Users\\Barbaros\\Desktop\\All\\env\\lib', 'C:\\Users\\Barbaros\\Desktop\\All\\env\\Scripts', 'c:\\users\\barbaros\\appdata\\local\\programs\\python\\python37-32\\Lib', 'c:\\users\\barbaros\\appdata\\local\\programs\\python\\python37-32\\DLLs', 'C:\\Users\\Barbaros\\Desktop\\All\\env', 'C:\\Users\\Barbaros\\Desktop\\All\\env\\lib\\site-packages'] Server time: Fri, 22 Nov 2019 20:36:41 +0000 -
Find users of security group with django-python3-ldap
Very new to LDAP and AD. I'm using django-python3-ldap to authenticate users of my django app. We want to make it so that only a subset of our users can access our django app, so yesterday they added the security group 'MyAppGroup.' Only problem is, I don't seem able to add this to the search base. User lookup always fails. Working search base (returns ALL users): "ou=Basic Users, ou=BIGAPP Users,dc=subd,dc=domain,dc=com" When I asked, they said that MyAppGroup was a security group, and that "Basic Users" and "BIGAPP Users" were "AD Members." dsquery group -name "MyAppGroup" returns: CN=MyAppGroup,OU=BIGAPP Groups,dc=subd,dc=domain,dc=com This result does not work as the search base. Do I need to add a custom search filter for this to work? Any help is appreciated. -
Django - how to dynamicaly create models in tests? (Django 2.x)
I would like to test my custom subclassed Django model field. I could use existing models from my project but they are quite complicated and hard to setup. I have found two SO question but the are quite old (2009 and 2012). #1 #2 So I wanted to ask if anyone knows a better way to achieve this. Django wiki has a dedicated page for custom fields, but there I haven't found anything about testing there. Thanks for any tip or suggestion. -
Empty Serialised Response in Django Rest Framework
I have a model, a view and a serializer which produce the following response representing a medical test: { "name": "electrocardiogram", "cost": "180.00", "results": [ { "id": "bff25813-5846-4eac-812f-7e57d8fbb496", "lots more things" : "were here, but I hid them for brevity's sake" "video": [] } ] } As you can see, it is a nested object which is put together by some nested DRF serializers. This is great, but I want to put a couple of custom database calls into my view logic as I want to keep track of which tests a user runs. To do this I have written. class RunTestView(generics.RetrieveAPIView): serializer_class = TestSerializer def get_object(self): if 'test' not in self.request.query_params: return Response({'Error': 'test not in request'}, status=status.HTTP_400_BAD_REQUEST) test = get_object_or_404(Test, id=self.request.query_params['test']) return test def get(self, request, *args, **kwargs): if 'case_attempt' not in request.query_params: return Response({'Error': 'case_attempt not in request'}, status=status.HTTP_400_BAD_REQUEST) case_attempt = get_object_or_404(CaseAttempt, id=request.query_params['case_attempt']) # get the test object which we will later serialise and return test = self.get_object() # if we've gotten this far, both case_attempt and test are valid objects # let's record this in the TestsRunTracking model if it is not already there if not TestsRunTracking.objects.all().filter(case_attempt=case_attempt, test=test, user=request.user).exists(): tracking = TestsRunTracking(case_attempt=case_attempt, test=test, user=request.user) tracking.save() # … -
How to edit object in forms if the form has __init__ method?
I have a form that have choice field and must be filtered by request.user and for this I use the init method. When it is initialized, the data is ready to be selected which is good but when I want to edit that object, it doesn't show the data stored in selected choice instead shows an empty select field. Is important that in both cases (create and edit) that object in choice field to be filtered by request.user. How can I edit the object if the form uses a init method? class EditarePereche(forms.ModelForm): boxa = forms.IntegerField(label="Boxa", min_value=1) sezon = forms.CharField(label="Sezon reproducere", initial=datetime.now().year) mascul = forms.ModelChoiceField(queryset=None, label="Mascul", empty_label="Alege mascul") femela = forms.ModelChoiceField(queryset=None, label="Femela", empty_label="Alege femela") serie_pui_1 = forms.TextInput() serie_pui_2 = forms.TextInput() culoare_pui_1 = forms.ModelChoiceField(queryset=None, label="Culoare pui 1", empty_label="Alege culoarea", required=False) culoare_pui_2 = forms.ModelChoiceField(queryset=None, label="Culoare pui 2", empty_label="Alege culoarea", required=False) data_imperechere = forms.DateInput() primul_ou = forms.DateInput() data_ecloziune = forms.DateInput() data_inelare = forms.DateInput() comentarii = forms.TextInput() # Functie pentru filtrarea rezultatelor dupa crescator def __init__(self, *args, crescator=None, **kwargs): super(EditarePereche, self).__init__(*args, **kwargs) self.fields['mascul'].queryset = Porumbei.objects.filter(crescator=crescator, sex="Mascul", perechi_masculi__isnull=True) self.fields['femela'].queryset = Porumbei.objects.filter(crescator=crescator, sex="Femelă", perechi_femele__isnull=True) self.fields['culoare_pui_1'].queryset = CuloriPorumbei.objects.filter(crescator=crescator) self.fields['culoare_pui_2'].queryset = CuloriPorumbei.objects.filter(crescator=crescator) class Meta: model = Perechi fields = "__all__" -
Serve to docker service with nginx in different endpoint
I'm building a multiservice webapp with two different services. The webfront and the API. I've manage to server the front, and make it communicate with the api internally, but i'm new to nginx and I've no idea how to do it. This is my actual ninx.conf for a django front. upstream webapp{ server front:8000; } server { listen 80; location / { proxy_pass http://webapp; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } location /staticfiles/ { alias /home/webapp/web/staticfiles/; } } The front is running with gunicorn in port 8000, and its served in http://localhost/. The api is running with gunicorn in port 5000 and I would like to access it like http://localhost/api This is how i define the service in the docker-compose file: api: build: context: ./API dockerfile: Dockerfile command: gunicorn -b 0.0.0.0:5000 api:api --limit-request-line 0 ports: - 5000:5000