Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: How do I check for duplicates before bulk_create (when defining the object)?
I would like to define an object and check if it is a duplicate before creating it,as shown below. if data['title'] in videos: I'm hoping I can determine it this way. How can I determine duplicates? videos = [] throughs = [] for datas in files: for data in datas: tags = data["tags"].split() tag_pks = list( set([Tag.objects.get_or_create(name=tag)[0].pk for tag in tags]) ) #Around here, we want to make sure that the list called videos already contains data['title']. video = Video( title=data["title"], thumbnail_url=data["thumbnail_url"], preview_url=data["preview_url"], embed_url=data["embed_url"], embed_source=data["embed_source"], duration=data["duration"], published_at=data["published_at"], ) for tag_pk in tag_pks: throughs.append( Video.tags.through(video_id=video.pk, tag_id=tag_pk) ) videos.append(video) Video.objects.bulk_create(videos) Video.tags.through.objects.bulk_create(throughs) -
django redirect to other page and auto login to that page
Is there a way to redirect to other page and automatically log into that page? So it's like I make django webpage with login and create link to facebook. When user clicks to facebook link, it should automatically login to his facebook page. Of course, I will have his facebook username and password on db I used to create the website. Is this possible? Basically, I am trying to create interface page on django with link to several different webpage and make user access to his page by simply logon to this interface page alone. -
Can't access fields on abstracted user model in Django
I have an abstracted user model like so: class MyAccountManager(BaseUserManager): """ Class to adjust the base user manager """ def create_user(self, email, username, password=None): if not email: raise ValueError("Users must have an email address") user = self.model( email=self.normalize_email(email), username=username, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, username, password): user = self.create_user( email=self.normalize_email(email), username=username, password=password, ) user.is_admin = True user.is_staff = True user.is_superuser = True user.is_active = True user.company = None user.cashpool = None user.save(using=self._db) return user class User(AbstractBaseUser): """ Main User model, inherits from AbstractBaseUser """ # Meta email = models.EmailField(verbose_name='email', max_length=60, unique=True) username = models.CharField(max_length=40, unique=True) # equals to email date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True) last_login = models.DateTimeField(verbose_name='last login', auto_now=True) # Relations company = models.ForeignKey(Company, on_delete=models.CASCADE, null=True) cashpool = models.ForeignKey(Cashpool, on_delete=models.CASCADE, null=True) # Booleans is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) # Manager objects = MyAccountManager() # Use Email as login USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] def __str__(self): return self.username def has_perm(self, perm, obj=None): return self.is_admin def has_module_perms(self, app_label): return True def get_full_name(self): return f'{self.username}' Now in a view I can't access the company field for instance: def test(request): company = request.user.company .. # settings.py # Custom User Model AUTH_USER_MODEL = "user.User" … -
Django call related object's function
I have the following models class Customer(models.Model): created_at = models.DateTimeField(auto_now_add=True) name = models.CharField(max_length=255) def as_dic(self): return {"id": self.id, "name": self.name } class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.PROTECT) quantity = models.PositiveSmallIntegerField() def as_dic(self): return {"id": self.id, "quantity": self.quantity, "customer": self.customer.as_dic() } then orders = Order.objects.select_related('customer').all() orders_list = [obj.as_dict() for obj in orders] the error message says 'Customer' object has no attribute 'as_dic' -
I am trying to use soaplib for python third version and getting some errors
I am migrating code from python2.7 to python3.6 where I am using soaplib and it is compatible with python 3.6 is there any other lib like this? -
How do I fix pagination when there is a GET filter from the URL?
In the main product browse page (www.url.com/works), pagination works well (displays 10 items at a time) and the URL becomes www.url.com/works/?page=2 In the same view, the works can be filtered by category (i.e. www.url.com/works/?collection=Drawing). Since it using the same view, it is still paginating by 10, but if I click other pages, it loses the /?collection=Drawing and just goes back to being www.url.com/works/?page=2. How do I combine them to be something like www.url.com/works/?collection=Drawing&page=2 ? Thank you! views.py class ProductListView(ListView): model = Product template_name = "products/product_all.html" paginate_by = 10 def get_queryset(self, *args, **kwargs): sold = ProductPurchase.objects.filter( refunded=False ).values_list('product_id') qs = super(ProductListView, self).get_queryset(**kwargs) qs = qs.filter(for_sale=True, test_check=False).exclude(id__in=sold).order_by('-timestamp') categoryfilter = self.request.GET.get("collection") if categoryfilter: qs = qs.filter( Q(category__name__icontains=categoryfilter) ) query = self.request.GET.get("q") if query: tags = Tag.objects.filter( slug=query ).values_list('products') qs = qs.filter( Q(title__icontains=query) | Q(description__icontains=query) | Q(material__icontains=query) | Q(id__in=tags) ).order_by("title") return MyFilterSet(data=self.request.GET, queryset=qs).filter() -
how to configure Postgres to work with pytest
I am using django for my backend and pytest to handle my tests. I switched my project db from sqlite3 to postgres, everything works just fine except for the tests, for some reason all of my them are failing. before switching I was able to access my db during my tests with the following line: pytestmark = pytest.mark.django_db but now after using Postgres as my db I get this error on all of my tests UndefinedTable The above exception was the direct cause of the following exception: request = <SubRequest '_django_db_marker' for <Function test_logged_user_saved_recipes_url_reverse>> @pytest.fixture(autouse=True) def _django_db_marker(request): """Implement the django_db marker, internal to pytest-django. This will dynamically request the ``db``, ``transactional_db`` or ``django_db_reset_sequences`` fixtures as required by the django_db marker. """ marker = request.node.get_closest_marker("django_db") if marker: transaction, reset_sequences = validate_django_db(marker) if reset_sequences: request.getfixturevalue("django_db_reset_sequences") elif transaction: request.getfixturevalue("transactional_db") else: > request.getfixturevalue("db") does anyone knows the right way to access Postgres db while using pytest? or maybe there is a way to switch to sqlite3 db only when testing? thanks in advance -
Use of serializer class in other frameworks
Why isn't there a serializer class just like in DRF Djnago in node, express , laravel or RoR?? Is it just on python we need serialization? In every other framework, are data saved as json in database? I dont think so. Can someone explain this? For eg in DRF we have something like this: class Leadserializer(serializers.ModelSerializer): class Meta: model = Lead fields = '__all__' Here this serializer class serializes all the fields of Lead model while calling a get api. It brings out the complex queryset to json format in api response. Shouldnt the same thing be happening in all other frameworks as well?? -
How to Save a Query Set of Objects in a Single Transaction without using a for loop in Django ORM
Just a quick question, for ex, posts variable has n objects, and i need to save the post id in a post_tag model, how can i achieve without using a for loop, and just with the a single transaction using Django ORM. Here is a small snippet what i want to achieve: posts = Post_Tag.objects.filter(tag_id = subcat).values_list('post_id', flat = True) for post in posts: post_home_feed = Post_Home_Feed.objects.create(post_id = post.post_id, user_id = user_id.id) Any leads much appreciated, Thanks in advance. -
when i try to create a blog post is shows not null constraint failed: blog_blog.id
when i try to create a blog post is shows not null constraint failed: blog_blog.id and i have tried everything possible to fix this and it still not working i dont know if i should add and id field in my models.py let me show my code models.py # some field are commented out because i was trying them to see if it would work class Blog(models.Model): id = models.UUIDField(primary_key=True, editable=False) title = models.CharField(max_length=10000, null=True, blank=True, verbose_name="Title") content = models.TextField(verbose_name="Post Content") # slug = models.SlugField(unique=True) image = models.ImageField(upload_to="blog-images/%Y/%m/%d/", verbose_name="Post Thumbnail") category = models.ForeignKey(Category, on_delete=models.DO_NOTHING, verbose_name="Category", null=True) tags = models.ManyToManyField(Tag, related_name='tags', verbose_name="Tag") status = models.CharField(choices=STATUS_CHOICE, default="published", max_length=150, verbose_name='Status') creator = models.ForeignKey(User, on_delete=models.DO_NOTHING, verbose_name="Creator", null=True) created = models.DateTimeField(auto_now_add=True ,verbose_name="Created", null=True) def get_absolute_url(self): # return reverse('blog:blog-details', args=[self.slug]) return reverse('blog:blog-details', kwargs={'pk': self.pk}) class Meta: verbose_name = "Blog Post" verbose_name_plural = "Blog Posts" def __str__(self): return self.title views.py def blogpost(request): if request.method == "POST": form = BlogPostForm(request.POST, request.FILES) if form.is_valid(): form = form.save(commit=False) form.creator = request.user form.save() messages.success(request, f'Hi, Your Post have been sent for review and would be live soon!') return redirect('blog:home') else: form = BlogPostForm() context = { "form": form } return render(request, 'blog/AddPost.html', context) urls.py path('', views.blog_list, name="home"), path('post/<int:pk>', views.blog_detail, name="blog-details"), path('post/categories/<slug:category_slug>', … -
Using Django/Postgres to store binary data in a memory efficient manor
Context I have a Django project, and inside of this project, I have a database model with a field of type models.BinaryField(max_length=50000000, default=b'0') Problem When the server is requested to query for this binary data, even though there are never more than 1-2 concurrent requests, I am reaching the ram limits of my server using io.BytesIO, along with stream.seek({index}), and stream.close()(I use the term stream very loosely, as I am simply referring to seeking and closing a stream of bytes here). Question Is it possible that I need to implement the way I am storing this binary data differently? Solutions that I have tried that didn't work Would splitting it up into chunks of smaller sizes be computationally more efficient for the RAM of the server? When I attempted this, I discovered that chunking up the file into smaller chunks and relating them with a many-to-one relationship was extremely taxing as far as overhead on the database. -
How do I get collectstatic to work when running a DjangoApp on Heroku?
I have a Django App that am trying to deploy on Heroku I am sharing my log file and my settings.py and urls.py file as well. This is my log file 2021-11-18T17:47:23.000000+00:00 app[api]: Build started by user ravirajkukade11@gmail.com 2021-11-18T17:47:49.297666+00:00 app[api]: Release v55 created by user ravirajkukade11@gmail.com 2021-11-18T17:47:49.297666+00:00 app[api]: Deploy 6d11bc39 by user ravirajkukade11@gmail.com 2021-11-18T17:47:49.717498+00:00 heroku[web.1]: Restarting 2021-11-18T17:47:49.753132+00:00 heroku[web.1]: State changed from up to starting 2021-11-18T17:47:50.533623+00:00 heroku[web.1]: Stopping all processes with SIGTERM 2021-11-18T17:47:50.719741+00:00 app[web.1]: [2021-11-18 23:17:50 +0530] [9] [INFO] Worker exiting (pid: 9) 2021-11-18T17:47:50.719816+00:00 app[web.1]: [2021-11-18 23:17:50 +0530] [10] [INFO] Worker exiting (pid: 10) 2021-11-18T17:47:50.719923+00:00 app[web.1]: [2021-11-18 17:47:50 +0000] [4] [INFO] Handling signal: term 2021-11-18T17:47:50.723833+00:00 app[web.1]: [2021-11-18 17:47:50 +0000] [4] [WARNING] Worker with pid 9 was terminated due to signal 15 2021-11-18T17:47:50.820321+00:00 app[web.1]: [2021-11-18 17:47:50 +0000] [4] [INFO] Shutting down: Master 2021-11-18T17:47:50.953355+00:00 heroku[web.1]: Process exited with status 0 2021-11-18T17:47:54.323110+00:00 heroku[web.1]: Starting process with command gunicorn resume_app.wsgi 2021-11-18T17:47:55.884509+00:00 app[web.1]: [2021-11-18 17:47:55 +0000] [4] [INFO] Starting gunicorn 20.1.0 2021-11-18T17:47:55.884907+00:00 app[web.1]: [2021-11-18 17:47:55 +0000] [4] [INFO] Listening at: http://0.0.0.0:5402 (4) 2021-11-18T17:47:55.884969+00:00 app[web.1]: [2021-11-18 17:47:55 +0000] [4] [INFO] Using worker: sync 2021-11-18T17:47:55.887917+00:00 app[web.1]: [2021-11-18 17:47:55 +0000] [9] [INFO] Booting worker with pid: 9 2021-11-18T17:47:55.895825+00:00 app[web.1]: [2021-11-18 17:47:55 +0000] [10] [INFO] Booting worker with pid: 10 … -
I don't understand how to use the django-dynamic-formset plugin
I am using the Django Dynamic Formset However, I have not found a documentation for noobs who are just starting out, I feel that they already take many things for granted and do not go step by step. I have several doubts: In point 5 of the page, it mentions that I must write jquery.formset.js in my MEDIA_ROOT and I must include the jQuery library if my MEDIA_ROOT, but how will I do that if mine is like this MEDIA_ROOT = os.path.join (BASE_DIR, ' photos') in point 4 of the plugin documentation it says this prefix: '{{formset.prefix}}' which means prefix here -
How to delete model by filtering with pk
I am trying to delete an entire model using pk, but when I click on "delete" I am redirected to the given page but nothing happens model is still there and not being deleted, but when I write the 'room_name' instead of 'pk' it does work, (thanks in advance) *Views.py: def delete_room(request, pk): Room.objects.filter(name=pk).delete() return redirect('home') Urls.py: path("delete/<int:pk>/", views.delete_room, name="delete_room") Models.py: class Room(models.Model): name = models.CharField(max_length=100) about = models.TextField(max_length=500, null=True, blank=True) creator = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True, related_name='room_creator') members = models.ManyToManyField(User, through="RoomMember") class RoomMember(models.Model): approved = models.BooleanField(default=False, blank=False) room = models.ForeignKey(Room, related_name='memberships', on_delete=models.CASCADE) user = models.ForeignKey(User, related_name='user_groups', on_delete=models.CASCADE) class Messages(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=False, blank=False) text = models.CharField(max_length=10000, blank=False, null=False) date = models.DateTimeField(default=datetime.now) room = models.ForeignKey(Room, null=True, blank=False, on_delete=models.CASCADE) Html: <a class="btn btn-danger" href="{% url 'delete_room' pk=room.pk %}">Delete Room</a>* -
Wrong decimal round to first 2 digits of amounts in python 3.7 and Django
Let there be 3 Django fields: INPUT = models.DecimalField(max_digits=20, decimal_places=3, default=0) RESULT = models.DecimalField(max_digits=20, decimal_places=3, default=0) RATE = models.DecimalField(max_digits=12, decimal_places=5, default=1) RATE is always Decimal('1.00000'). I want to have RESULT = INPUT * RATE and since the source is either from database, either from APIs, I use: RESULT = Decimal(INPUT) * Decimal(RATE) I do not know why, but in some cases (≈ 2%) I end with the numbers you see in the following table. There is a round to the first 2 digits. Do you know what could cause that? I do not see anything in the code that could do that and I am clueless. Both columns should be equal. RESULT INPUT 610.000 609.000 3700.000 3743.520 1200.000 1159.000 570.000 573.300 61.000 61.470 1300.000 1321.550 44.000 43.730 130.000 125.770 18.000 18.500 100.000 99.590 41.000 40.650 95.000 94.880 19.000 18.710 36.000 35.640 120.000 118.800 12.000 12.290 11.000 11.260 1.000 1.030 160.000 155.970 190.000 186.850 51.000 50.770 130.000 128.150 12.000 12.290 11.000 11.260 25.000 24.940 24.000 23.640 -
Makefile code-convention pylint set doen'st work
Im trying to configure code-convention at my project with pylint and flak8, I set configurations in the file and run 'make code-convention', but its return ModuleNotFoundError: No module named 'myproject'. The $PATH variable is correctly configured. My Makefile: code-convention: export DJANGO_SETTINGS_MODULE=myproject.config.settings ;\ flake8 myproject ;\ pylint myproject/ up_env: docker-compose up -d up_env_build: docker-compose up -d --build down_env: docker-compose rm --stop --force logs_env: docker-compose logs -f # Server run_server: python -m application all: clean create-venv setup-dev test-cov default_target: clean code-convention test-cov -
Django verbose logging for bad request
I am relatively new to django. I recently deployed my application on a web server, and I find it very hard to debug issue. I am getting 400 Http status code for some of my requests and not sure why. I am trying to increase the level of logs in order to find the root cause for it. However, the output of the logs in not very informative. I am using this configuration for logging (DEBUG is enabled): logging.config.dictConfig({ 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'console': { 'format': '%(name)-12s %(levelname)-8s %(message)s' }, 'file': { 'format': '%(asctime)s %(name)-12s %(levelname)-8s %(message)s' } }, 'handlers': { 'console': { 'class': 'logging.StreamHandler', 'formatter': 'console' }, 'file': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'formatter': 'file', 'filename': '/var/log/django/debug.log' } }, 'loggers': { '': { 'level': 'DEBUG', 'handlers': ['console', 'file'] } } }) This is the output that I am getting in the logs: 2021-11-18 16:18:59,667 django.request WARNING Bad Request: /create How can increase the verbosity of the logs to be more informative? -
Django url kwargs in templates
Previously we have been accessing kwargs in Django templates with {{view.kwargs.kwarh_name}}. However, it has been to my surprise that this is not working in my django 3.2.4+ Has it been removed, is there any issue with the line above? Note: Kwargs here I mean something like below: Given a function as below: def GetSomething(request, code): return render(request, "some template here") Now, the urlpatterns would be something like, import GetSomething from .views app_name = "some_app_name_here" urlpattern = [ path("link/<int:code>/", GetSomething, name="some_cool_name") #http:localhost/link/12345/ ] Now in HTML/Django templates or Jinja2(whichever you use), accessing this code would be via {{ view.kwargs.code }} But it so happens that this is not working for me in Django 3.2, any reasons?? Hope I was very clear! -
Django DurationField just for HH:MM never needing seconds?
I have a DurationField in my DB and trying to use this in ModelForm` with the purpose of keeping track of days if any, and only hours and minutes. I do not need seconds at all. I have tried to build out custom functionality to do this, as follows... def duration_string(duration): days = duration.days seconds = duration.seconds minutes = seconds // 60 hours = minutes // 60 minutes = minutes % 60 dur_string = f'{hours}:{minutes}:00' if days: dur_string = 'f{days} + dur_string' return dur_string class CustomDurationField(forms.DurationField): def prepare_value(self, value): if isinstance(value, datetime.timedelta): return duration_string(value) return value class TimeForm(ModelForm): setup_duration = CustomDurationField() now in my form field, when a user enters 1:45 I want this to register as 1 hour and 45 minutes, yet when I check my database, 00:01:45 is returned, which is 1 minute and 45 seconds. In my shell, I am getting a timdelta object such as datetime.timedelta(seconds=105) If anybody has any guidance as to how to accomplish this would be greatly appreciated! -
django path to view
hey i have a url path that i want to lead me to an application url file but it says page not found here is my core url: from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include('store.urls', namespace='store')), path('basket/', include('basket.urls', namespace='basket')), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) and here is my basket.url file: from django.urls import path from . import views app_name = 'basket' urlpatterns = [ path('', views.basket_summary, name='basket_summary'), ] and this is the view: from django.shortcuts import render # Create your views here. def basket_summary(request): return render(request, 'store/basket/summary.html') my app name is basket , and i might add all of the files are defined. whats the problem ? -
Django - Invalid template name in 'extends' tag: ''. Got this from the 'current_module.base_template' variable
In my project I wanted to apply django-material frontend according to this tutorial http://docs.viewflow.io/frontend_crud.html I just wanted to add one more application to an existing and working project. Unfortunately, I ran into a problem with urls.py configuration Here are some code snippets that may be relevant INSTALLED_APPS ... INSTALLED_APPS = [ 'epm.apps.EpmConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_extensions', 'organize', 'crispy_forms', 'compressor', 'bootstrap_modal_forms', 'django_filters', 'fontawesome-free', 'material', 'material.frontend', 'viewflow', 'viewflow.frontend', 'ordercard', 'general.apps.GeneralConfig' ] ... TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', #'DIRS': [], 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'APP_DIRS': True, ... ... ... My global urls.py from django.contrib import admin from django.urls import path, include from django.conf.urls import url from material.frontend import urls as frontend_urls from pprint import pprint #from . import views urlpatterns = [ path('', include('epm.urls')), path('card/', include('ordercard.urls')), path('admin/', admin.site.urls), path('auth/', include('django.contrib.auth.urls')), path('viewflow/', include(frontend_urls)), path('organize/', include('organize.urls')), url(r'general/', include('general.urls')), path('', include(frontend_urls)), ] and my urls.py from general app from django.conf.urls import url, include from django.views import generic from material.frontend import urls as frontend_urls from . import views app_name='general' urlpatterns = [ url('^$', generic.RedirectView.as_view(url='./customer/'), name="index"), url('^customer/', include(views.MyModelViewSet().urls)), #url(r'', include(frontend_urls)), #url('', generic.TemplateView.as_view(template_name="sales/index.html"), name="index"), ] With this configuration of files, he gets an error message: TemplateSyntaxError at /general/customer/ Invalid template name in 'extends' tag: … -
Apply a migration to Django Flatpage model
I would like to use the modeltranslation package in a Django application that uses the flatpages app. I installed both, followed the model translation docs, and created a translation.py file, which I put in the main app (where all the global stuff lies), as I can't put it directly in the flat pages app (Django code is a requirement and is not committed to VCS). # django/main/translation.py from modeltranslation.translator import translator, TranslationOptions from django.contrib.flatpages.models import FlatPage class FlatPageTranslationOptions(TranslationOptions): fields = ('title', 'content') translator.register(FlatPage, FlatPageTranslationOptions) Then I ran python manage.py makemigrations, and it created a migration file in the flatpages app /usr/local/lib/python3.8/site-packages/django/contrib/flatpages/migrations/0002_auto_20211118_1558.py. It would be again in the Django code, so I tried to simply move it to the main app at django/main/migrations/0002_flatpages_translations.py (there is already an unrelated 0001_initial.py migration, which has no dependencies): from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('flatpages', '0001_initial'), ] operations = [ migrations.AddField( model_name='flatpage', name='content_en', field=models.TextField(blank=True, null=True, verbose_name='content'), ), migrations.AddField( model_name='flatpage', name='content_fr', field=models.TextField(blank=True, null=True, verbose_name='content'), ), migrations.AddField( model_name='flatpage', name='title_en', field=models.CharField(max_length=200, null=True, verbose_name='title'), ), migrations.AddField( model_name='flatpage', name='title_fr', field=models.CharField(max_length=200, null=True, verbose_name='title'), ), ] And... when I finally try to run the migration (python manage.py migrate), I got this error: CommandError: Conflicting migrations detected; multiple leaf … -
How to get a list of existing student names in Django?
I am new to Django rest framework, I want to get a list of the student first names(only) when it is existed. can anyone help me? In my model.py class School(models.Model): name = models.CharField(max_length=100, null=False, blank=False) city = models.CharField(max_length=100, null=False, blank=False) street = models.CharField(max_length=100, null=False, blank=False) def __str__(self): return f"{self.city}->{self.street}->{self.name}" class Student(models.Model): school_id = models.ForeignKey(School, on_delete=models.CASCADE) first_name = models.CharField(max_length=100, null=False, blank=False) last_name = models.CharField(max_length=100, null=False, blank=False) def __str__(self): return f"{self.first_name} {self.last_name}" In my serializers.py: class StudentSerializer(serializers.Serializer): class Meta: model = Student fields = ['first_name'] class SchoolSerializer(serializers.Serializer): is_existing_student = = serializers.BooleanField() student = StudentSerializer(many=True, read_only=True) class Meta: model = School fields = ['is_existing_student','student'] In my views: class schoolViewSet(viewsets.ModelViewSet): serializer_class = SchoolSerializer queryset = School.objects.all() In this picture you can see how it should look like [1]: https://i.stack.imgur.com/bR8cN.png -
/etc/nginx/conf.d/default.conf is not a file or does not exist
I am trying to route both Django and React with NGINX via docker-compose. The error I get is /etc/nginx/conf.d/default.conf is not a file or does not exist Here is my docker file version: "3.9" services: web: container_name: web build: context: ./backend dockerfile: Dockerfile command: gunicorn server.wsgi:application --bind 0.0.0.0:8000 volumes: - django_static_volume/:/usr/src/app/static expose: - 8000 env_file: - ./backend/.env depends_on: - db react: container_name: react build: context: ./frontend dockerfile: Dockerfile volumes: - react_static_volume:/usr/src/app/build/static expose: - 3000 env_file: - ./.env.dev command: serve -s build -l 3000 depends_on: - web db: image: postgres:12.0-alpine volumes: - postgres_data:/var/lib/postgresql/data/ env_file: - ./backend/.env nginx: container_name: nginx restart: always build: ./nginx volumes: - django_static_volume:/usr/src/app/django_files/static - react_static_volume:/usr/src/app/web_frontend/static ports: - 80:80 depends_on: - react - db - web volumes: postgres_data: react_static_volume: django_static_volume: here is my nginx.conf upstream django_backend { server django:8000; } upstream react_frontend { server react:3000; } server { listen 80; ########### # URL ROUTING # ########### location /admin { proxy_pass http://django_backend; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } location /api { proxy_pass http://django_backend; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } ########### # STATIC FOLDER ROUTING # ########### location /static/admin/ { alias /usr/src/app/django_files/static/admin/; } location /static/rest_framework/ { alias /usr/src/app/django_files/static/rest_framework/; } location /static/ { alias /usr/src/app/react_files/static/; } … -
Change available options in select but don't change selected one
I wan't to create Django/JavaScript mechanism that will enable me to change form select data based on other selected fields. For example let's say I have two select fields, I change the first one, then the function is triggered in Django and new template is loaded to html select element (I am using Ajax for that). This works fine, but the problem is when I will choose element 1 and then I want element 2 to also be able to change element1, the first option is reseted. I was trying to solve this by remembering the selected field and then loading it in but it then triggers element 2 and it, won't work. Any help will be appreciated :)