Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Celery Beat Periodic Tasks Running Twice
I trying to send scheduled emails to users but my Django celery periodic tasks running 2 times within a half-hour span. Every day I scheduled my email task at 7.00 AM but it is running 1st task at 7.00 AM and the same task is running at 7.30 AM also. Here is my celery app # coding=utf-8 from __future__ import absolute_import import os from celery import Celery from django.conf import settings os.environ.setdefault("DJANGO_SETTINGS_MODULE", "app_name.settings") app = Celery("app_name") app.config_from_object("app_name.celeryconfig") app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) @app.task(bind=True) def debug_task(self): print ("Request: {0!r}".format(self.request)) Celery app config # coding=utf-8 import os PROJECT_APP_PATH = os.path.dirname(os.path.abspath(__file__)) # Celery Config BROKER_URL = 'redis://redis_server:6379' CELERY_RESULT_BACKEND = 'redis://redis_server:6379' CELERY_TASK_SERIALIZER = 'json' CELERY_ACCEPT_CONTENT = ['application/json'] # Ignore other content CELERY_RESULT_SERIALIZER = 'json' CELERY_ENABLE_UTC = True CELERY_TASK_RESULT_EXPIRES = 0 # Never expire task results CELERY_IGNORE_RESULT = True CELERY_TRACK_STARTED = True CELERY_IMPORTS = ( "module.tasks" ) Periodic Tasks scheduled in Django admin panel Functionality working fine but these tasks are running twice daily for 2 to 3 days and after that, it will run once but if I restart celery then It will start running tasks again twice for some days. Please let me know If I'm missing in celery configuration. -
How can I connect the mayanedms api to my django project?
I would like to connect MayanEdms api to my Django project. Note that mayan is running on different port from my Django container (both are running Docker). The problem I'm having is because, if I navigate to the api link, it works for me, but if I do it through code it doesn't. I don't know why that is? I attach below the error that I get both in the browser and in the command console. I also attach the function that should connect to the API. What I want this function to do is to list all the documents that arrive to my email (it is read with MayanEdms). Once the documents are saved in Mayan, I want to show the information of the emails, including the attached files, in the independent interface that I have made with django. views.py: @login_required def f_facturaspendientes(request): # URL de tu API externa que proporciona las facturas pendientes api_url = 'http://127.0.0.1/api/v4/documents/' # Datos de autenticación auth = ('admin', 'jehK4XvBGp') # Realiza una solicitud GET a la API con autenticación response = requests.get(api_url, auth=auth) # Verifica si la solicitud fue exitosa if response.status_code == 200: data = response.json() # Convierte la respuesta JSON en … -
How to write unit tests with django-tenants and django-graphene to test graphql APIs?
i have written below code following the django-tenants documentation but it is not working and i am getting the error. I know i am not the first one doing this will appreciate any kind of lead..Thanks! I have added the following code which is very simple in use case in which we create organization and that's it import string, random from django_tenants.test.cases import TenantTestCase from django_tenants.test.client import TenantClient from app.tenant.models import Organization, Domain from ..utility import utils, constants def generate_token(user): # sourcery skip: inline-immediately-returned-variable """ this function generates a token for the user :param user: :return: token generated """ from strobes.app.serializers import TwoFactorAuthenticationSerializer t = TwoFactorAuthenticationSerializer() return t.get_token(user).access_token class TenantGraphQLTestCase(TenantTestCase): def setUp(self): alphabet = string.ascii_lowercase random_name = ''.join(random.choice(alphabet) for _ in range(10)) self.user = utils.generate_fake_superuser() self.tenant = Organization.objects.create(name="Clear Org",industry="Dummy",referer="Direct",employee_size=100,strobes_customer=True) domain = Domain() domain.tenant = self.tenant domain.domain = "client.co" domain.save() self.authentication_headers = { "HTTP_AUTHORIZATION": f"JWT {generate_token(self.user)}", "Content-Type": "application/json", } def tearDown(self): # Delete tenant and domain self.tenant.delete() self.domain.delete() def test_tenant_clients_query(self): client = TenantClient(self.tenant, **self.authentication_headers) response = client.post('/graphql/', {'query': '{ clients { name } }'}) self.assertEqual(response.status_code, 200) self.assertEqual(response.json()['data']['clients'][0]['name'], 'make') error i am getting: Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/django_tenants/test/cases.py", line 38, in setUpClass cls.tenant.save(verbosity=cls.get_verbosity()) File "/usr/local/lib/python3.8/site-packages/django_tenants/models.py", line 107, in save super().save(*args, … -
Django return render/httpresponse and Json into a single Jsonresponse
I'm new to Django and try to understand how to return 2 different kind of response type inside one return Jsonresponse : view.py def article_filter_mobile(request): # Here I'm trying to get the total records number of my DB number_of_rec = Record.objects.count() # Need to access {{number_of_rec}} in test.html count = render(request, 'test.html', {'number_of_rec': number_of_rec}) # here I'm listing all datas of my DB data = dict() locations = Record.objects.raw("SELECT * FROM myDb") available_lessons = [model_to_dict(l) for l in locations] # Need to access {{available_lessons|safe}} in a JS script inside grid_mobile.html data['html_table'] = render_to_string('grid_mobile.html', {'available_lessons': available_lessons},request=request) # I think my problem is here as data and count are not in the same format return JsonResponse(data,count) Can someone help me to understand what is wrong in this code ? Thanks -
Page not found (404) No comments found matching the query
views,py: class CommentCreateView(LoginRequiredMixin, CreateView): model = Comments fields = ['content'] template_name = 'blog/comment_create.html' def form_valid(self, form): form.instance.post_id = self.kwargs['pk'] form.instance.author = self.request.user messages.success(self.request, 'You have made a comment') return super().form_valid(form) class CommentUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = Comments fields = ['content'] template_name = 'blog/comment_update.html' def test_func(self): comment = self.get_object() if self.request.user == comment.author: return True else: return False def form_valid(self, form): messages.success(self.request, 'You have updated the post') return super().form_valid(form) urls.py: from django.contrib import admin from django.urls import path from blog.views import home, about, PostListView, PostDetailView, PostCreateView, PostUpdateView, PostDeleteView, CommentCreateView, CommentUpdateView urlpatterns = [ # path('', home, name='blog_home'), path('', PostListView.as_view(), name='blog_home'), path('post/<int:pk>', PostDetailView.as_view(), name='post_detail'), path('post/<int:pk>/update', PostUpdateView.as_view(), name='post_update'), path('post/<int:pk>/delete', PostDeleteView.as_view(), name='post_delete'), path('post/create/', PostCreateView.as_view(), name='post_create'), path('post/<int:pk>/create_comment/', CommentCreateView.as_view(), name='comment_create'), path('post/<int:pk>/update_comment/<int:comment_id>', CommentUpdateView.as_view(), name='comment_update'), path('about/', about, name='blog_about'), ] models.py: class Comments(models.Model): content = models.CharField(max_length=100) date_posted = models.DateTimeField(auto_now_add=True) author = models.ForeignKey(to=User, on_delete=models.CASCADE) post = models.ForeignKey(to=Post, related_name='comments',on_delete=models.CASCADE) def __str__(self): return f'Comment by {self.author} for {self.post.title}' def get_absolute_url(self): return reverse('post_detail', kwargs={'pk': self.post.pk}) that is fom post template: {% for comment in post.comments.all %} <article class="media content-section"> <div class="small text-muted">Comment by {{ comment.author }}</div> <a href="{% url 'comment_update' pk=object.pk comment_id=comment.pk %}">{{ comment.content }}</a> <div class="small text-muted"> Posted on {{ comment.date_posted }}</div> </article> {% endfor %} that is an error: enter image … -
Django: convert dropdowns created with Html pages in Django forms (project already working)
I have a small fully functional project where there are 3 dropdowns, however created with manual Html pages. I'm a beginner and I realized that it's better to use the classic Django Forms (and not create dropdowns manually with html pages). Can you show me how I can convert this little project to Django forms? Thank you **CODE PYTHON ** models.py from django.db import models class Country(models.Model): name = models.CharField(max_length=40) def __str__(self): return self.name class City(models.Model): country = models.ForeignKey(Country, on_delete=models.CASCADE) name = models.CharField(max_length=40) def __str__(self): return self.name class FullRecord(models.Model): country = models.ForeignKey(Country, on_delete=models.CASCADE) city_departure = models.ForeignKey(City, on_delete=models.CASCADE, related_name="city_departure") city_destination = models.ForeignKey(City, on_delete=models.CASCADE, related_name="city_destination") @property def departure_destination(self): return f"{self.city_departure}-{self.city_destination}" def __str__(self): return self.country.name views.py **from django.shortcuts import render from .models import FullRecord, Country def trip_selector(request): if "Hx-Request" in request.headers: trips = FullRecord.objects.none() if request.headers["Hx-Trigger"] == "id_trip": country_id = request.GET.get("country") if country_id != "": trips = FullRecord.objects.filter(country_id=country_id) return render(request, "trips.html", {"trips": trips}) elif request.headers["Hx-Trigger"] == "id_extract_single_city": selected_trip = request.GET.get("trips") extracted_cities = [] if selected_trip != "": trip = FullRecord.objects.get(id=int(selected_trip)) trip_with_combined_names = trip.departure_destination split_trip = trip_with_combined_names.split("-") extracted_cities = split_trip return render(request, "extract_single_city.html", {"options": extracted_cities}) else: countries = Country.objects.all() return render(request, "form.html", {"countries": countries})** urls.py **from django.urls import path from . import views urlpatterns … -
Creating a Custom Choices Field in Django Model
I'm working on a Django project and need to implement a charfield field "Custom" in the dropdown menu in the UserProfile model. The requirements are as follows: Users should be able to select their gender from predefined options (Male or Female). Additionally, there should be an option to select "Custom" if the user's gender is not represented by the predefined options. If a user selects "Custom," a text field should appear, allowing them to enter their gender description. I've already created the UserProfile model with predefined gender choices, but I'm not sure how to dynamically show or hide the text field based on the user's selection of "Custom." Note: I want this to be done in both Django Admin and DRF API. Feature should look like this: a screenshot of a custom field taken from Instagram Here's my UserProfile model: class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) FEMALE = 'FEMALE' MALE = 'MALE' CUSTOM = 'CUSTOM' NONE = 'NONE' GENDER = [ (FEMALE, "Female"), (MALE, "Male"), (CUSTOM, "Custom"), (NONE, "Prefer not to say"), ] gender = models.CharField( max_length=20, choices=GENDER, default=NONE, ) custom_gender = models.CharField( max_length=255, blank=True, # Allow it to be optional null=True, # Allow it to be null ) … -
Importing data from MYSQL to Django
I using the inspectdb in Django because im trying to get the data from my localhost(MYSQL) now if i add or edit a data into my Mysql does also update automatically the changes into my django? or any reccomendation would really appreciate. #newbie I tried the InspectDb and i thought if i made changes into Mysql the django also update -
No such column: 'wagtailcore_page.latest_revision_id' post upgrade from wagtail 3 to wagtail 4.2.4
I have recently upgraded my Wagtail version from v3 to v4.2.4 In this upgrade, the wagtailcore_page creates a new column latest_revision_id through one of its migrations under the library. When I am trying to run my test cases, it is giving me an error with this column saying that it does not exist. During deployment too I faced the same issue but running migrations in a specific order worked and issue was resolved. During test cases, the internal test database is newly created and looks for that column before the migration that creates the column runs due to which this issue arise. Please find below screenshot for reference. screenshot -
How do I pass the current logged in user to a field in a django and another model via an automic transaction?
I have a model form and can fulfill this requirement by setting the form field equal to request.user in the form view. My problem is I need to create whats basically a join table during the form save and can't figure out how to get the request.user to the form field then do a final validation and form save in the view. I'm pretty new to django and web dev in general. Any help is greatly appreciated. class LocationCreateForm(forms.ModelForm): class Meta: model = Organization fields = ("name", "email", "address", "addressline2", "city", "state", "about", "payment") def __init__(self, *args, **kwargs): self.user = kwargs.pop('user', None) super(LocationCreateForm, self).__init__(*args, **kwargs) @transaction.atomic def save(self): data = super().save(commit=False) if self.user is not None: data.created_by = self.user data.save() OrganizationTeam.objects.create( organization=data, practitioner=self.user, is_admin=True, ) return data HttpResponse("Didn't work.") -
Django+Html: Convert a working project from manual html forms to Django forms
In this 100% fully functional project, i would like to replace the manually created html forms with the classic Django forms. Can you show me how I can convert this little project to Django forms? Thank you **CODE PYTHON ** models.py from django.db import models class Country(models.Model): name = models.CharField(max_length=40) def __str__(self): return self.name class City(models.Model): country = models.ForeignKey(Country, on_delete=models.CASCADE) name = models.CharField(max_length=40) def __str__(self): return self.name class FullRecord(models.Model): country = models.ForeignKey(Country, on_delete=models.CASCADE) city_departure = models.ForeignKey(City, on_delete=models.CASCADE, related_name="city_departure") city_destination = models.ForeignKey(City, on_delete=models.CASCADE, related_name="city_destination") @property def departure_destination(self): return f"{self.city_departure}-{self.city_destination}" def __str__(self): return self.country.name views.py **from django.shortcuts import render from .models import FullRecord, Country def trip_selector(request): if "Hx-Request" in request.headers: trips = FullRecord.objects.none() if request.headers["Hx-Trigger"] == "id_trip": country_id = request.GET.get("country") if country_id != "": trips = FullRecord.objects.filter(country_id=country_id) return render(request, "trips.html", {"trips": trips}) elif request.headers["Hx-Trigger"] == "id_extract_single_city": selected_trip = request.GET.get("trips") extracted_cities = [] if selected_trip != "": trip = FullRecord.objects.get(id=int(selected_trip)) trip_with_combined_names = trip.departure_destination split_trip = trip_with_combined_names.split("-") extracted_cities = split_trip return render(request, "extract_single_city.html", {"options": extracted_cities}) else: countries = Country.objects.all() return render(request, "form.html", {"countries": countries})** urls.py **from django.urls import path from . import views urlpatterns = [ path("", views.trip_selector, name="trips") ]** admin.py from django.contrib import admin # Register your models here. from .models import Country, … -
Django - How to delete an object from a button in a table
Objective: I want to delete an object from a table using a button in Django, but it's not working as expected. I've provided relevant parts of my code below. Can someone please guide me on what to add to urls.py and views.py to make this work? Database Attributes: _id: ObjectId response: string contact_id: string status: string views.py: def delete(request, id): try: excel_data = get_object_or_404(ExcelData, id=id) excel_data.delete() return redirect('web_services_app:tables') except ExcelData.DoesNotExist: # Handle the case where the object doesn't exist return HttpResponse("The object you're trying to delete doesn't exist.") **urls.py:** path('delete/<int:id>/', views.delete, name='delete'), **HTML Table in tables.html:** <div class="table-responsive"> <table class="table table-striped" id="data-table"> <thead> <tr> <th scope="col" style="font-weight: bold; color: black;">Response</th> <th scope="col" style="font-weight: bold; color: black;">Contact ID</th> <th scope="col" style="font-weight: bold; color: black;">Status</th> <th scope="col" style="font-weight: bold; color: black;">Actions</th> </tr> </thead> <tbody> {% for data in excel_data %} <tr class="table-row"> <td class="table-data">{{ data.response }}</td> <td class="table-data">{{ data.contact_id }}</td> <td class="table-data">{{ data.status }}</td> <td> <a class="btn btn-danger" href="/web_services_app/delete/{{ data.id }}">Delete</a> </td> </tr> {% endfor %} </tbody> </table> </div> I appreciate any help you can provide. Thank you! ❤️ -
Django and react images don't appear with media folder
I use django rest framework and react where I am trying to show a user's profile picture by fetching them with axios in react. settings.py STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'frontend/build/static') ] MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'frontend/build/static/media') When I save a user's profile picture from admin panel the image is added in media folder. React is inside django. I use build in react and the structure looks like this. build static media images src public In the django rest framework page the image looks like this /media/images/Photo.jpg The problem is that even when I open the image from the admin panel it doesn't show and instead shows this Also in the frontend it doesn't appear. const profiles = friends.map(friend => { return ( <> <img src={friend.profile.profile_pic} /> </> ) }) -
How to update where the files are stored in Django app
I have a Django app that contains multiple models with FileField. I am saving by default every file directly in the Media folder. But as the app grew larger also Media folder became bigger. Now my idea is to move the files into separate folders split by models. So I am wondering what is the best practice when it comes to this? Shall I move the files to separate folders, then manually update every file location in the Database and then update Filefield path for every model? Or is there better approach? -
How to trigger a file download on click using Django and Javascript
I'm trying to produce a file download on click using Django and Javascript. I've nearly figured it out but I'm confused as to how to prevent Django from automaticall downloading the file once processing is complete. Here is my code: views.py: def translateFile(request) : if request.method == 'POST': source_language = request.POST.get('source_language') target_language = request.POST.get('target_language') form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): uploaded_file = request.FILES['file'] fs = FileSystemStorage() filename = fs.save(uploaded_file.name, uploaded_file) uploaded_file_path = fs.path(filename) file = (converter(uploaded_file_path, source_language, target_language))#translates file file_location = uploaded_file_path with open(file_location, 'rb') as f: file_data = f.read() response = HttpResponse(file_data, content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="' + filename + '"' return response Javascript: const formData = new FormData(form); const xhr = new XMLHttpRequest(); xhr.open('POST', form.getAttribute('action'), true); xhr.onreadystatechange = function () { console.log("Ready state: ", xhr.readyState); console.log("Status: ", xhr.status); if (xhr.readyState === XMLHttpRequest.DONE) { if (xhr.status === 200) { loaderDiv.style.display = 'none'; const downloadArrowDiv = document.querySelector('#download-btn'); downloadArrowDiv.style.display = 'flex'; const responseText = document.querySelector('#response_text') responseText.textContent = 'Click to download' // File was successfully translated, you can update UI here const downloadLink = document.querySelector('#response_text_anchor'); downloadLink.href = URL.createObjectURL(xhr.response); downloadLink.download = formData.get('file').name; downloadLink.click(); } else { // Handle error case console.error('Error translating file'); } } }; xhr.responseType = 'blob'; xhr.send(formData); }); HTML: <button … -
Django Heroku deployment errors
I am trying to deploy a web application and came across this issue where it says that it could not build wheels for myproject and that the runner is empty. I am just confused because I did not name it myproject on Heroku or VSCode. Is there something I might have done that made it register in this way? Regardless, I am trying to get over this roadblock so i can deploy it. remote: Building wheel for myapp (setup.py): finished with status 'done' remote: Created wheel for myapp: filename=myapp-0.1.dev0-py3-none-any.whl size=1166 sha256=ec655f854ab6a2c0ba6b36dda552a60e1b54af84d93a82785eda9229258b686c remote: Stored in directory: /tmp/pip-ephem-wheel-cache-7q7p2y16/wheels/8b/36/8b/cb810ee2b64417af5f91d361665839bd04414f112ecafcb1e0 remote: Building wheel for myproject (setup.py): started remote: Building wheel for myproject (setup.py): finished with status 'error' remote: error: subprocess-exited-with-error remote: remote: × python setup.py bdist_wheel did not run successfully. remote: │ exit code: 1 remote: ╰─> [3 lines of output] remote: warning: build_scripts: runner is an empty file (skipping) remote: remote: error: [Errno 2] No such file or directory: 'build/scripts-3.9/runner' remote: [end of output] remote: remote: note: This error originates from a subprocess, and is likely not a problem with pip. remote: ERROR: Failed building wheel for myproject remote: Running setup.py clean for myproject remote: Building wheel for mysqlclient (setup.py): started remote: Building … -
Why/when does Django makemigrations ignore a field and then do an Add field or Alter
This is the order Django created the migration - Create model MedicalTest - Create model MedicalTestGroup - Add field test_group to medicaltest - Alter unique_together for medicaltest (1 constraint(s)) This is the order I was expecting - Create model MedicalTestGroup - Create model MedicalTest Under what circumstances would it do what I am expecting? Why does it only get some of the ordering wrong some of the time? I understand and acknowledge that the outcome of both may be the same. I am asking what might cause Django to treat the order of one model differently from another because I'd like to get it right in my own code. -
Displaying HTML Body of an email
I am building a website using Python Django and would like to display emails. The emails are processed in the backend and are retrieved by ajax in JSON format. How can I safely display the html body of an email without destroying my main theme? I thought of implementing the email with iframes <iframe sandbox=""> . Are there other (better) ways to implement the html body without running into danger to compromise my website? -
whitenoise dosen't seem to work in Django
I want to check my web app in DEBUG = False and use whitenoise to do the static stuff. I have followed documentation and different blog post, I have also used the tool before, but this time it just does not work. Things I've tried: reinstalling whitenoise changing the location of whitenoise middleware collected statics many times and also changed its name restart the local web server settings.py: DEBUG = False ALLOWED_HOSTS = ['*'] 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', 'whitenoise.middleware.WhiteNoiseMiddleware', ] MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') STATIC_URL = '/static/' STATIC_ROOT = BASE_DIR / "static" urls.py: urlpatterns = [ path('', include('bella_beauty_shop_web_store.urls')), path('123321/', admin.site.urls), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) and here you can see that I have collected statics: Errors: When I put the DEBUG to FALSE, there is an error in the console: I really don't know what's wrong here. I am quit new to Django, but I have built some web apps and also used whitenoise before. As you know, I expect my html to render with style when the DEBUG is set to FALSE using whitenoise. -
Set API Data(JSON) Dynamically in Database views.py in Django using model when NUmber of columns of each tables are different
Set API Data(JSON) Dynamically in Database views.py in Django using model when NUmber of columns of each tables are different. I mean i am sending data from desktop software to web using api... in web I am getting that json data using request , Now i have alot of model classes that have different number of columns , i have tried alot of things but in knownledge nothing seem to be working ... I can add the data statically but would take alot of time to write the code, i have list of table_names so, Is there any way that code will automatically read the json data. Fetch Rows and columns from it and than add the numbers of rows to database . and vice versa -
DJANGO count number of records with raw MYSQL query and use result in html template
I'm trying to get the total number of records of my database using raw Mysql query and render it in a html template with something like {{ number_of_rec }} So far I have tried : view.py def number_of_rec(request): locate = Record.objects.raw("SELECT count(*) FROM mydb ") number_of_rec = len(locate.fetchall) return render(request, 'test.html', {'number_of_rec': number_of_rec}) But it's not working as {{ number_of_rec }} in the template html return nothing. I also tried number_of_rec = len(locate.fetchall)[0] but no changes. What am I doing wrong ? -
django database sqlite3 "no such a column" error
time to time i am facing "no such a column" error during django backend, django-admin development. when i face this issue, i cannot solve it. so that; i detele db.sqllite3 database file in my project location. i delete migrations files in application folder /djangioapp/migrations/ i run makemigrations, migrate and createsuperuser commands. i face with this error when i make changes on my Model. even more, i updated my model, i run makemigrations and migrate commands and i got this error no such a column when i try to access /admin in my djnago project. actually, after making migrations with makemigrations and migrate; i see the changes in 0001_initial.py file but it does not apply in database. is there any practical solution for "no such a column" error? i face with this error when i make changes on my Model. even more, i updated my model, i run makemigrations and migrate commands and i got this error no such a column when i try to access /admin in my djnago project. actually, after making migrations with makemigrations and migrate; i see the changes in 0001_initial.py file but it does not apply in database. -
Django keeps running migrations without changes made
I am creating a custom model field. It basically a one-level dictionary field which allows you to store model-subfields in a JSON manner in the database so fields which wont be queried upon will not take up an extra column. The issue is, whenever I predefine the default value for the field, the migrations keep thinking there's changes in the default values, and thus makes a new migration. The default values don't change across migration files, but maybe I am missing something about Django's internals. The custom field: class JSONStructField(models.JSONField): def __init__(self, fields=None, fieldrows=None, *args, **kwargs): self.fields = self.process_fields(fields) if fields else None self.fieldrows = self.process_fieldrows(fieldrows) if fieldrows else None kwargs["default"] = self.generate_default super().__init__(*args, **kwargs) @staticmethod def process_fields(fields): return [FieldType(**field[2]) if isinstance(field, tuple) else field for field in fields] @staticmethod def process_fieldrows(fieldrows): return [ [FieldType(**field[2]) if isinstance(field, tuple) else field for field in row] for row in fieldrows ] def generate_default(self): default = {} if self.fields: for field in self.fields: default[field.name] = field.default elif self.fieldrows: for row in self.fieldrows: for field in row: default[field.name] = field.default else: default = None return default def formfield(self, **kwargs): return super().formfield(**{ "widget": JsonInputWidget(fields=self.fields, fieldrows=self.fieldrows), **kwargs }) def deconstruct(self): name, path, args, kwargs = super().deconstruct() … -
Django: websockets for dynamic updates in real time to a django template (only this way, no Ajax etc.)
Can you please help me with dynamic update in template. I've found a lot of tutorials, but all of them are so different. It would be better to get an advice for my specific situation. So, that's the part of my template: <th scope="row"> <div class="player-date" data-toggle="modal" data-target="#playerDataEditModal"> <h2><i class="fa fa-bolt" aria-hidden="true"></i> <span class='total'>{{player.leavel.first.leavel|add:player.power.first.power}}</span></h2> <p><i class="fa fa-line-chart" aria-hidden="true"></i> <span class='level'>{{player.get_leavel}}</span> / <i class="fa fa-gavel" aria-hidden="true"></i> <span class='power'>{{player.get_power}}</span></p> </div> </th> I gotta dynamically change the class="total" tag. So what do I need to do that? I can't even decide what library to install, because they are different in these tutorials (django-channels, channels, channels[redis], channel-layers etc.). -
How can I return different field foreign key for two models related it
I want to retrieve the field full name for the field author in book creation, and the nickname to retrieve in article creation. models.py : class Author(models.Model): full_name = models.CharField( verbose_name="First Name", null=False, blank=False, max_length=20, ) nick_name = models.CharField( verbose_name="Nick Name", null=False, blank=False, max_length=20, ) def __str__(self): return f"{self.full_name}" class Book(models.Model): author = models.ForeignKey( Author, on_delete=models.PROTECT, related_name="book_author", null=False, blank=False, ) class Article(models.Model): author = models.ForeignKey( Author, on_delete=models.PROTECT, related_name="article_author", null=False, blank=False, ) How can I do it?