Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django ListView - getting the most recent related object and preventing Django from caching the view or database query
I have a Campaign model and a CampaignStatus model whose foreign key is the Campaign model. When a Campaign is edited or created it will pass through several statuses and will have a CampaignStatus object associated with each status change. Using Django's CBVs, I have a list view that shows a users Campaigns, and I want to pass the most recent status in the context to the template. Django seems to be caching the status and I don't know how to prevent it. (Possibly relevant: the Django admin campaign view also has the same caching problem - I've defined a method to get the most recent status. The Django admin CampaignStatus list view behaves as expected, always showing new statuses as soon as they're created.) I would like the cache to be 5 seconds, but it appears to be about 3 minutes. How can I change this? A code snippet from the generic ListView we're using: @method_decorator(cache_page(5), name="dispatch") # single arg is seconds class CampaignsListView(LoginRequiredMixin, ListView): model = Campaign paginate_by = 100 template_name = "writing/user_campaigns.html" context_object_name = "user_campaigns" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) for i, _ in enumerate(context.get("user_campaigns")): campaign = context["user_campaigns"][i] campaign_status = CampaignStatus.objects.filter(campaign=campaign).latest("-status") context["user_campaigns"][i].status = campaign_status.get_status_display() return context … -
ImportError: cannot import name 'ugettext_lazy' from 'django.utils.translation'
I imported from rest_auth.views import LoginView and I am trying to implement login api and I never import ugettext_lazy directly. from rest_auth.views import LoginView from django.contrib.auth import authenticate, login, logout from .serializers import LoginUserSerializer class Login(LoginView): def post(self, request, *args, **kwargs): serializer = LoginUserSerializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.validated_data['user'] login(request, user) return super().post(request, format=None) I recieved this problem File "C:\Users\v_kum\Documents\My Project\wshp\app_mypage\urls.py", line 4, in <module> from .login import Login File "C:\Users\v_kum\Documents\My Project\wshp\app_mypage\login.py", line 1, in <module> from rest_auth.views import LoginView File "C:\Users\v_kum\Documents\myenv\lib\site-packages\rest_auth\views.py", line 9, in <module> from django.utils.translation import ugettext_lazy as _ ImportError: cannot import name 'ugettext_lazy' from 'django.utils.translation' (C:\Users\v_kum\Documents\myenv\lib\site-packages\django\utils\translation\__init__.py) I read the other answers and most of answer suggested to downgrade from the django version 4 to 3. Is there any other ways to fix this problem or any other suggestion to implement login api? -
send video chunks from django to react
I've a video comming from rstp feed, I successfully processed it using openCV python. now it is generating image frames and I want to sent these image frames directly to frontend as they are generated. while True: success, img = cap.read() img = cv2.resize(img, (0, 0), None, 0.5, 0.5) ih, iw, channels = img.shape blob = cv2.dnn.blobFromImage( img, 1 / 255, (input_size, input_size), [0, 0, 0], 1, crop=False) net.setInput(blob) layersNames = net.getLayerNames() outputNames = [(layersNames[i - 1]) for i in net.getUnconnectedOutLayers()] outputs = net.forward(outputNames) postProcess(outputs, img) # I want to send these frames to my react frontend cv2.imshow('Output', img) if cv2.waitKey(1) == ord('q'): break I've already work with API's but never encountered such situation I'm confused how do I send these frames to my frontend. If streaming server is required, please share some references, any help will be appreciated. -
how to access the url after Django rest frame router
I am unable to access the url after path("", include(router.urls)), i would like to render a template after the load i am using django rest framework and i want to access the url after the rest fromework router and render a template from django.urls import path, include from rest_framework import routers from .views import NSE_DATA_VIEW_SET, AddCoi router = routers.DefaultRouter() router.register(r"", NSE_DATA_VIEW_SET) urlpatterns = [ path("", include(router.urls)), path("add", AddCoi) ] Image from django.urls import include, path urlpatterns = [ path("nsedata/", include("api.nsedata.urls")), path("coidata/", include("api.coidata.urls")) ] -
Upon email verification endpoint I'm getting an Invalid token error while trying to activate a user with tokens sent to the mail?
from django.db import models from django.contrib.auth.models import ( AbstractBaseUser, BaseUserManager, PermissionsMixin) from rest_framework_simplejwt.tokens import RefreshToken class UserManager(BaseUserManager): def create_user(self,username,email, password=None ): if username is None: raise TypeError("Users should have a username") if email is None: raise TypeError("Users should have an Email") user =self.model(username=username, email=self.normalize_email(email)) user.set_password(password) user.save() return user def create_superuser(self, username, email, password=None): if password is None: raise TypeError("Password should not be none") user = self.create_user(username, email, password) user.is_superuser = True user.is_staff = True user.save() return user class User(AbstractBaseUser, PermissionsMixin): username = models.CharField(max_length=100, unique=True, db_index=True) email = models.EmailField(max_length=100, unique=True, db_index=True) is_verified = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) USERNAME_FIELD = "email" REQUIRED_FIELDS = ["username"] objects = UserManager() def __str__(self): return self.email def tokens(self): refresh = RefreshToken.for_user(self) return { "refresh":str(refresh), "access": str(refresh.access_token) } Below is the serializers.py file from .models import User from rest_framework import serializers from django.contrib import auth from rest_framework.exceptions import AuthenticationFailed class RegisterSerializer(serializers.ModelSerializer): password = serializers.CharField(max_length=50, min_length=6, write_only =True) class Meta: model = User fields = ["email", "username", "password"] def validate(self, attrs): email = attrs.get("email", '') username = attrs.get("username", '') if not username.isalnum(): raise serializers.ValidationError("The username should contain only alphanumeric characters") return attrs def create(self, validated_data): return User.objects.create_user(**validated_data) class EmailVerificationSerializer(serializers.ModelSerializer): token … -
disable or enable checkboxes if belong to parent class
I have 2 tabs with a list of checkboxes. I'd like to create dependent checkboxes so if the user will select a checkbox in the first tab then it will disable all checkboxes in tab 2 that don't belong to the checkbox in tab 1. Both client_list and business_challange are the filters for my products and they are connected in relation ManyToMany with the Product model (models with view below). html file <div class="container"> <ul class="nav nav-tabs flex-row f-12 mb-3" id="myTab" role="tablist"> <li class="nav-item" role="presentation"> <button class="nav-link active" id="client-list-tab" data-bs-toggle="tab" data-bs-target="#client_list" type="button" role="tab" aria-controls="client_list" aria-selected="true">Client</button> </li> <li class="nav-item" role="presentation"> <button class="nav-link" id="business-challange-tab" data-bs-toggle="tab" data-bs-target="#business_challange" type="button" role="tab" aria-controls="business_challange" aria-selected="false">Challanges</button> </li> </ul> <div class="tab-content filters" id="myTabContent"> <div class="tab-pane fade show active" id="client_list" role="tabpanel" aria-labelledby="client-list-tab"> <div class="parent-checkbox"> {% for object in client_list %} <div class="form-check"> <input class="form-check-input" type="checkbox" value="{{object.title}}" id="{{object.title}}" data-filter="client_list" name="showCb" onclick="showMe('uncheck-all')"> <label class="form-check-label ps-2" for="{{object.title}}"> {{object.title}} </label> </div> {% endfor %} </div> </div> <div class="tab-pane fade" id="business_challange" role="tabpanel" aria-labelledby="business-challange-tab"> <div class="child-checkbox"> {% for object in business_challange %} <div class="form-check"> <input class="form-check-input" type="checkbox" value="{{object.title}}" id="{{object.title}}" data-filter="business_challange" name="showCb" onclick="showMe('uncheck-all')"> <label class="form-check-label ps-2" for="{{object.title}}"> {{object.title}} </label> </div> {% endfor %} </div> </div> </div> </div> js file $(document).on('click', '.parent-checkbox input[type=checkbox]', function (event) { // If … -
Django - Custom model field with default value
How can I set default value for timestp field ? Default value > 'NOW()' class Timestamp(models.Field): def db_type(self, connection): return 'timestamp' class MyModel(Model): # ... my_field = Timestamp() -
Access RelatedManager object in django
I have the following model : class Travel(models.Model): purpose = models.CharField(max_length=250, null=True) amount = models.IntegerField() class TravelSection(models.Model): travel = models.ForeignKey(Travel, related_name='sections', on_delete=models.CASCADE) isRoundTrip = models.BooleanField(default=True) distance = models.FloatField() transportation = models.CharField(max_length=250) I create object without using the database : mytravel = Travel( purpose='teaching', amount=1 ) mysection = TravelSection( travel=mytravel, isRoundTrip=True, distance=500, transportation='train' ) When I try to access mytravel.sections, I can't access to the field distance and other fields. How can I do this wihtout having to save in the database ? I don't want to create objects in the database, beaucause I'm trying to make some preprocessing. Thanks for your help -
Can I write RIGHT JOIN queryset in Django ORM?
How can I write RIGHT JOIN and ORDER BY queryset in Django ORM? For example I have two table : NEWS | id | title | | -------- | -------------- | | 1 | News 1 | | 2 | News 2 | | 3 | News 3 | | 4 | News 4 | COMMENTS | id | news_id | like_count | | -------- | -----|----- | | 1 | 1 | 100 | | 2 | 1 | 90 | | 4 | 3 | 245 | select n.title from NEWS n right join Comment c on n.id = c.news_id order by c.like_count DESC; wanted result: title like_count News 3 245 News 1 100 News 1 90 -
Django doesn't respect Prefetch filters in annotate
class Subject(models.Model): ... students = models.ManyToMany('Student') type = models.CharField(max_length=100) class Student(models.Model): class = models.IntergerField() dropped = models.BooleanField() ... subjects_with_dropouts = ( Subject.objects.filter(category=Subject.STEM). prefetch_related( Prefetch('students', queryset=Students.objects.filter(class=2020)) .annotate(dropped_out=Case( When( students__dropped=True, then=True, ), output_field=BooleanField(), default=False, )) .filter(dropped_out=True) ) I am trying to get all Subjects from category STEM, that have dropouts of class 2020, but for some reason I get Subjects that have dropouts from other classes as well. I know that I can achive with subjects_with_dropouts = Subject.objects.filter( category=Subject.STEM, students__dropped=True, students__class=2020, ) But why 1st approach doesn't work? I am using PostgreSQL. -
How to adjust the setting file to have the smallest (lightest) django source?
I want to build a lightest django source and how to set it in the settings.py As I notice, whenever I build and migrate a django source. There are tables which will be migrate by default such as: auth_group auth_group_permissions ... django_admin_log django_content_type ... In the situation, that I only need to build a source that server a couple of tables and CRUD (create, retrieve, update, delete) rows on that table. I dont need auth and django things. What should I do ? -
Django using the auth_user table in relationships
I'd like to use the auth_user table in one-to-many and many-to-many relationships. Is this a bad idea? Can I do it? How do I do it? Everything is happening through Admin. So, I just need the models. -
Django ManytoManyField query does not exist
I've created models for the logic of friend list and friend request. In the FriendRequest I've defined a method which adds User relation to FriendList if accept method is called. However I'm unable to do so because of the error shown below. I don't understand the error as I'm adding the User in the model. views.py friend_request = FriendRequest.objects.get(id=request_id) if request_option == 'accept': friend_request.accept() if request_option == 'decline': friend_request.decline() models.py class FriendList(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="user") friends = models.ManyToManyField(User, blank=True, related_name="friends") def add_friend(self, account): if not account in self.friends.all(): self.friends.add(account) self.save() class FriendRequest(models.Model): sender = models.ForeignKey(User, on_delete=models.CASCADE, related_name="sender") receiver = models.ForeignKey(User, on_delete=models.CASCADE, related_name="receiver") is_active = models.BooleanField(blank=False, null=False, default=True) timestamp = models.DateTimeField(auto_now_add=True) def accept(self): receiver_friend_list = FriendList.objects.get(user=self.receiver) if receiver_friend_list: receiver_friend_list.add_friend(self.sender) sender_friend_list = FriendList.objects.get(user=self.sender) if sender_friend_list: sender_friend_list.add_friend(self.receiver) self.is_active = False self.save() def decline(self): self.is_active = False self.save() raise self.model.DoesNotExist( friends.models.FriendList.DoesNotExist: FriendList matching query does not exist. -
RabbitMQ : How to check queue content when processing a task using celery?
I have setup a basic message and task queue using RabbitMQ and Celery in my Django app. According to my understanding the when I use delay menthod, that pushes my tasks to the rabbitMQ queue and one of my workers from my celery app fetches the same from queue to execute the same. Is there any way in which when I push the task to the queue using delay I can view the same on my message queue RabbitMQ management portal? Since the tasks are almost instantly fetched and processed there is no chance of viewing them on the portal. This is what I tried which I think is wrong by adding a sleep timer in my task method. sudo nano tasks.py from __future__ import absolute_import, unicode_literals from celery import shared_task import time @shared_task def add(x, y): time.sleep(100) return x + y Started my celery app (myprojectenv) root@ubuntu-s-1vcpu-1gb-blr1-01:/etc/myproject# celery -A myproject worker -l info Pushed the tasks for processing (myprojectenv) root@ubuntu-s-1vcpu-1gb-blr1-01:/etc/myproject# python3 manage.py shell Python 3.8.10 (default, Mar 15 2022, 12:22:08) [GCC 9.4.0] on linux Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> from app1.tasks import add >>> add.delay(1,2) On celery window [2022-06-10 06:16:15,182: INFO/MainProcess] celery@ubuntu-s-1vcpu-1gb-blr1-01 ready. … -
Validation Error {'__all__': ['Model with this field1, field2, field3 and field4 already exists.']} not getting handled by Django in admin
When I enter duplicate values for field1, field2, field3 and field4 in the django admin form, the debug screen with Validation Error appears Validation Error {'all': ['Model with this field1, field2, field3 and field4 already exists.']} instead of getting handled by the djnago admin form. The solution was I had excluded the field1 in my django admin.py file for the Model, I removed it from exclude and entered field1 in the fields of my Model Form. P.S. : readonly fields do not work in this scenario, you need to include the field in normal field, but you can add it as in custom form as widget readonly. -
Best way to send many choices through Django Rest Framework
I am using Django Rest Framework in conjunction with Vuejs to create a recipe costing calculator. I have an lot of unit choices (eg. grams, kilograms, liters etc.). What is the best way to send this data through to the frontend? I've created an endpoint for it at /ingredients/get-all-unit-choices/ that returns only an object with all the unit choices. Is this a good approach or is there a cleaner way to declare the choices and send it through to the frontend? And in general is it a good approach to create a lot of endpoints that do and return certain things? unitchoices.py WEIGHT_CHOICES = ["pound", "kilogram", "ounces", "grams", "tonnes"] VOLUME_CHOICES = [ "millileter", "litre", "gallon", "teaspoon", "tablespoon", "fluid-ounce", "quart", "pint", "cup", ] QUANTITY_CHOICES = ["each", "dozen", "hundreds", "thousands"] TIME_CHOICES = ["hours", "minutes", "seconds"] LENGTH_CHOICES = ["millimeter", "meter", "centimeter", "inch", "foot", "yard"] grouped_unit_choices = { "Weight": WEIGHT_CHOICES, "Volume": VOLUME_CHOICES, "Quantity": QUANTITY_CHOICES, "Time": TIME_CHOICES, "Length": LENGTH_CHOICES, } View This is the view that gets called by the ingredient/get-all-unit-choices/ endpoint. I also had to create the grouped_unit_choices dictionary so that I can display the <optgroup> in the html to have some order to them @api_view(["GET"]) def get_all_unit_choices(request): """helper view for returning all valid … -
no module named 'multiselectfield' (docker / Django)
I am trying to run a database on my server using docker. I am using django and postgreSQL. After adding the multiselectfield library to my repo it keeps failing to run the container with following error: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.8/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.8/site-packages/django/core/management/__init__.py", line 395, in execute django.setup() File "/usr/local/lib/python3.8/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python3.8/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/usr/local/lib/python3.8/site-packages/django/apps/config.py", line 224, in create import_module(entry) File "/usr/local/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked ModuleNotFoundError: No module named 'multiselectfield' Even though i pip installed the library on all python versions i have installed (requirement already satisfied....) It is included in the requirements.txt and is installed as well when building the container. -
Filter Embedded Documents that match a condition in MongoEngine, Django, GraphQl
Document Structure Data class Data(EmbeddedDocument): v = FloatField() q = StringField() co2 = FloatField() price = FloatField() ts = DateTimeField() Meters Data class MetersData(DynamicDocument): meta = {'collection': 'dk_heating'} _id = ObjectIdField() ident = StringField() meteringPointId = StringField() customer = StringField() cvr = StringField() type = StringField() unit = StringField() address = StringField() period = EmbeddedDocumentField(Period) hourly_data = ListField(EmbeddedDocumentField(Data), db_field='data') daily_data = ListField(EmbeddedDocumentField(Data)) monthly_data = ListField(EmbeddedDocumentField(Data)) # monthly_data = EmbeddedDocumentListField(Data) yearly_data = ListField(EmbeddedDocumentField(Data)) I am using this Query. Query MetersData.objects.filter(address=address, customer=customer).fields( monthly_data={"$elemMatch": {"q": "E"}}, address=1, customer=1, cvr=1, ident=1, meteringPointId=1, type=1, unit=1, period=1) It returns me only the first matching element. I have read the documentation and it reads that $elemMatch is supposed to return only the first matching result. But in my case, I need all the matching results. Result of the Query I have searched everywhere but I am unable to find a solution. -
How to test foreignkeys to self in django
Django allows a foreign key to "self" as in class Profile(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE, verbose_name="User", related_name="user_profiles", ) entity = models.ForeignKey( Entity, on_delete=models.CASCADE, verbose_name="Entity", related_name="entity_profiles", ) email = models.EmailField( max_length=255, help_text=_("Automatically generated to use entity email domain"), ) supervisor0 = models.ForeignKey( "self", on_delete=models.CASCADE, null=True, blank=True, verbose_name="Supervisor0", related_name="supervisor0_profiles", help_text=_("Employees only."), ) supervisor1 = models.ForeignKey( "self", on_delete=models.CASCADE, null=True, blank=True, verbose_name="Supervisor1", related_name="supervisor1_profiles", help_text=_( "Employees only. Only the executive head is his/her own \ supervisor." ), ) supervisor2 = models.ForeignKey( "self", on_delete=models.CASCADE, null=True, blank=True, verbose_name="Supervisor2", related_name="supervisor2_profiles", help_text=_( "Employees only. Only the executive head is his/her own \ supervisor." ), ) supervisor3 = models.ForeignKey( "self", on_delete=models.CASCADE, null=True, blank=True, verbose_name="Supervisor3", related_name="supervisor3_profiles", help_text=_( "Employees only. Only the executive head is his/her own \ supervisor." ), ) The supervisor0 is the user and being supervisor0 identifies him/her as an employee. The other supervisors also have to be already in the database for them to be able to be referenced. The help_texts explain the situation of the executive head. The question is how to test these relationships to "self". I have no problem with relationships to other models. Using pytest, I record only supervisor0 in the ProfileFactory for the moment. class ProfileFactory(factory.django.DjangoModelFactory): class Meta: model = Profile user … -
How i can to prevent to create multiple instance while multi request in django?
Hi everyone i have project include about payment function between user and user. But i have a problem when many user buy a product.the many payment object will created more than product avaliable. How i can to solve this ? products_avaliable = Product.objects.filter(on_sell=true) for product in products_avaliable: payment = Payment() payment.buyer = .... payment.seller = product.owner payment.save() product.on_sell = False product.save() when add deley products_avaliable = Product.objects.filter(on_sell=true) for product in products_avaliable: payment = Payment() payment.buyer = .... payment.seller = product.owner payment.save() time.sleep(10) # simulate to slow server or many request product.on_sell = False product.save() when i try to time.delay before payment create (simulate when server to slow or may request by user) the payment will create many object -
Django could not detect newly added database after adding router
I have three database out of which one is set to default. I have already created router for ringi database and it working perfectly fine. Now i would like to add one more database and after creating the new router for database named cms, its not working. So my project name is wshp and one of router for ringi database, i placed it in same folder as settings.py. I created another app called mypage and created router for cms and name of router is cmsrouter. settings.py DATABASE_ROUTERS = ['wshp.router.myrouter','app_mypage.cms_router.cmsrouter'] DATABASE_APPS_MAPPING = { 'ringi':'ringi_db', 'cms':'cms_db' } DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'mypage', 'USER': 'root', 'PASSWORD': '', 'HOST': 'localhost', 'PORT': '3306', }, 'ringi_db':{ 'ENGINE': 'django.db.backends.mysql', 'NAME': 'ringi', 'USER': 'root', 'PASSWORD': '', 'HOST': 'localhost', 'PORT': '3306', }, 'cms_db':{ 'ENGINE': 'django.db.backends.mysql', 'NAME': 'cms', 'USER': 'root', 'PASSWORD': '', 'HOST': 'localhost', 'PORT': '3306', } } cms_router.py class cmsrouter: def db_for_read(self, model, **hints): if model._meta.app_label == 'cms': return 'cms_db' else: return None def db_for_write(self, model, **hints): if model._meta.app_label == 'cms': return 'cms_db' else: return None def allow_relation(self, obj1, obj2, **hints): if obj1._meta.app_label == 'cms' or \ obj2._meta.app_label == 'cms': return True else: return None def allow_migrate(self, db, app_label, model_name=None, **hints): if app_label == 'cms': … -
form.errors won't display upon invalid form submission
I'm having difficulty with displaying custom defined errors on a page when a user submits an invalid form submission. I set novalidate on the form element with the intent of disabling a browser's default form validation messages. At the same time the error messages that are defined on QuestionForm are not displaying on the page. It's not clear to me why the form error messages aren't showing? Is setting novalidate causing this to occur? class Page(TemplateView): def get_context_data(self, **kwargs): context = super().get_context_data() context['search_form'] = SearchForm() return context class AskQuestionPage(Page): template_name = "posts/ask.html" extra_context = { 'title': "Ask a public question" } def attach_question_tags(self, tags): question_tags = [] for name in tags: try: tag = Tag.objects.get(name=name) except Tag.DoesNotExist: tag = Tag.objects.create(name=name) finally: question_tags.append(tag) return question_tags def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['form'] = QuestionForm return context def post(self, request): context = self.get_context_data() form = context['form'](request.POST) if form.is_valid(): tags = self.attach_question_tags( [tag.lower() for tag in form.cleaned_data.pop("tags")] ) try: question = form.save(commit=False) question.profile = request.user.profile question.save() except IntegrityError: form.add_error(None, "This post is already posted") context['form'] = form else: question.tags.add(*tags) form.save_m2m() return SeeOtherHTTPRedirect( reverse("posts:question", kwargs={ "question_id": question.id }) ) return self.render_to_response(context) <div class="question_posting_form"> <h2>{{ title }}</h2> {% if form.non_field_errors %} <ul class="non_field_errors"> {% for … -
Login page is not appearing while it directly catch register form
login.html {% extends 'main.html' %} main.html extended {% block content %} block content added {% if page == 'Login' %} if url is login will open login section {% csrf_token %} Sign Up {% else %} {% csrf_token %} {% for field in form %} {{field.label}} used for auto filling of fields {{field}} fields are fetched directly from model.py {% endfor %} Already signed up yet? Login {% endif %} {% endblock content %} -
Is there a way to override ClockedSchedule model from Django Celery Beat?
I want to add unique=True attribute to clocked_time field of ClockedSchedule model. Current Scenario is, when multiple threads try to get_or_create schedule, it creates more than one of similar records given schedule is not found, and when next time some thread tries to get the schedule it throws MultipleObjectsReturned exception. So, I was thinking adding a DB constraint might work here. Attaching the code for reference: schedule, created = ClockedSchedule.objects.get_or_create(**clocked_options) return schedule And the model looks like: class ClockedSchedule(models.Model): """clocked schedule.""" clocked_time = models.DateTimeField( verbose_name=_('Clock Time'), help_text=_('Run the task at clocked time'), ) class Meta: """Table information.""" verbose_name = _('clocked') verbose_name_plural = _('clocked') ordering = ['clocked_time'] def __str__(self): return '{}'.format(self.clocked_time) Let me know your thoughts, thanks! -
Ajax get request stays on readystate 1, but when i log the response text in the console it displays it without a problem
I cant display the result in my html because the request stays in state 1 and the response text displays undefined. When I access the url it displays the value I want to show on my html. Why is this happening? I'm using django on server side btw. Kinda new to ajax but I haven't been able to find an answer to this problem on other already solved questions. Code that executes the request: const getHighScore = (gameID, levelID) => { let ajaxPrueba = $.ajax({ url: `/get-data/${gameID}/${levelID}`, type: 'get', success: function(data) { return data; }, failure: function(data) { console.log('Got an error dude'); } }); return ajaxPrueba; } The parameters i pass on are 1 for gameID and 1 for levelID The url i'm talking about Also this is what the console returns: ajaxPrueba = $.ajax({ url: `/get-data/1/1`, type: 'get', success: function(data) { return data;… Object { readyState: 1, getResponseHeader: getResponseHeader(e), getAllResponseHeaders: getAllResponseHeaders(), setRequestHeader: setRequestHeader(e, t), overrideMimeType: overrideMimeType(e), statusCode: statusCode(e), abort: abort(e), state: state(), always: always(), catch: catch(e) , … } abort: function abort(e) always: function always() catch: function catch(e) done: function add() fail: function add() getAllResponseHeaders: function getAllResponseHeaders() getResponseHeader: function getResponseHeader(e) overrideMimeType: function overrideMimeType(e) pipe: function pipe() progress: function …