Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Form wont update home db page. django and python
My django project wont update my home db page with the information from the join.html page. My urls.py file from django.urls import path from . import views urlpatterns = [ path( '' , views.home, name ="home"), path('join',views.join, name ="join"), ] views.py from django.shortcuts import render from .models import PersonInfo from .forms import PersonInfoForm import csv from django.core.files.base import ContentFile from django.core.files.storage import FileSystemStorage #from rest_framework.decorators import action #from rest_framework.response import Response # Create your views here. def home(request): all_members = PersonInfo.objects.all return render(request, 'home.html', {'all':all_members}) def join(request): if request.method == "POST": #console.log("hello") #if "submitButton" in request.POST: form = PersonInfoForm(request.POST or None) if form.is_valid(): form.save() return render(request, 'join.html', {}) else: return render(request, 'join.html', {}) forms.py from django import forms from .models import PersonInfo class PersonInfoForm(forms.ModelForm): class Meta: model = PersonInfo fields = ['customerName','address','age','email','accountId'] models.py from django.db import models from django.utils.translation import gettext # Create your models here. class PersonInfo(models.Model): accountId = models.IntegerField(default=None) customerName = models.CharField(max_length = 50, default=None ) address = models.CharField(max_length = 50, default=None) email = models.EmailField(max_length = 200, default=None) age = models.IntegerField(max_length = 3, default=None) def __str__(self): return self.customerName + ' ' #return self.accountId class book(models.Model): accountId = models.IntegerField( ("Account_ID") ) customerName = models.CharField( ("Customer_Name"), max_length = 50, default=None … -
How to prevent the creation of same object using Faker?
I have the following factory: class MonthFactory(factory.django.DjangoModelFactory): class Meta: model = Month year = factory.Faker("random_int", min=2014, max=2022) month = factory.Faker("random_int", min=1, max=12) Both year and month are unique in my Django class: class Meta: unique_together = ( "month", "year", ) When I want to create two objects for a test, let's say: month1 = MonthFactory() month2 = MonthFactory() sometimes I hit the jackpot and get: django.db.utils.IntegrityError: duplicate key value violates unique constraint because Faker got the same month and year for both objects. Is there a way to prevent this? -
Microsoft Access design View in django
How can I create one model that can takes all these models to look exactly like Microsoft Access Design View? I want to put these model into a one called TablesDesign so that it would enable user to design how their data could be stored in the application, is there anyone who can help? class Numbers(models.Model): num = models.IntegerField() class Characters(models.Model): char = models.CharField(max_length=1000) class Check(models.Model): check = models.BooleanField() class Date(models.Model): date = models.DateField() class LargeNumber(models.Model): larger_num = models.DecimalField(max_digits=30 decimal_places=15) class TablesDesign(model.Models): """" I want to put all these models into the TablesDesign to create something similar to Microsoft Access Design View. -
Django: Use Proxy Models and lost history
i implement two proxy models from a main model to use them in different ModelAdmins with different get_queryset´s. ALl is running fine. But i lost the change history of the object if it switches between the main model to the proxy model. Is there a solution for that ? -
why pipenv install gives me Package installation failed... error
i want to run django app so whenever i run pipenv install to install all the packages from my pipfile it gives me this error note : -i'm running on windows -cmake did nothing -it doesn't change anything if pipenv shell is opened or closed -i tried to delete pipenv manually and reinstall -i tried to install and update wheel and thank you in advance Installing dependencies from Pipfile.lock (631114)... An error occurred while installing boto3==1.26.86 --hash=sha256:7e8fc7bfef6481e48380d13e18a0a036413d126dc7eda37eadc1a052a3426323 --hash=sha256:e981703b76d2fb9274ce5cdda6ea382e29c9e7c65bc400c94c0a259b26f8914a! Will try again. An error occurred while installing botocore==1.29.86 ; python_version >= '3.7' --hash=sha256:8a4afc6d540c01890e434b9a31fb1b17f8c759001e12c7ad7c49f55ea5805993 --hash=sha256:6083c649791559dd916c9ff7ac62486b391f6f9464d3cf6964582a489c866b11! Will try again. An error occurred while installing charset-normalizer==3.1.0 ; python_full_version >= '3.7.0' --hash=sha256:4155b51ae05ed47199dc5b2a4e62abccb274cee6b01da5b895099b61b1982974 --hash=sha256:322102cdf1ab682ecc7d9b1c5eed4ec59657a65e1c146a0da342b78f4112db23 --hash=sha256:e89df2958e5159b811af9ff0f92614dabf4ff617c03a4c1c6ff53bf1c399e0e1 --hash=sha256:73dc03a6a7e30b7edc5b01b601e53e7fc924b04e1835e8e407c12c037e81adbd --hash=sha256:7381c66e0561c5757ffe616af869b916c8b4e42b367ab29fedc98481d1e74e14 --hash=sha256:34e0a2f9c370eb95597aae63bf85eb5e96826d81e3dcf88b8886012906f509b5 --hash=sha256:74db0052d985cf37fa111828d0dd230776ac99c740e1a758ad99094be4f1803d --hash=sha256:891cf9b48776b5c61c700b55a598621fdb7b1e301a550365571e9624f270c203 --hash=sha256:e1b25e3ad6c909f398df8921780d6a3d120d8c09466720226fc621605b6f92b1 --hash=sha256:fca62a8301b605b954ad2e9c3666f9d97f63872aa4efcae5492baca2056b74ab --hash=sha256:c36bcbc0d5174a80d6cccf43a0ecaca44e81d25be4b7f90f0ed7bcfbb5a00909 --hash=sha256:6734e606355834f13445b6adc38b53c0fd45f1a56a9ba06c2058f86893ae8017 --hash=sha256:3573d376454d956553c356df45bb824262c397c6e26ce43e8203c4c540ee0acb --hash=sha256:20064ead0717cf9a73a6d1e779b23d149b53daf971169289ed2ed43a71e8d3b0 --hash=sha256:78cacd03e79d009d95635e7d6ff12c21eb89b894c354bd2b2ed0b4763373693b --hash=sha256:9a3267620866c9d17b959a84dd0bd2d45719b817245e49371ead79ed4f710d19 --hash=sha256:d2686f91611f9e17f4548dbf050e75b079bbc2a82be565832bc8ea9047b61c8c --hash=sha256:d7fc3fca01da18fbabe4625d64bb612b533533ed10045a2ac3dd194bfa656b60 --hash=sha256:de5695a6f1d8340b12a5d6d4484290ee74d61e467c39ff03b39e30df62cf83a0 --hash=sha256:830d2948a5ec37c386d3170c483063798d7879037492540f10a475e3fd6f244b --hash=sha256:1435ae15108b1cb6fffbcea2af3d468683b7afed0169ad718451f8db5d1aff6f --hash=sha256:ea9f9c6034ea2d93d9147818f17c2a0860d41b71c38b9ce4d55f21b6f9165a11 --hash=sha256:75f2568b4189dda1c567339b48cba4ac7384accb9c2a7ed655cd86b04055c795 --hash=sha256:6f6c7a8a57e9405cad7485f4c9d3172ae486cfef1344b5ddd8e5239582d7355e --hash=sha256:22908891a380d50738e1f978667536f6c6b526a2064156203d418f4856d6e86a --hash=sha256:dd5653e67b149503c68c4018bf07e42eeed6b4e956b24c00ccdf93ac79cdff84 --hash=sha256:ac3775e3311661d4adace3697a52ac0bab17edd166087d493b52d4f4f553f9f0 --hash=sha256:628c985afb2c7d27a4800bfb609e03985aaecb42f955049957814e0491d4006d --hash=sha256:a04f86f41a8916fe45ac5024ec477f41f886b3c435da2d4e3d2709b22ab02af1 --hash=sha256:04afa6387e2b282cf78ff3dbce20f0cc071c12dc8f685bd40960cc68644cfea6 --hash=sha256:12d1a39aa6b8c6f6248bb54550efcc1c38ce0d8096a146638fd4738e42284448 --hash=sha256:3160a0fd9754aab7d47f95a6b63ab355388d890163eb03b2d2b87ab0a30cfa59 --hash=sha256:3d9098b479e78c85080c98e1e35ff40b4a31d8953102bb0fd7d1b6f8a2111a3d --hash=sha256:0be65ccf618c1e7ac9b849c315cc2e8a8751d9cfdaa43027d4f6624bd587ab7e --hash=sha256:ac0aa6cd53ab9a31d397f8303f92c42f534693528fafbdb997c82bae6e477ad9 --hash=sha256:b116502087ce8a6b7a5f1814568ccbd0e9f6cfd99948aa59b0e241dc57cf739f --hash=sha256:10c93628d7497c81686e8e5e557aafa78f230cd9e77dd0c40032ef90c18f2230! Will try again. An error occurred while installing colorama==0.4.6 ; platform_system == 'Windows' --hash=sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6 --hash=sha256:08695f5cb7ed6e0531a20572697297273c47b8cae5a63ffc6d6ed5c201be6e44! Will try again. An error occurred while installing django==4.2b1 --hash=sha256:33e3b3b80924dae3e6d4b5e697eaee724d5a35c1a430df44b1d72c802657992f --hash=sha256:9bf13063a882a9b0f7028c4cdc32ea36fe104491cd7720859117990933f9c589! Will try again. An error occurred while installing django-admin==2.0.2 --hash=sha256:a92f9fb21f63edabb5db9030f36b62c6c16a0187183e7e7de4142aee4472b70f --hash=sha256:43c9f94ca5ad498789c0282691931c609c8e26db61aeb49ae8ad90d15b80cb75! Will try again. An error occurred while installing django-excel-response2==3.0.5 --hash=sha256:ba908be16decbdc97b998bd20e596c27da78d23f97b533853c778c8c9c0974e3 --hash=sha256:4bbdd374cadd2d85723d5cd4b49822301141f7e4fef69616639cf3b7535e9ea5! Will try again. An error occurred while installing django-six==1.0.5 … -
Django: How to make model for list of string as one-to-many relation?
I have data like so: [ { "name": "Alice", "hobbies": ["programming", "swimming"] }, { "name": "Bob", "hobbies": ["sleeping", "skiing", "skating"] } ] I want to be able to use hobbies for later filtering, so I would like to have separate Hobby model with many-to-one relation to the Person model. What is a good practice to do so? Is there any simple way how to save person and hobbies at once (for example using singular serializer) and/or use serializer to retrieve data in the simmilar fashion as the input? -
Switched from WSGI to ASGI for Django Channels and now CircleCI throws "corrupted double-linked list" even though tests pass
I've been working on a project which requires WebSockets. The platform is built with Django and was running the WSGI server gunicorn. We decided to implement WebSockets using Django Channels. I set everything up including switching from gunicorn to the ASGI server daphne. Everything works great in local development environment. Deployment to AWS is working and everything works great on dev/staging. pytest works and all tests pass locally. On CircleCI all the tests are passing, but at the end of the "test" step we get the following and CircleCI shows a failed status: ================== 955 passed, 2 skipped in 216.09s (0:03:36) ================== corrupted double-linked list /bin/bash: line 2: 278 Aborted (core dumped) poetry run coverage run -m pytest $TESTFILES -vv --junitxml htmlcov/junit.xml Exited with code exit status 134 CircleCI received exit code 134 There are no other errors, warnings, or unexpected output. I cannot replicate the issue outside of CircleCI. I tried adding the @pytest.mark.asyncio decorator to the one async test we have and still got the above. Even when I totally remove said test CircleCI still throws the same. Google has not been helpful. Edit: This same thing has also happened a couple of times during the "migrate" step … -
Python Django: Inline edit and sub-total automatic
I have a simple application for forecasting hours in projects for team members. The 'view' mode: For the "edit" mode I have this interface: Instead of a new view/template for "edit" I would like to have inline edit functionality. Is that feasible with Python Dango only as I don't want to use jquery or JavaScript. Similarly, can the sub-total be calculated automatically on the page just using Python Django? -
Using shell_plus doesn't import models with the same name
Let's say we have app1 and app2 that both have models MyModel. When using the console, I've noticed that app1's MyModel is the only one that is imported: python manage.py tenant_command shell_plus The above command only imports the first MyModel, and I'm assuming it doesn't do the second since there's already a MyModel imported. Is there anyway to deal with the above? Thanks I've tried to use import as but that doesn't seem to work and causes issues in a larger codebase. I can get around this by manually importing the model, but that will overwrite the one that's already imported within shell_plus -
Nginx no such file or directory unix:/run/gunicorn.sock
Разворачиваю Django на сервере. Использую Nginx и gunicorn. После настройки, получаю ошибку 502 от Nginx. В логах запись о том, что не найден файл unix:/run/gunicorn.sock, хотя файл существует и gunicorn запущен Логи Nginx (https://i.stack.imgur.com/Ru8xK.jpg) Конфиг Nginx (https://i.stack.imgur.com/VlBiD.png) Настройки Gunicorn (https://i.stack.imgur.com/CT5XP.png) Статус Gunicorn (https://i.stack.imgur.com/lj4tS.png) -
Django - New object is not created if html action argument is provided
I have simple contact form: <form method="post"> {% csrf_token %} {{ form_email.as_div }} {{ form_message.as_div }} <button name="submit">Send</button> </form> When text is provided in both fields (email and message) and then the user click on submit button, the data should be saved in data base. View function: def index(request): """The home page.""" # Send a message. if request.method != 'POST': # No data submitted; create a blank form. form_email = EmailForm() form_message = EmailMessageForm() else: # POST data submitted; proecess data. form_email = EmailForm(data=request.POST) form_message = EmailMessageForm(data=request.POST) if form_email.is_valid() and form_message.is_valid(): form_email.save() email = Email.objects.last() message = form_message.save(commit=False) message.email = email message.save() # Display a blank or invalid form. context = {'form_email': form_email, 'form_message': form_message} return render(request, 'home/index.html', context) Until now everything works as expected, but when I add action argument in order to redirect the user to the 'Thank you' page if form has been sent, the data is not saved. <form action="{% url 'home:contact_thank_you' %}" method="post"> {% csrf_token %} {{ form_email.as_div }} {{ form_message.as_div }} <button name="submit">Send</button> </form> Do you have any idea why the data is not saved when I add the action argument? -
How to filter ManyToMany fields using django-filter
How can I filter a ManyToMany field with django-filter I would like to display an input field on a template where you can filter Student to get these results: all of the Students that speak English (Student.languages contains 'English') all of the Students that speak English and German (Student.languages contains 'English' and 'German') # models.py class Student(models.Model): name = models.CharField(...) languages = models.ManyToManyField(Language) class Language(models.Model): language = models.CharField(...) # English / German / ... level = models.CharField(...) # B1 / B2 / C1 / ... #filters.py import django_filters as filters from .models import Employee class EmployeeFilter(filters.FilterSet): class Meta: model = Employee fields = ['name', 'languages'] How should I modify the EmployeeFilter to make it ready to filter the Students according to their spoken languages? I tried declaring a class variable named languages like so: class EmployeeFilter(filters.FilterSet): languages = filters.ModelChoiceFilter( queryset = Languages.objects.all() ) class Meta: model = Employee fields = ['name', 'languages'] but it did not work, the filter had no effect. Thanks for your help, it is well appreciated! -
subprocess.PIPE not working in django model
So I have this model in which there is isRunning property. When it is set to True it spawns a subprocessing instance and saves it to subprocessObject . It looks like this. class Monitor(models.Model): Name = models.CharField(max_length=143) # Some other stuff CommandToExecute = models.CharField(max_length=1000, default="python -c print('HelloWorld')") subprocessObject = None @property def isRunning(self): return False @isRunning.getter def isRunning(self): if self.subprocessObject is None or self.subprocessObject.poll() is None: return False return True @isRunning.setter def isRunning(self, value): if value is True and self.isRunning is False: self.subprocessObject = subprocess.Popen(self.CommandToExecute.split(" "), stdout=sys.stdout, stdin=sys.stdin, shell=True) elif value is False and self.isRunning is None: self.subprocessObject.stdin.close() self.subprocessObject.stdout.close() self.subprocessObject.terminate() self.subprocessObject == None def __str__(self): return self.Name For now I have a simple file that prints something each second with flush=True. The problem is that there is an error looking like this: OSError: [Errno 22] Invalid argument Exception ignored in: <_io.TextIOWrapper name='<stdout>' mode='w' encoding='cp1252'> OSError: [Errno 22] Invalid argument When I changed subprocess.PIPE to sys.stdout and when I started the subprocess in a view it worked as expected so it's probably problem with subprocess.PIPE in models? Should I start the process in a view or is there an solution? -
Django Form auto submit when user open page
I have different forms on my template. Each of these forms are displayed against specific venues for which rules/ conditions are set. The submission of the form results in a set of points being added. The rule I am struggling with relates to the following situation: If a user opens a page of a venue_1 and if venue_1 has a rule that considers that +1 is added when the page is open; then +1 point is added to the user point count on page load. It seems in order to achieve this I need to use some JavaScript. As this is a recurring question on this forum I tried the different solutions offered but cannot seem to make it work. I must be missing something. models.py class Venue(models.Model, HitCountMixin): name = models.CharField(verbose_name="Name",max_length=100, blank=True) class VenueLoyaltyPointRule(models.Model): venue = models.ForeignKey(Venue, null = True, blank= True, on_delete=models.CASCADE) points = models.IntegerField(verbose_name="loylaty_points_rule", null = True, blank=True) auto_submit = models.BooleanField(default=False) timestamp = models.DateTimeField(auto_now_add=True) views.py def venue_loyalty_add_point_rule(request,userprofile_id): url = request.META.get('HTTP_REFERER') venue = UserProfile.objects.filter(user=request.user).values('venue') venue_loyalty_point_rule = get_object_or_404(VenueLoyaltyPointRule, venue=request.user.userprofile.venue) submitted = False if request.method == "POST": form = LoyaltyCardForm(request.POST) if form.is_valid(): data = form.save(commit=False) data.add_points = venue_loyalty_point_rule.points data.user_id = userprofile_id data.venue_id = venue data.save() form.save() messages.success(request, 'Points added!') return … -
ProgrammingError: column ... must appear in the GROUP BY clause or be used in an aggregate function
Django's documentation mentions aggregation: pubs = Publisher.objects.annotate(num_books=Count('book')) My code is full of similar constructs (adding a count of something to a queryset, using annotate), and this always worked well. Now suddenly, for reasons unknown, I'm getting this error: ProgrammingError: column ... must appear in the GROUP BY clause or be used in an aggregate function In fact, I have the same version of Django on my dev and prod, and everything works on dev, but fails on prod (typical). Spontaneously. For no apparent reason. And I cannot add the named column to the GROUP BY clause, because then it wants me to add the next column, and the next, and the next, etc. I can also not add some random aggregate function. In short: the solutions that the error mentions make no sense! There are many more questions with this same error, many unanswered. I have no solution, but it seems this error started appearing lately, in Django versions 4+, at least for me. I've tried the failing SQL query directly within Postgres and it fails there as well, of course, with exactly the same error. The fault is not with Django. The only way to make this annotate query … -
Stop logging parameters for django background tasks?
I'm using Django Background Tasks in my app for a task that requires user authentication. To create the task, I use a command like: my_cool_task(pks, request.POST.get('username'), request.POST.get('password')) I just realized that the username and password parameters are getting stored in the Django Admin tables for the tasks, which in this case creates a security issue. Is there a way to not store these parameters? Or is there a better way to authenticate a process that will take longer than it takes for a server timeout error? -
error : django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured
django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. When I run the testapscheduler.py file, I get the above error. Is it because I only run one file in the Dajngo frame that I get the above error? How can I test it? testapscheduler.py: import logging from models import Todo from apscheduler.schedulers.background import BackgroundScheduler from datetime import datetime, timedelta import pytz import requests def notify_todo(): # 現在の日時を取得 now = datetime.now(pytz.timezone('Asia/Tokyo')) # 締め切りが30分以内のTODOリストを取得 todos = Todo.objects.filter( deadline__gt=now - timedelta(minutes=30), deadline__lt=now + timedelta(minutes=30), ttime__isnull=False, ttime__gt=now.time() ) # 30分以内のTODOリストの数を出力 # ログの出力名を設定 logger = logging.getLogger('mylog') #ログレベルを設定 logger.setLevel(logging.DEBUG) #ログをコンソール出力するための設定 sh = logging.StreamHandler() logger.addHandler(sh) logger.debug(f'{len(todos)}個のTODOリストが締め切り30分以内にあります。') for todo in todos: #LINE NotifyのAPIトークンを取得 api_token = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' # 通知メッセージの作成 message = f"【{todo.title}】\n締切時間:{todo.deadline.strftime('%Y/%m/%d %H:%M')}\n詳細:{todo.description}" # LINE Notifyに通知を送信 headers = {'Authorization': f'Bearer {api_token}'} payload = {'message': message} requests.post('https://notify-api.line.me/api/notify', headers=headers, data=payload) def start(): scheduler =BackgroundScheduler(timezone='Asia/Tokyo') scheduler.add_job(notify_todo, 'interval', seconds=2) # 2秒ごとに実行 scheduler.start() models.py from django.db import models class Todo(models.Model): title = models.CharField("タスク名", max_length=30) description = models.TextField("詳細", blank=True) deadline = models.DateField("締切") ttime = models.TimeField("") def __str__(self): return self.title -
I am working on django website for a restaurent ,in order to display every day's menu on my homepage what should I do
How to handle the django articles in order to display the menu of restaurent on my website's homepage every day? How can I add and update menu on homepage? I tried to add a modal based menu pop ups when admin logins but didn't worked -
ModuleNotFoundError: No module named 'bootstrap5'
i have installed boostrap 5 and wrote it down on installed apps and this error keeps popping up i´ve tried everything, unisntalling and installing, writing this: python3 -m pip install django-bootstrap5, and nothing works -
How to return object insted of id's, and auto create foreingKey object (get python with django)
I'm creating a simple rest api This is my actual result from devices [ { "id_device": "a099d2ce-812b-4d85-8c8b-cfe71057fbe7", "name": "Interruptor 4", "identifier": "teste1", "group": "39407ef6-1a3e-4965-9b61-96f6c40b76b3", "options": [ "1b383a37-5229-4ae0-9649-f76aa32eeda0", "4ff5406a-8c7b-4517-9ec0-14fd4f68f30b", "a541216d-f509-4461-85ca-444491ac9217", "3debe828-edd6-4d83-bfd8-2776a1594380" ] }, { "id_device": "dc9f672f-6759-4b1f-ac65-e3d78e09833d", "name": "teste", "identifier": "teste", "group": "39407ef6-1a3e-4965-9b61-96f6c40b76b3", "options": [ "a76c54cf-b11a-4a5e-986b-3e38a86568cd", "ef736b76-4bac-42f1-9393-c01e18787108", "84e6c598-072f-4bb8-90e9-34019547534f" ] } ] my models.py from uuid import uuid4 from django.db import models class Options(models.Model): id_option = models.UUIDField(primary_key=True, default=uuid4, editable=False) name = models.CharField(max_length=255) identifier = models.CharField(max_length=255) class Meta: ordering = ['name'] def __str__(self): return self.name class Groups(models.Model): id_group = models.UUIDField(primary_key=True, default=uuid4, editable=False) name = models.CharField(max_length=255) class Meta: ordering = ['name'] def __str__(self): return self.name class Devices(models.Model): id_device = models.UUIDField(primary_key=True, default=uuid4, editable=False) name = models.CharField(max_length=255) identifier = models.CharField(max_length=255) options = models.ManyToManyField(Options) group = models.ForeignKey(Groups, on_delete=models.CASCADE, default="") viewsets from rest_framework import viewsets from devices.api import serializers from devices import models class DevicesViewsets(viewsets.ModelViewSet): serializer_class = serializers.DevicesSerializer queryset = models.Devices.objects.all() class OptionsViewsets(viewsets.ModelViewSet): serializer_class = serializers.OptionsSerializer queryset = models.Options.objects.all() class GroupsViewsets(viewsets.ModelViewSet): serializer_class = serializers.GroupsSerializer queryset = models.Groups.objects.all() serializers from rest_framework import serializers from devices import models class DevicesSerializer(serializers.ModelSerializer): class Meta: model = models.Devices fields = '__all__' class OptionsSerializer(serializers.ModelSerializer): class Meta: model = models.Options fields = '__all__' class GroupsSerializer(serializers.ModelSerializer): class Meta: model = models.Groups fields = '__all__' I try some … -
I'm looking for an Available/unavailable/maybe Available date picker html
I'm looking to create a date picker in django html where the user can use a traffic light system to update a calendar saying if they are available (green) unavailable (amber) not available (red). The user would them submit the answers to update a data base. Lots of date pickers only have the available/unavailable. I can't see options for the 'maybe available'. Any ideas where to start. -
What is the business logic/rule of this function in views.py?
I am working on learning management system and got a piece of code from a source. This function is in my views.py file. It adds a semester. But I'm not clear about the business rules of this function. Means why I'm not able to mark more then one semester as is_current_semester. Please help me to get the basic idea behind the working of this code. Thank you @login_required @lecturer_required def semester_update_view(request, pk): semester = Semester.objects.get(pk=pk) if request.method == 'POST': if request.POST.get('is_current_semester') == 'True': # returns string of 'True' if the user selected yes for 'is current semester' unset_semester = Semester.objects.get(is_current_semester=True) unset_semester.is_current_semester = False unset_semester.save() unset_session = Session.objects.get(is_current_session=True) unset_session.is_current_session = False unset_session.save() new_session = request.POST.get('session') form = SemesterForm(request.POST, instance=semester) if form.is_valid(): set_session = Session.objects.get(pk=new_session) set_session.is_current_session = True set_session.save() form.save() messages.success(request, 'Semester updated successfully !') return redirect('semester_list') else: form = SemesterForm(request.POST, instance=semester) if form.is_valid(): form.save() return redirect('semester_list') else: form = SemesterForm(instance=semester) return render(request, 'app/semester_update.html', {'form': form}) -
How do I Access fields from one table through another table in Django
Please how do I link and access the fields: 'location' and 'building_type' from Property table in Client table. (I want to be able to get the 'location' and 'building_type' information for Client table from Property table ) class Property(models.Model): location = models.CharField(choices=Property_Location, max_length=120) building_type= models.CharField(choices=Property_Type, max_length=120) class Client(models.Model): first_name = models.CharField(max_length=120) last_name = models.CharField(max_length=120) phone = models.IntegerField() location=() building_type =() I tried using PK & related_name for both, but it ended up showing me just the details of 'location' for both the location and building_type fields -
Django Runserver Error: django.db.utils.OperationalError: (2003, "Can't connect to MySQL server on '127.0.0.1:3306' (111)")
I have checked the answers to these questions and many others but my problem isn't still solved yet: django.db.utils.OperationalError: (2003, "Can't connect to MySQL server on '127.0.0.1' (111)" mysql.connector.errors.InterfaceError: 2003: Can't connect to MySQL server on '127.0.0.1:3306' (111 Connection refused) I got a new system (Windows,same as the old one) and installed Ubuntu 22.04 and install Django and other dependencies, including pipenv to manage the packages. In my old system, the project was in a Dropbox folder and I have navigated to it in the new system, but when I run python manage.py runserver I get ...lib/python3.10/site-packages/MySQLdb/connections.py", line 185, in __init__ super().__init__(*args, **kwargs2) django.db.utils.OperationalError: (2003, "Can't connect to MySQL server on '127.0.0.1:3306' (111)") My database setting is also okay and MySQL80 is running when I checked Windows Services DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'my_db', 'USER': 'root', 'PASSWORD': 'my_password', 'HOST': '127.0.0.1', 'PORT': '3306', } } Meanwhile, the old system works just fine. -
How to avoid redirect after like in Django?
I've created likes logic by sending a post request to the specific url. Disadvantage of this method is that I can't avoid redirect. Even HTTPresponseRedirect to the current page is frustrating for user, cause it bangs viewport to the start of the page. I don't understand ajax, but wouldn't mind to use java script if needed. Most likely solution is to create it in Django somehow, but I think it might be impossible. So, any solutions are welcome!