Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DJango, the preivous post or the next post according to that category list
I am studying to develope a blog website using DJango's generic view class. I categorized blogs into categories. If you select a blog from the full list and go to the detail page, you have implemented the ability to go to the previous post and the next post using "previous()" and "next()" in that post. I want to select a blog from a category list and move it to the preivous post or the next post according to that category list, but I don't know how. What can I do? models.py class Post(models.Model): .......... def prev(self): return self.get_previous_by_created_at() def next(self): return self.get_next_by_created_at() views.py class PostListByCategory(PostList): def get_queryset(self): slug = self.kwargs['slug'] if slug == 'no_category': category = None else: category = Category.objects.get(slug=slug) return Post.objects.filter(category=category).order_by('-pk') def get_context_data(self, **kwargs): context = super(PostListByCategory, self).get_context_data() slug = self.kwargs['slug'] if slug == 'no_category': category = 'None' else: category = Category.objects.get(slug=slug) context['category'] = category return context post_detail.html .............. <div class="row row-cols-auto"> {% if object.next %} <div class="col"> <a href="{% url 'tube_detail' object.next.pk %}" class="btn btn-sm pt-1 pb-1 bg-light" title="Prev"> <i class="bi bi-caret-left-fill" style="color:#dd3535"></i> </a> </div> {% endif %} <div class="col"> <a href="{% url 'tube_list' %}{% if request.GET.category %}category/{{ request.GET.category}}{% endif %}" class="btn btn-sm pt-1 pb-1 bg-light" title="LIST"> … -
Django SimpleTestCase debug method not displaying the debug message
so i'm using this test to display a debug message indicating success if the response code is 200 : class ExampleTestCase(SimpleTestCase): def test_example(self): # Your test code response = self.client.get("/") # Debugging output if the test succeeds if self.assertEqual(response.status_code, 200): self.debug('Debug message: test succeeded') but when i use python3 manage.py test to run the tests i got no Debug message instead i got a simple output indicating that the test passes: System check identified no issues (0 silenced). . ---------------------------------------------------------------------- Ran 1 test in 0.018s OK my question is how to add the debug message to the above output ? -
(this file is not in the editor because it is either binery or uses an unsapported text encoding)?
Im using vscode and I head with this error while using html template and jinja files and when im going to open such a file this error appears lately I tried installing jinja extension but it was not a deal solution !!!!! -
Type error when changing model object in admin
When I try to change an object in django admin, I get a Type error. This happens with all the objects of that model, but not with other models. I suspect there is something wrong in my model, or at least something that django admin doesn't appreciate. Here is the error: TypeError at /admin/events/evenement/10/change/ type object argument after ** must be a mapping, not QuerySet Request Method: GET Request URL: http://127.0.0.1:8000/admin/events/evenement/10/change/ Django Version: 4.1.5 Exception Type: TypeError Exception Value: type object argument after ** must be a mapping, not QuerySet This is my model class Evenement(models.Model): name = models.CharField(max_length=50) url_name = models.SlugField(max_length=50, blank=True) datum = models.DateField() locatie = models.CharField(max_length=100) omschrijving = models.TextField() evenement_type = models.ForeignKey(EvenementType, on_delete=models.PROTECT) ideal = models.BooleanField() aantal_honden_toegestaan = models.IntegerField(default=2) annuleren_toegestaan = models.BooleanField(default=True) alleen_flatcoat = models.BooleanField(default=False) secretariaat = models.ForeignKey(Group, on_delete=models.PROTECT, limit_choices_to=limit_secretary_choices) publicatiedatum_vanaf = models.DateField() inschrijven_vanaf = models.DateField() inschrijven_tot = models.DateField() onderdelen = models.ManyToManyField(Onderdeel, blank=True) prijs_leden = models.DecimalField(max_digits=5, decimal_places=2) prijs_niet_leden = models.DecimalField(max_digits=5, decimal_places=2) extra_onderdelen = models.ManyToManyField(ExtraOnderdeel, blank=True) def __str__(self): return '{} ({})'.format(self.name, self.datum.strftime('%d-%m-%Y')) class Meta: verbose_name_plural = "Evenementen" If more info is needed I will provide of course. The model works fine when I use it in webviews and forms, so I don't understand what the problem could be. … -
store phone field use django-phonenumber-field override search method to e164 format
i have store phone field to database using django-phonenumber-field with e164 format, its success formated and succesfully. this is my model.py class External(models.Model): name = models.CharField(max_length=255, unique=True) address = models.CharField(max_length=255) type= models.ForeignKey(Type, on_delete=models.CASCADE, verbose_name="Type") region= models.ForeignKey(Region, on_delete=models.CASCADE, verbose_name="Region") email = models.EmailField(max_length=254, unique=True) phone = PhoneNumberField(null=True, blank=True, unique=True) status = models.BooleanField(default=True) created_at = models.DateTimeField('date created', auto_now_add=True) updated_at = models.DateTimeField('last edited', auto_now=True) def __str__(self): return self.name but the problem is when i seacrh using national format like 0216333007 no data found. can someone help me to override the search methode when user input 0216333007 auto format to e164 = +62216333007 ? im using django 4.1.5 thanks to anyone who helps me. sorry for my bad english. -
How to fix AttributeError: 'NoneType' object has no attribute 'encode' in setting.py Django
I want to streamline the coding process by running DATABASE_URL from docker-compose files to use setting.py, can you suggest a solution to the error I'm experiencing? When I use python manage.py migrate I came across this problem. DATABASES = {'default': dj_database_url.parse(DATABASE_URL.encode())} AttributeError: 'NoneType' object has no attribute 'encode' docker-compose.yml version: '3.7' services: db: image: mariadb:10 command: --default-authentication-plugin=mysql_native_password restart: always environment: - MYSQL_ROOT_PASSWORD=mariadb - MYSQL_DATABASE=mariadb - MYSQL_USER=mariadb - MYSQL_PASSWORD=mariadb - MARIADB_ROOT_PASSWORD=mysecretpassword ports: - 3306:3306 volumes: - "mysqldata:/var/lib/mysql" web: build: . restart: always command: python manage.py runserver 0.0.0.0:8000 environment: - DATABASE_URL=mariadb+mariadbconnector://user:mariadb@db:3306/mariadb ports: - "8000:8000" depends_on: - db volumes: mysqldata: setting.py import os import dj_database_url DATABASE_URL = os.environ.get('DATABASE_URL') DATABASES = {'default': dj_database_url.parse(DATABASE_URL.encode())} -
RelatedObjectDoesNotExist with TabularInline and proxy models
my app's models include the Service model along with three proxy models: class Service(models.Model): SERVICE_TYPE_CHOICES = [ ('AR', 'Area'), ('OC', 'Occupancy'), ('CO', 'Consumption'), ] service_type = models.CharField(max_length=2, choices=SERVICE_TYPE_CHOICES) building = models.ForeignKey(Building, on_delete=models.CASCADE) def __init__(self, *args, **kwargs): super(HouseService, self).__init__(*args, **kwargs) subclasses = { 'AR' : AreaService, 'OC' : OccupancyService, 'CO' : ConsumptionService, } self.__class__ = subclasses[self.service_type] class AreaServiceManager(models.Manager): def get_queryset(self): return super(AreaServiceManager, self).get_queryset().filter(service_type='AR') def create(self, **kwargs): kwargs.update({'service_type': 'AR'}) return super(AreaServiceManager, self).create(**kwargs) class AreaService(Service): objects = AreaServiceManager() def save(self, *args, **kwargs): self.service_type = 'AR' return super(AreaService, self).save(*args, **kwargs) class Meta: proxy = True # Manager and Model class definitions omitted for the other two proxy models This works as intended such that I can create objects for each proxy model transparently by registering them for the admin interface, and queries for Service.objects will return the proper proxy/subclass objects. But when I try to add a TabularInline to admin.py – class ServiceInlineAdmin(admin.TabularInline): model = Service extra = 0 class BuildingAdmin(admin.ModelAdmin): inlines = [ServiceInlineAdmin,] – I get the following error message for the line self.__class__ = subclasses[self.service_type] in models.py (s. above): __class__ <class 'services.models.Service'> args () kwargs {} self Error in formatting: RelatedObjectDoesNotExist: Service has no building. subclasses {'AR': <class 'services.models.AreaService'>, 'CO': <class 'services.models.ConsumptionService'>, … -
Is there a proper filter for Django Rest Framework to work with PostgreSQL InetAddressField
I am using DRF and PostgreSQL to store IP, Subnet and IP Range data. For the filters I wanted to create a filter that resolves the given reach string and checks if a given IP is not only an exact match, but also part of a subnet or IP range in the database. PostgreSQL does have a number of operators that can be used for a lookup in InetAddressFields. PostgreSQL Documenation But it seems none are supported by Django/DRF. The django.contrib.postgres.fields package seems to have none of the network address fields. Is there a well supported module or any other way to implement proper filters for InetAddressField in DRF? -
Django project crashes server when admin backend is accessed
Problem I am running apache2 on my local ubuntu server. I set up a Django project using django-admin startproject site and set up my virtual host to use a WSGI Daemon process to run the Django project. This worked and the site is accessible through its IP 192.168.1.3. When I go to /admin, it allows me to log in and see the initial backend but loads for 5 minutes then goes to a 500 error when I click anything or reload, even when trying to access the non-admin index page. This persists until I run systemctl restart apache2 and completely restart apache or wait ~10-15 minutes until it fixes itself (only to break again immediately if I access /admin pages). Versions Django version 4.1.5 mod-wsgi version 4.9.4 My Attempts If I run the project with python manage.py runserver, I can access it on 192.168.1.3:8000 and fully use the /admin backend, even creating new users, etc. I then thought it was the WSGI Daemon process somehow messing it up, so I followed the linked section of this page: https://pypi.org/project/mod-wsgi#using-mod-wsgi-express-with-django and ran the site with python manage.py runmodwsgi. The site completely works on 192.168.1.3:8000 along with the /admin, and I can create … -
Initial values for some fields from db
Is it possible to put data from the database in the initial form? def add_customer_from_list(request, pk): application = Contact.objects.get(pk=pk) params = {'name': application.name, 'email': application.email, 'phone_number': application.phone_number, 'dog_name': application.dog_name, 'service_type': application.service_type} form = CustomerForm(request.POST or None, initial=params) if form.is_valid(): """form.name = form.cleaned_data['name'] form.email = form.cleaned_data['email'] form.phone_number = form.cleaned_data['phone_number'] form.address = form.cleaned_data['address'] form.dog_name = form.cleaned_data['dog_name'] form.dog_age = form.cleaned_data['dog_age'] form.service_type = form.cleaned_data['service_type'] form.training_place = form.cleaned_data['training_place'] form.contact_date = form.cleaned_data['contact_date'] form.source = form.cleaned_data['source'] form.status = form.cleaned_data['status'] form.notes = form.cleaned_data['notes']""" form.save() return redirect('xxx') return render(request, 'xxx', {'form' : form}) I would like some fields to be automatically filled in from the database with data, I have already tried various ways but to no avail What I wrote above for some reason does not fill the fields for me -
Problem displaying selected size from one template to another
I have two views that store and cart, also with templates for both of them. I have defined 3 sizes option in Product model and showing them in a form in store. I am getting diifculty rendering that selected size in my cart.html These are the views that i have for them: def store(request): if request.user.is_authenticated: customer = request.user.customer order, created = Order.objects.get_or_create(customer=customer, complete=False) items = order.orderitem_set.all() cartItems = order.get_cart_items if request.method == 'POST': size = request.POST.get('size') return redirect('cart', size=size) else: items = [] order = {'get_cart_total':0, 'get_cart_items':0} cartItems = order['get_cart_items'] c1 = ProductCollection.objects.get(name='c1') products = c1.products.all() context = { 'c1': c1, 'products': products, 'cartItems': cartItems, } return render(request, 'store.html', context) def cart(request): if request.user.is_authenticated: customer = request.user.customer order, created = Order.objects.get_or_create(customer=customer, complete=False) items = order.orderitem_set.all() cartItems = order.get_cart_items size = request.POST.get('size') else: items = [] order = {'get_cart_total':0, 'get_cart_items':0} cartItems = order['get_cart_items'] context = { 'items': items, 'order': order, 'cartItems': cartItems , 'size': size } return render(request, 'cart.html', context) This is store.html template: <div class="row" > {% for product in products %} <div class="col-lg-4"> <img class="thumbnail" src="{{product.imageURL}}"> <div class="box-element product"> <h6><strong>{{product.name}}</strong></h6> <hr> <form method="post" > {% csrf_token %} <label for="size">Select size:</label> <select id="size" name="size"> <option value="{{ product.size_option_1 }}">{{ product.size_option_1 … -
How to send JSON from NodeJS to Django?
The architecture of our app uses NodeJS and Django together. I need to send a JSON data as a HTTP post from NodeJS to Django without receiving any request before that from Django. Because, there is a function in NodeJS that generates and returns JSON data such that whenever this data returned, NodeJS must send (post) it to Django. I don't know any thing about that and have not any idea for that. What should I do? What APIs/modules do I need to use and how should I work with NodeJS and Django to fulfill it? -
Django templates rendering issue
I'm new to Django, trying my hand at creating a web app based on the self learn tutorial. i have created a app with name "travello" and project name is "travellproject", in the views i'am trying to render a html page. from django.shortcuts import render from django.http import HttpResponse # Create your views here. def homepage(request): return render(request,'homepage.html') i have created the "templates" directory under travellproj (please refer the directory structure below) also defined DIRS of template variable as below and urls.py as below. "DIRS": [os.path.join(BASE_DIR,'templates')], urlpatterns = [ path("",views.homepage), path("admin/", admin.site.urls), ] But I'm receiving a TemplateDoesNotExist error, please help. Error TemplateDoesNotExist at / homepage.html Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 4.1.5 Exception Type: TemplateDoesNotExist Exception Value: homepage.html Exception Location: C:\Users\Django\first_proj\lib\site-packages\django\template\loader.py, line 19, in get_template Raised during: travello.views.homepage Directory structure: travello |-views.py travellProj |-templates -- > homepage.html |-urls.py |-setting.py -
what is the best way for heavy periodic tasks (django)
i have a django app that has more than 500 tables each table is for a device (each device sends 500 data every day and i store them in database). i should get 10 minutes,hourly,daily,weekly, monthly averages and store them in another table called averages. i don't know what is the best way for these periodic tasks. using django modules like celery-beat or using supervisor of the host? thanks a lot. -
Signin error: Exception Value: Cannot force an update in save() with no primary key
I am using django with mongo db to create a social media website, but I run into the following error while signing in: Environment: Request Method: POST Request URL: http://127.0.0.1:8000/signin Django Version: 3.2.16 Python Version: 3.7.2 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'core'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "/Users/sparshbohra/django-social/venv/lib/python3.7/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/Users/sparshbohra/django-social/venv/lib/python3.7/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/sparshbohra/django-social/django-social-media-website/core/views.py", line 230, in signin login(request, user) File "/Users/sparshbohra/django-social/venv/lib/python3.7/site-packages/django/contrib/auth/__init__.py", line 135, in login user_logged_in.send(sender=user.__class__, request=request, user=user) File "/Users/sparshbohra/django-social/venv/lib/python3.7/site-packages/django/dispatch/dispatcher.py", line 182, in send for receiver in self._live_receivers(sender) File "/Users/sparshbohra/django-social/venv/lib/python3.7/site-packages/django/dispatch/dispatcher.py", line 182, in <listcomp> for receiver in self._live_receivers(sender) File "/Users/sparshbohra/django-social/venv/lib/python3.7/site-packages/django/contrib/auth/models.py", line 22, in update_last_login user.save(update_fields=['last_login']) File "/Users/sparshbohra/django-social/venv/lib/python3.7/site-packages/django/contrib/auth/base_user.py", line 67, in save super().save(*args, **kwargs) File "/Users/sparshbohra/django-social/venv/lib/python3.7/site-packages/django/db/models/base.py", line 740, in save force_update=force_update, update_fields=update_fields) File "/Users/sparshbohra/django-social/venv/lib/python3.7/site-packages/django/db/models/base.py", line 778, in save_base force_update, using, update_fields, File "/Users/sparshbohra/django-social/venv/lib/python3.7/site-packages/django/db/models/base.py", line 841, in _save_table raise ValueError("Cannot force an update in save() with no primary key.") Exception Type: ValueError at /signin Exception Value: Cannot force an update in save() with no primary key. My views.py imports and signin function: from django.shortcuts import render, redirect from django.contrib.auth.models import User, auth from django.contrib.auth … -
Django - Two forms on one page, how can I maintain URL parameters when either form is submitted?
I'm building an application that contains a list of meals, where each meal has various filters, a price, and a rating. The filters are like tags; the user can select multiple, and the page only shows the meals that have the selected filters. The price and ratings are integers, and the user can sort by either price or rating, which sorts the meals (cheapest -> most expensive for price, highest -> lowest for rating). I have built two forms in Django, one for filters and one for sorting, and they both work on their own. However, let's say I submit the sorting form to sort by price; when I do this, it does sort by price, but it removes all of the prior filters I had submitted. Below are the important pieces of code relevant to this problem: views.py def meals(request): meal_list = Meal.objects.all() tags = Tag.objects.all() reviews = Review.objects.all() filter_form = FilterForm(request.GET or None) sorting_form = SortingForm(request.GET or None) sort = "" active_filters = [] if filter_form.is_valid(): tags = filter_form.cleaned_data.get('tags') for tag in tags: meal_list = meal_list.filter(tags__name=tag) active_filters.append(tag) if sorting_form.is_valid(): sort = sorting_form.cleaned_data.get('sort') if sort == "price": meal_list = meal_list.order_by('price') else: meal_list = meal_list.order_by('-rating') paginator = Paginator(meal_list, 8) page_number … -
Cannot reduce "SELECT" queries with "select_related()" and "prefetch_related()" in one-to-one relationship in Django
I have Person and PersonDetail models in one-to-one relationship as shown below: class Person(models.Model): name = models.CharField(max_length=20) def __str__(self): return self.name class PersonDetail(models.Model): person = models.OneToOneField(Person, on_delete=models.CASCADE) # Here age = models.IntegerField() gender = models.CharField(max_length=20) def __str__(self): return str(self.age) + " " + self.gender Then, I have 5 objects for Person and PersonDetail models each: Then, I iterate and call PersonDetail model from Person model as shown below: for obj in Person.objects.all(): print(obj.persondetail) Or, I iterate and call PersonDetail model from Person model with select_related() as shown below: for obj in Person.objects.select_related().all(): print(obj.persondetail) Or, I iterate and call PersonDetail model from Person model with prefetch_related() as shown below: for obj in Person.objects.prefetch_related().all(): print(obj.persondetail) Then, these below are outputted on console: 32 Male 26 Female 18 Male 27 Female 57 Male Then, 5 SELECT queries are run as shown below for all 3 cases of the code above. *I use PostgreSQL and these below are the query logs of PostgreSQL and you can see my answer explaining how to enable and disable the query logs on PostgreSQL: So, I cannot reduce 5 SELECT queries with select_related() and prefetch_related() in one-to-one relationship in Django. So, is it impossible to reduce SELECT queries … -
I am getting a Assertion error in the views of my django project
AssertionError: Expected a Response, HttpResponse or HttpStreamingResponse to be returned from the view, but received a <class 'NoneType'> Code:- from rest_framework.decorators import api_view from user_app.api.serializers import RegistrationSerializer @api_view(['POST',]) def registration_view(request): if request.method == 'POST': serializer = RegistrationSerializer(data=request.data) if serializer.is_valid(): serializer.save() return serializer.data Before it was showing the error: TypeError: User() got unexpected keyword arguments: 'password2' Then I removed the password2 field and I again added it, now it is showing an Assertion Error. -
SystemError: PY_SSIZE_T_CLEAN macro must be defined for '#' formats in django project
I am trying to run the code.But none of the below commands working: python manage.py runserver. pyhton manage.py makemigrations pyhton manage.py showmigrations I am getting below error: I am doing this in ubuntu Traceback (most recent call last): File "/home/zapbuild/ZapbuildProjects/timetracker/timetracker/manage.py", line 21, in <module> main() File "/home/zapbuild/ZapbuildProjects/timetracker/timetracker/manage.py", line 17, in main execute_from_command_line(sys.argv) File "/home/zapbuild/ZapbuildProjects/timetracker/env/lib/python3.10/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/zapbuild/ZapbuildProjects/timetracker/env/lib/python3.10/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/zapbuild/ZapbuildProjects/timetracker/env/lib/python3.10/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/home/zapbuild/ZapbuildProjects/timetracker/env/lib/python3.10/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/home/zapbuild/ZapbuildProjects/timetracker/env/lib/python3.10/site-packages/django/db/migrations/loader.py", line 212, in build_graph self.applied_migrations = recorder.applied_migrations() File "/home/zapbuild/ZapbuildProjects/timetracker/env/lib/python3.10/site-packages/django/db/migrations/recorder.py", line 73, in applied_migrations if self.has_table(): File "/home/zapbuild/ZapbuildProjects/timetracker/env/lib/python3.10/site-packages/django/db/migrations/recorder.py", line 56, in has_table return self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor()) File "/home/zapbuild/ZapbuildProjects/timetracker/env/lib/python3.10/site-packages/django/db/backends/base/base.py", line 256, in cursor return self._cursor() File "/home/zapbuild/ZapbuildProjects/timetracker/env/lib/python3.10/site-packages/django/db/backends/base/base.py", line 233, in _cursor self.ensure_connection() File "/home/zapbuild/ZapbuildProjects/timetracker/env/lib/python3.10/site-packages/django/db/backends/base/base.py", line 217, in ensure_connection self.connect() File "/home/zapbuild/ZapbuildProjects/timetracker/env/lib/python3.10/site-packages/django/db/backends/base/base.py", line 197, in connect self.init_connection_state() File "/home/zapbuild/ZapbuildProjects/timetracker/env/lib/python3.10/site-packages/django/db/backends/mysql/base.py", line 231, in init_connection_state if self.features.is_sql_auto_is_null_enabled: File "/home/zapbuild/ZapbuildProjects/timetracker/env/lib/python3.10/site-packages/django/utils/functional.py", line 80, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/zapbuild/ZapbuildProjects/timetracker/env/lib/python3.10/site-packages/django/db/backends/mysql/features.py", line 82, in is_sql_auto_is_null_enabled cursor.execute('SELECT @@SQL_AUTO_IS_NULL') File "/home/zapbuild/ZapbuildProjects/timetracker/env/lib/python3.10/site-packages/django/db/backends/utils.py", line 99, in execute return super().execute(sql, params) File "/home/zapbuild/ZapbuildProjects/timetracker/env/lib/python3.10/site-packages/django/db/backends/utils.py", line 67, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "/home/zapbuild/ZapbuildProjects/timetracker/env/lib/python3.10/site-packages/MySQLdb/cursors.py", line 312, in _query db.query(q) File "/home/zapbuild/ZapbuildProjects/timetracker/env/lib/python3.10/site-packages/MySQLdb/connections.py", line 224, in query … -
there are "room" is not accessedPylance
It was my views.py codes It was my urls.py codes How i can solve this error. -
Does anyone know where Elastic Beanstalk stores my Django models?
I am creating an app in Django, and I am hosting it on Elastic Beanstalk. I want to know where it stores my models, because I don't know whether Django isn't saving models when I save them from a ModelForm, or if Elastic Beanstalk stores the models somewhere else. This is kind of like an extension to my other problem: 'form.save(commit=True)' not saving to database -
How to send context request in DRF Management Commands without request Object
I stuck now 2 days on this, for cache reasons I store data in memcache - Im collecting data with managemend-commands from django - if I collect data all the urls are relative - for absolute path i need to pass context to serializer - but I dont have this. How can I solve this problem to get the full path? Any Idea? For the public view it works well - but if I develop with localhost then i have troubles with the urls. I tryed fake a request object with requestfactory or testclient but not worked :D -
Wrong value for variable is being given
so I have a problem with some variables, which are coming from an dictionary iteration: for rank in ranked_stats: if rank['queueType'] == "RANKED_FLEX_SR": flex_rank_name = "Ranked Flex" flex_tier = rank["tier"] flex_rank = rank['rank'] totalrank_flex = flex_tier + " " + flex_rank winrate_flex = rank['wins']/(rank['wins']+rank['losses']) winrate_flex *= 100 winrate_flex = "{:.2f}%".format(winrate_flex) wins_flex = rank['wins'] losses_flex = rank['losses'] else: flex_rank_name = "None" flex_tier = "None" flex_rank = "None" totalrank_flex = "None" winrate_flex = "None" wins_flex= "None" losses_flex = "None" for ranksolo in ranked_stats: if ranksolo['queueType'] == "RANKED_SOLO_5x5": solo_rank_name = "Ranked Solo/Duo" solo_tier = ranksolo['tier'] solo_rank = ranksolo['rank'] totalrank_solo = solo_tier + " " + solo_rank winrate_solo = ranksolo['wins']/(ranksolo['wins']+ranksolo['losses']) winrate_solo *= 100 winrate_solo = "{:.2f}%".format(winrate_solo) wins_solo = ranksolo['wins'] losses_solo = ranksolo['losses'] else: solo_rank_name = "None" solo_tier = "None" solo_rank = "None" totalrank_solo = "None" winrate_solo = "None" wins_solo= "None" losses_solo = "None" These are the loops for this dictionary: [{"leagueId": "0b36ed94-33bc-43e3-aa39-3bff2350f76e", "queueType": "RANKED_SOLO_5x5", "tier": "BRONZE", "rank": "II", "summonerId": "___hidden__", "summonerName": "lantern is lava", "leaguePoints": 57, "wins": 8, "losses": 5, "veteran": false, "inactive": false, "freshBlood": false, "hotStreak": false}, {"leagueId": "52002724-73b2-49bc-ad7b-ae58c64f2623", "queueType": "RANKED_FLEX_SR", "tier": "BRONZE", "rank": "II", "summonerId": "__hidden__", "summonerName": "lantern is lava", "leaguePoints": 1, "wins": 5, "losses": 5, "veteran": false, "inactive": false, "freshBlood": false, … -
How to set SSL on another port besides port 80 for react/django/nginx app
Here is my nginx.conf. SSL works on port 80/443, and I can go to the url mynacode.com with https, however I also want to access my backend on port 8000 using secured https connection. How can I do that? Right now, I can access my backend with an insecure connection i.e. http://www.mynacode.com:8000. I would like to use a secured url https://www.mynacode.com:8000 as well. upstream api { server backend:8000; } server { listen 8080; server_name mynacode www.mynacode.com; location /.well-known/acme-challenge/ { root /var/www/certbot; } location / { return 301 https://$host$request_uri; } } server { listen 443 ssl; server_name mynacode www.mynacode.com; ssl_certificate /etc/letsencrypt/live/www.mynacode.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/www.mynacode.com/privkey.pem; include /etc/letsencrypt/options-ssl-nginx.conf; ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; location / { proxy_read_timeout 300s; proxy_connect_timeout 75s; root /var/www/react; try_files $uri /index.html; proxy_set_header Host $host; } location /api/ { proxy_read_timeout 300s; proxy_connect_timeout 75s; proxy_pass http://api; proxy_set_header Host $http_host; } } I've tried searching answers on stackoverflow but have been unsucessful so far. Any help would be appreciated! -
I started a Django course and in that I am using data grip. I am new to this framework and MySQL
When I uploaded the SQL file into data grip it shows me an error. Please refer to the image that you can see the error I tried changing the SQL code in many ways but it didn't work out. please help me.