Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
JS fetch doesn't exclude from Cart via DRF API
Models: class AbstractProductContainer(AbstractContainer): """ Abstract container for products. """ products = models.ManyToManyField('Product') def toggle(self, product): if self.products.all().contains(product): self.products.remove(product) return False else: self.products.add(product) return True class Cart(AbstractProductContainer): """ Product container for purchasing products. """ pass class Account(AbstractBaseUser, PermissionsMixin): favourite = models.OneToOneField( Favourite, verbose_name=("Favourite products"), on_delete=models.CASCADE, unique=True, default=Favourite.get_new, ) cart = models.OneToOneField( Cart, verbose_name=("Product cart"), on_delete=models.CASCADE, unique=True, default=Cart.get_new, ) DRF Views class ProductViewSet(viewsets.ModelViewSet): serializer_class = serializers.ProductSerializer queryset = Product.objects.filter(sellable=True) @action(methods=['post', 'put', 'delete'], detail=True, permission_classes=[permissions.IsAuthenticated], url_path='toggle-cart', url_name='toggle_cart') def toggle_cart(self, request, *args, **kwargs): product = self.get_object() request.user.cart.toggle(product) return Response() API Test class ProductViewSetTest(TestCase): def testToggle(self): c = self.client u = Account.objects.all()[0] c.login(username="testUser A", password="testPassword123") p = Product.objects.all()[0] url = reverse('api:product-toggle_cart', None, [p.pk]) resp = c.post(url, secure=False) self.assertEqual(resp.status_code, 200, f'Error code: {resp.status_code}') self.assertTrue(u.cart.products.all().contains(p), f"Cart contains: {u.cart.products.all()}, must cantain Product A") resp = c.post(url, secure=False) self.assertFalse(u.cart.products.all().contains(p), f"Cart contains: {u.cart.products.all()}, must be empty") JS Function const removeFromContainer = async btn => { let csrf = new DOMParser().parseFromString(`{% csrf_token %}`, 'text/html').querySelector('input').value; let id = btn.parentElement.parentElement.querySelector('input[name="id"]').value; await fetch(`/api/product/${id}/toggle-cart/`, { method: "PUT", headers: { 'X-CSRFToken': csrf} }) // You are not interested in this part let span = document.querySelector('.in-container span'); span.textContent = Number(span.textContent) - 1; span = document.querySelector('.total span'), span.textContent = (Number(span.textContent) - Number(btn.parentElement.parentElement.querySelector('.price').textContent)).toFixed(2); btn.parentElement.parentElement.remove(); } Product model doesn't matter, … -
Problems with mod-wsgi Windows
I'm new IT and programming; I been struggling to install mod_wsgi with pip Example in cmd: pip install mod_wsgi I'm using Apcache 24 and my PC is windows 10, 64bits My python is 3.7.9 and Django is 3.2.16 Error : Building wheels for collected packages: mod-wsgi Building wheel for mod-wsgi (setup.py) ... error error: subprocess-exited-with-error × python setup.py bdist_wheel did not run successfully. │ exit code: 1 ╰─> [24 lines of output] running bdist_wheel running build running build_py creating build creating build\lib.win-amd64-3.7 creating build\lib.win-amd64-3.7\mod_wsgi copying src\__init__.py -> build\lib.win-amd64-3.7\mod_wsgi creating build\lib.win-amd64-3.7\mod_wsgi\server copying src\server\apxs_config.py -> build\lib.win-amd64-3.7\mod_wsgi\server copying src\server\environ.py -> build\lib.win-amd64-3.7\mod_wsgi\server copying src\server\__init__.py -> build\lib.win-amd64-3.7\mod_wsgi\server creating build\lib.win-amd64-3.7\mod_wsgi\server\management copying src\server\management\__init__.py -> build\lib.win-amd64-3.7\mod_wsgi\server\management creating build\lib.win-amd64-3.7\mod_wsgi\server\management\commands copying src\server\management\commands\runmodwsgi.py -> build\lib.win-amd64-3.7\mod_wsgi\server\management\commands copying src\server\management\commands\__init__.py -> build\lib.win-amd64-3.7\mod_wsgi\server\management\commands creating build\lib.win-amd64-3.7\mod_wsgi\docs copying docs\_build\html\__init__.py -> build\lib.win-amd64-3.7\mod_wsgi\docs creating build\lib.win-amd64-3.7\mod_wsgi\images copying images\__init__.py -> build\lib.win-amd64-3.7\mod_wsgi\images copying images\snake-whiskey.jpg -> build\lib.win-amd64-3.7\mod_wsgi\images running build_ext building 'mod_wsgi.server.mod_wsgi' extension error: [WinError 2] El sistema no puede encontrar el archivo especificado [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. ERROR: Failed building wheel for mod-wsgi Running setup.py clean for mod-wsgi Failed to build mod-wsgi Installing collected packages: mod-wsgi Running setup.py install for mod-wsgi ... error error: subprocess-exited-with-error In advance thank you … -
Replace labels in networkx graph according to translation given by list of tuples
I have a MultiDiGraph, G with the following edges: [('SP', 'LU', 0), ('SP', 'KI', 0), ('LU', 'PC', 0), ('LU', 'LR', 0), ('LU', 'LR', 1), ('PC', 'LI', 0), ('PC', 'HT', 0), ('PC', 'HT', 1), ('LI', 'TE', 0), ('TE', 'GB', 0), ('TE', 'BL', 0), ('GB', 'LR', 0), ('GB', 'ST', 0), ('LR', 'KI', 0), ('LR', 'SP', 0), ('LR', 'PC', 0), ('KI', 'HT', 0), ('KI', 'PC', 0), ('HT', 'SI', 0), ('HT', 'LU', 0), ('HT', 'LU', 1), ('SI', 'BL', 0), ('SI', 'LI', 0), ('BL', 'ST', 0), ('BL', 'TE', 0), ('ST', 'SP', 0)] I would like to translate the labels according to this list of tuples, replacing all LU with 肺 etc. [('LU', '肺', 'Lung'), ('LI', '大腸', 'Large Intestine'), ('ST', '胃', 'Stomach'), ('SP', '脾', 'Spleen'), ('HT', '心', 'Heart'), ('SI', '小腸', 'Small Intestine'), ('BL', '膀胱', 'Bladder'), ('KI', '腎', 'Kidney'), ('PC', '心包', 'Pericardium'), ('TE', '三焦', 'Triple Energizer'), ('GB', '膽', 'Gallbladder'), ('LR', '肝', 'Liver')] A simple function like this converts the list of tuples to what I want: def translate_labels(G): """Translate labels from standard ID to Chinese.""" edges = G.edges convert = [('LU', '肺', 'Lung'), ('LI', '大腸', 'Large Intestine'), ('ST', '胃', 'Stomach'), ('SP', '脾', 'Spleen'), ('HT', '心', 'Heart'), ('SI', '小腸', 'Small Intestine'), ('BL', '膀胱', 'Bladder'), ('KI', '腎', 'Kidney'), ('PC', … -
Multiselect Dropdown List With Checkboxes – multiselect.js how to set placeholder
I am using multiselect.js/css from https://www.cssscript.com/multiselect-dropdown-list-checkboxes-multiselect-js/#google_vignette and creating one select dropdown for Categories. <select name="categoryFilter" id="categoryFilter" aria-label="Category" required multiple > {% for category in categories %} <option value="{{category.id}}">{{ category }}</option> {% endfor %} </select> my JQuery code : document.multiselect('#categoryFilter') .setCheckBoxClick("checkboxAll", function(target, args) { console.log("Checkbox 'Select All' was clicked and got value ", args.checked); }) .setCheckBoxClick("1", function(target, args) { console.log("Checkbox for item with value '1' was clicked and got value ", args.checked); }); document.multiselect('#categoryFilter', { texts: { placeholder: 'Select options', } }); I am not able to set placeholder for my Category option. please suggest where I am wrong. -
Unable to create new objects of a model after referencing a field on another model as FK - django
I have overrided django auth model to a custom one, where I declare the USERNAME_FIELD as phone_number. OTPLog model is intended to keep a log record of the messages sent to the clients. To remove duplication of keeping phone numbers in db, I referenced the phone_number field in OTPLog to phone_number field in User as FK. class User(AbstractUser): phone_number = models.CharField( unique=True, max_length=11, validators=[RegexValidator(regex=consts.PHONE_REGEX_PATTERN)] ) USERNAME_FIELD = 'phone_number' class OTPLog(models.Model): created_at = models.DateTimeField(auto_now_add=True) expiry_date = models.DateTimeField(default=default_otp_duration) phone_number = models.ForeignKey(settings.AUTH_USER_MODEL, to_field='phone_number', on_delete=models.DO_NOTHING, db_index=True) Now making an object of OTPLog with phone_number is not possible any more, as the following exception is risen: otplog = OTPLog.objects.create(phone_number='01145279126') will give ValueError: Cannot assign "'01145279126'": "OTPLog.phone_number" must be a "User" instance. After making an object of User and calling otplog = OTPLog.objects.create(phone_number=user) the object is created successfully, but that is not the way I expect it work. I would simply need a FK constraint, where if a user with a given phone_number does not exist, the otplog object could not be created. How would I resolve the issue? -
Bad Gateway error when using Google Cloud Speech API in a Django application that is running on nginx and waitress
I've been working on a Django project using Google's speech-to-text api. It works fine on my local as well as a standalone application. However, when I deploy it to the production that has nginx working with waitress, it doesn't work and gives Bad Gateway error and the nginx server stops running. This is where it happens. from google.cloud import speech_v1 .... .... client = speech_v1.SpeechClient() Here is my nginx-waitress configuration: #Finally, send all non-media requests to the Django server. location / { proxy_pass http://localhost:8080; #proxy_set_header Host $host; #proxy_set_header X-Forwarded-For $remote_addr; } I tried with that $host and $remote_addr lines, still no luck. Here is the credentials json file that is working fine in both local django server and standalone application. { "type": "service_account", "project_id": "my_project_id", "private_key_id": "my_private_key_id", "private_key": "my_private_key", "client_email": "my_client_email", "client_id": "my_client_id", "auth_uri": "https://accounts.google.com/o/oauth2/auth", "token_uri": "https://oauth2.googleapis.com/token", "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs", "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/speechtoblog-service%40yt2blog-377413.iam.gserviceaccount.com" } Is there any other configurations that I need to do in the nginx server side? I would highly appreciate your help. -
Django Tailwind theme refresh - won't load
I have successfully installed [django tailwind][1] on my project. The problem is with the preview. As the installation guide advised, i tried 'python manage.py tailwind start', but the usual port http://127.0.0.1/ says: This site can’t be reached. If I start with my usual command of 'python manage.py runserver 127.0.0.1:8080', I can see the site and the new css, but it does not reload the page with reload-worker.js If I try to reload the browser with the button, it just goes into a spinning icon in the tab, never reloads and i have to restart the browser and also the server. So i can't really see the css changes, which is very annoying. What am i missing here? Reload listener seems to be working: HTTP GET /static/django-browser-reload/reload-listener.js 200 [0.01, 127.0.0.1:52032] HTTP GET /static/css/dist/styles.css 200 [0.01, 127.0.0.1:52031] HTTP GET /static/django-browser-reload/reload-worker.js 200 [0.00, 127.0.0.1:52031] -
How make a superuser after signup a user?
This is my model and I just want to All Publisher users become superuser too, but I don't know How to do it?? class User(AbstractUser): email = models.EmailField() is_publisher = models.BooleanField(default=False) and This is my View def signup(response): form = SignUpForm() if response.method == "POST": form = SignUpForm(response.POST) if form.is_valid(): form.save() return redirect("/home") else: form = SignUpForm() return render(response, "registration/signup.html", {"form":form}) -
Django Token on test case return an error 'Authentication credentials were not provided'
I'm loggin inside the TestCase, creating another superuser for the test, but wen i send the token generated for this user, every call I send return me the error: {'detail': ErrorDetail(string='Authentication credentials were not provided.', code='not_authenticated')} I printed my headers: {'Authorization': 'Token 5e4bd809ef42a4f17043a73eec10692382cd78d9'} test.py class CreditCardTestCase(APITestCase): def setUp(self): self.user = User.objects.create_superuser(username='test.case', email='test.case@gmail.com', password='123456') if self.user is not None: try: self.token = Token.objects.get(user=self.user) except: self.token = Token.objects.create(user=self.user) self.headers = {'Authorization': 'Token ' + self.token.key} def test_credit_card_with_invalid_number(self): print(self.headers) response = self.client.put('/api/v1/credit-card', { 'exp_date': '02/2028', 'holder': 'Olivia Johnson', 'number': '1234567891231234', 'cvv': '999' }, **self.headers) print(response.data) self.assertDictEqual({ 'message': 'Invalid Credit Card Number' }, response.data) view.py class CreditCardView(APIView): authentication_classes = [TokenAuthentication] permission_classes = [IsAuthenticated] def get(self, request, key): credit_card = CreditCardModel.objects.get(pk=key) serializer = CreditCardSerializer(credit_card) private_key = read_keys('private') serializer_data = serializer.data serializer_data['number'] = decrypt_credit_card_number( private_key, credit_card.number) return Response({ 'credit_card': serializer_data }, status=HTTP_200_OK) def put(self, request): try: params = request.data credit_card = CreditCard(params['number']) response = basic_info_verifier(params, credit_card) brand_obj = CreditCardBrand.objects.get( description__icontains=response['brand']) public_key = read_keys('public') print(public_key) encrypted_number = encrypt_credit_card_number( public_key, params['number']) credit_card = CreditCardModel( exp_date=response['expiration_date'], holder=params['holder'], number=encrypted_number, cvv=params['cvv'] if params['cvv'] else '', brand=brand_obj ) credit_card.save() return Response({ 'message': 'Credit card registered with success', 'card_id': credit_card.id }, status=HTTP_201_CREATED) except BrandNotFound: return Response({ 'message': 'Brand Not Found' }, status=HTTP_400_BAD_REQUEST) except … -
Slice on the queryset argument of a Django Prefetch object and got "Cannot filter a query once a slice has been taken."
I did a slice on the queryset argument of a Django Prefetch object and got "Cannot filter a query once a slice has been taken." from django.db.models import Prefetch queryset = SomeModel.objects.filter(some_field=some_value).order_by('id')[:5] prefetch_obj = Prefetch('related_field', queryset=queryset) some_queryset.prefetch_related(prefetch_obj) Is there any way to slice only the first 5 query sets to be cached by prefetch? -
Find all broken foreign key and m2m relationships in a Django app?
I've got a sqlite data dump for a django app where some models have been redacted. How can I find all the models that have broken FK and M2M relationships* in the app ? *I'm happy I can generate placeholder data for everything that is missing - this is so I can write a script to make sure I'm not missing some field. -
Doesn't transfer a string to django?
return HttpResponse(f'{product}'.replace('\n', '')) does not wrap a string. what could this be about and how to fix it here's what I wanted to get into the product I have several data but all the data I have is not transferred -
Create a normal Django Model, View, Serializer within a wagtail app
We currently have a wagtail app that acts like a CMS as it should, but we recently had a requirement that requires us to create a model view and serializer that should not be seen through wagtail admin page. I've gone through and created a model from within one of our apps in django (not from home apps that is default created by wagtail). class MasterClass(models.Model): topic = models.CharField(max_length=255) <<redacted>> and it doesnt seem to be detected by django when doing make migrations. is there any additional config to make this work? -
How to run command directly on local machine drive
My intention is to write data directly on the disk from where I run the docker command and not into the container disk. Any ideas how to do this ? I tried this: docker exec -it app bash -c "python manage.py dumpdata > data.json" but the data is saved inside container. -
In django, bulk_create with update_conflicts=True doesn't work if I have multiple UniqueConstraints
Let's say I have this model: class XYZ(Model): id = models.BigAutoField(primary_key=True) keys_1 = models.IntegerField() keys_2 = models.JSONField(null=False, default=dict) keys_3 = models.DateField(null=True, default=None) values = models.JSONField(null=False, default=dict) class Meta: db_table = "xyz" constraints = [ models.UniqueConstraint( fields=["keys_1", "keys_2"], name="unicity_when_keys_3_null", condition=Q(keys_3__isnull=True), ), models.UniqueConstraint( fields=["keys_1", "keys_2", "keys_3"], name="unicity", ), ] I then do this: XYZ.objects.bulk_create( data, update_conflicts=True, unique_fields=["keys_1", "keys_2", "keys_3"], update_fields=["values"], ) with data being a list of XYZ objects If data[n].keys_3 is not None, it works as expected If data[n].keys_3 is None, it fails on conflict, citing the unicity constraint Am I doing something wrong ? PS: these can't be used btw XYZ.objects.bulk_create( data, update_conflicts=True, unique_fields=["keys_1", "keys_2"], update_fields=["values"], ) XYZ.objects.bulk_create( data, update_conflicts=True, unique_fields=["keys_1", "keys_2"], update_fields=["values", "keys_3"], ) -
Consuming messages from Kafka with different group IDs using confluent_kafka
I am using python and confluent_kafka I am building a Queue Management for Kafka where we can view the pending(uncommitted) messages of each topic, delete topic and purge topic. I am facing the following problems. I am using same group ID for all the consumers so that I can get the uncommitted messages. I have 2 consumers one (say consumer1) consuming and committing and another one (say consumer2) just consuming without committing. If I run consumer1 and consumer2 simultaneously only one consumer will start consuming and another just keep on waiting and hence cause heavy loading time in the frontend. If I assign different group Id for each it works but, the messages committed by consumer1 are still readable by consumer2. Example: If I have pushed 100 messages and say consumer1 consumed 80 messages and when I try to consume from consumer2 it should consume only remaining 20, but it is consuming all 100 including the messages committed by consumer1. How can I avoid that or solve? -
Django 'QuerySet' object has no attribute 'startswith'
I'm new to Django and I created function to allow admin to create users accounts. I used a password generator + make_password() function to hash the password. Now it's sending the plain password to users email and storing it in the database hashed, I used check_password() to compare but I'm getting this error: 'QuerySet' object has no attribute 'startswith' def user_login(request): if request.method == "POST": user_email = request.POST['user_email'] user_password = request.POST['user_password'] user_details = User.objects.filter(user_email=user_email).values() hashed_pw = User.objects.filter(user_password=user_password).values() check_password(user_password, hashed_pw) if user_details: request.session['logged_in'] = True request.session['user_email'] = user_details[0]["user_email"] request.session['u_id'] = user_details[0]["user_email"] request.session['user_name'] = user_details[0]["user_name"] request.session['u_type'] = "emp" return HttpResponseRedirect('/user_index') else: return render(request, 'EmpLogin.html', {'msg': "0"}) else: return render(request, 'EmpLogin.html') -
Is there any way to roll back execution of delete method with ldap3
I'm using Django 4.1 and ldap3 to connect directory service using ldap. Is there any way to roll back execution of delete method? the sample code likes below: # import class and constants from ldap3 import Server, Connection, ALL # define the server s = Server('servername', get_info=ALL) # define an unsecure LDAP server, requesting info on DSE and schema # define the connection c = Connection(s, user='user_dn', password='user_password') # perform the Delete operation c.delete('cn=user1,ou=users,o=company') #some checks here #if condition: # user1.recover() after some checking, I want to recover user's data based on a condition. Thanks! I've searched about rollback delete execution, but did not find any solution. -
Clean up unused database tables after removing a Django app?
When I remove a Django app from my list of INSTALLED_APPS, it doesn't get rid of the old database tables; running ./manage.py makemigrations doesn't detect any changes. Apart from going into the database myself and dropping the old tables, is there a better way to clean up unused tables after uninstalling an app from my Django project? -
Display data by date, when data comes from multiple models in Django
I'm currently working on an app with Django 4.1. I try to display a resume of some data comming from the database. Here is a simplified example of my models: class Signal(models.Model): data1 = models.CharField() data2 = models.CharField() date = models.DateTimeField() class Ban(models.Model): data3 = models.CharField() data4 = models.CharField() date = models.DateTimeField() What I'm trying to do is getting filtered data from these 2 models, and make a list ordered by date from all this data to display it. someting like: Ban1 (08/03/2023) Ban2 (07/03/2023) Signal2 (06/03/2023) Ban3 (05/03/2023) Signal1 (04/03/2023) Thanks in advance for your ideas -
Django I want to make comments on category posts
I want to make comments on posts. I found a lot of monual, but it either does not fit or does not work. I need to create a separate comment view function and display the comment form in a template. I don't understand how to make a separate comment function and display it in the post template. Need a simple, elegant solution to the problem. class season(models.Model): slug = models.SlugField(max_length=266, unique=True, db_index=True, verbose_name=('SLUG')) ... def __str__(self): return self.slug def get_absolute_url(self): return reverse('seasonpost', kwargs={'seasonpost_slug': self.slug, 'episodepost_slug': self.slug}) class episode(models.Model): slug = models.SlugField(max_length=266, unique=True, db_index=True, verbose_name=('SLUG')) ... cat = models.ForeignKey('season', on_delete=models.PROTECT, null=True) def __str__(self): return self.slug def get_absolute_url(self): return reverse('episodepost', kwargs={'seasonpost_slug': self.slug, 'episodepost_slug': self.slug}) class Comment(models.Model): post = models.ForeignKey(episode,on_delete=models.CASCADE, related_name='comments') name = models.CharField(max_length=80) email = models.EmailField() body = models.TextField() created_on = models.DateTimeField(auto_now_add=True) active = models.BooleanField(default=False) class Meta: ordering = ['created_on'] def __str__(self): return 'Comment {} by {}'.format(self.body, self.name) FORM.PY from .models import Comment from django import forms class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ('name', 'body') Views from .forms import * from .models import * ... def ContentSeason(request, seasonpost_slug): seasonpages = get_list_or_404(season, slug=seasonpost_slug) homepages=home.objects.all() seasonspages=seasons.objects.all() season_menu=season.objects.all() episodepost = episode.objects.filter() seasonpages=season.objects.filter(slug=seasonpost_slug) return render(request, 'content/season.html',{ 'season':seasonpages, 'episode': episodepost,}) def ContentEpisode(request, seasonpost_slug, episodepost_slug): … -
How to add more details in a shoping cart in django?
I am building a application which is quiet similiar to an Ecommerce Shopping Cart in Django. However, in my case for each item in the shopping cart belongs to someone. So, instead of having the name of the item, the quantity, the price, ..., I would like to be able to see for each item, the name of the buyer, the receiver, the receiver's phone number and so fourth. So, for each order ID, I will be able to the details of beside the price, the quantity and items. Here are my file Cart.py class Cart(object): def __init__(self, request): """ Initialize the cart. """ self.session = request.session cart = self.session.get(settings.CART_SESSION_ID) if not cart: # save an empty cart in the session cart = self.session[settings.CART_SESSION_ID] = {} self.cart = cart # store current applied coupon self.coupon_id = self.session.get('coupon_id') def add(self, product, quantity=1, update_quantity=False): """ Add a product to the cart or update its quantity. """ product_id = str(product.id) if product_id not in self.cart: self.cart[product_id] = { 'quantity': 0, 'price': str(product.prix), 'destinataire':product.destinataire } if update_quantity: self.cart[product_id]['quantity'] = quantity else: self.cart[product_id]['quantity'] += quantity self.save() def save(self): # mark the session as "modified" to make sure it gets saved self.session.modified = True def remove(self, … -
How would I update a field to set a default value?
After updating an existing django field to have a default value if I save the field with a null value I get the error: IntegrityError: null value in column rather than the field being set to the default, does anyone know why this may be? If I include null=True it just sets it to null. -
Django sitemap problem for domain/category/city listing pages
I have a business directory and i made sitemaps for categories and firms, but when i came to build sitemap for category/city listing pages, i couldn't resolve. https://www.endustri.io/firma/enerji/bursa/ This is my live website. firma is prefix for business directory, enerji is a category and bursa is city. I am listing companies correctly. I made sitemap5.py codes with chatgpt. #Before the live version i am making local tries. but the result is here <url> <loc>http://example.com/firma/</loc> <lastmod>2023-03-04</lastmod> <changefreq>daily</changefreq> <priority>0.9</priority> </url> <url> <loc>http://example.com/firma/</loc> <lastmod>2023-03-04</lastmod> <changefreq>daily</changefreq> <priority>0.9</priority> </url> <url> <loc>http://example.com/firma/</loc> <lastmod>2023-03-04</lastmod> <changefreq>daily</changefreq> <priority>0.9</priority> </url> </urlset> here is my models.py class City(models.Model): city = models.CharField(max_length=50) slug = models.SlugField() def __str__(self): return str(self.city) class District(models.Model): district = models.CharField(max_length=50) slug = models.SlugField() city = models.ForeignKey(City, on_delete=models.CASCADE) def __str__(self): return str(self.district) class FirmaCategory(models.Model): title = models.CharField(max_length=255) slug = models.SlugField() aciklama = tinymce_models.HTMLField() date_added = models.DateTimeField(auto_now_add=True) class Meta: verbose_name_plural = 'Firma Kategorileri' def __str__(self): return str(self.title) def get_absolute_url(self): return reverse('firma-category', args=[str(self.slug)]) class Firma(models.Model): category = models.ForeignKey(FirmaCategory, related_name="firma", on_delete=models.CASCADE) title = models.CharField(max_length=300) slug = models.SlugField() adres = tinymce_models.HTMLField() tel = tinymce_models.HTMLField() website = tinymce_models.HTMLField() email = tinymce_models.HTMLField() intro = tinymce_models.HTMLField() body = tinymce_models.HTMLField() city = models.ForeignKey(City,related_name="FirmaCategory" ,on_delete=models.CASCADE) district = models.ForeignKey(District,related_name="FirmaCategory", on_delete=models.CASCADE) #url = models.CharField(max_length=255) date_added = models.DateTimeField(auto_now_add=True) class Meta: verbose_name_plural … -
Setting a timer for players in an online game in Django [closed]
I am implementing an online poker game with Django. Each player in the game has a certain amount of time to perform an action. What solution do you suggest for placing this timer? For this project, I am using Django Channel and WebSocket, and the scheduling work is done there