Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django video uploads new video not display
I'm using django 3, when I upload a video from the admin panel, it doesn't appear on the page. When I go to the video url, I get a 404 error, but my old uploads are visible, and the newly uploaded files are not visible. My English is not very good, I translated it with google translate and I'm sorry if there are any mistakes -
serve() is called twice everytime I reload a blog page in wagtail
I am using wagtail to build a blog website. In order to count the visits of each blog, I override the get_context() and serve() to set cookie. The codes are as follows: def get_context(self, request): authorname=self.author.get_fullname_or_username() data = count_visits(request, self) context = super().get_context(request) context['client_ip'] = data['client_ip'] context['location'] = data['location'] context['total_hits'] = data['total_hits'] context['total_visitors'] =data['total_vistors'] context['cookie'] = data['cookie'] context['author']=authorname return context def serve(self, request): context = self.get_context(request) template = self.get_template(request) response = render(request, template, context) response.set_cookie(context['cookie'], 'true', max_age=3000) return response And the function count_visits is as follows: def count_visits(request, obj): data={} ct = ContentType.objects.get_for_model(obj) key = "%s_%s_read" % (ct.model, obj.pk) count_nums, created = VisitNumber.objects.get_or_create(id=1) if not request.COOKIES.get(key): blog_visit_count, created =BlogVisitNumber.objects.get_or_create(content_type=ct, object_id=obj.pk) count_nums.count += 1 count_nums.save() blog_visit_count.count += 1 blog_visit_count.save() The problem I met is that when I reload the blog page, serve() was loaded twice. The first time request was with cookie info. But the second time the cookie of the request was {}, which caused the count of visit does not work correctly. I do not understand why serve() is called twice everytime I reload page. -
How to check if the email/username already exists in the db in django?
How to check if the email_id/ username already exists in the database in django? I want to check the existence of the email/username in the views rather than in serializer. Following is the code: @api_view(['POST']) def registerUser(request): f_name = request.data.get('f_name') l_name = request.data.get('l_name') username = request.data.get('username') email_id = request.data.get('email_id') password = make_password(request.data.get('password')) RegistrationRegister.objects.create( f_name = f_name, l_name = l_name, username = username , email_id = email_id, password = password, created = datetime.datetime.now().isoformat() ) return Response("User registered successfully ") The name of the table is RegistrationRegister. How can I validate the email and check if it exists in the db? -
Register data by multiple select django
I'm a beginner and I was trying to create a registered data form in the database, all the fields are registered well instead of the multiple select fields. from.py class SavePost(forms.ModelForm): user = forms.IntegerField(help_text = "User Field is required.") title = forms.CharField(max_length=250,help_text = "Title Field is required.") description = forms.Textarea() dep = forms.Textarea() class Meta: model= Post fields = ('user','title','description','file_path', 'file_path2', 'dep') HTML <div class="form-group mb-3 "> <label for="exampleFormControlSelect2"> multiple select</label> <select multiple class="form-control" id="dep" value={{ post.title }}> <option>Process</option> <option>Product</option> <option>Equipment</option> </select> </div> <div class="form-group mb-3 "> <label for="title" class="control-label">Title</label> <input type="text" class="form-control rounded-0" id="title" name="title" value="{{ post.title }}" required> </div> <div class="form-group mb-3"> <label for="description" class="control-label">Description</label> <textarea class="form-control rounded-0" name="description" id="description" rows="5" required>{{ post.description }}</textarea> thank you in advanced -
Display field from another model in ModelAdmin of User model
My Django project is based on built-in User model. For some extra attributes, I have defined another model: models.py: class Status(models.Model): email = models.ForeignKey(User, on_delete=models.CASCADE) is_verified = models.BooleanField(default=False) is_active = models.BooleanField(default=False) def __str__(self): return self.email And here's the custom ModelAdmin: admin.py: class CustomUserAdmin(UserAdmin): model = User list_display = ['email'] search_fields = ['email'] I want list_display to show me is_verified and is_active fields from Status model but I'm lost. I've looked into some similar questions on SO like Display field from another model in django admin or Add field from another model Django but none of the solutions are applicable because one of my models is Django's built-in. -
Account with this Email already exists. how to fix this?
I tried to create a login form. But when I try to login django gives the error that Account with this Email already exists. i don`t now how to fix this.Help me plz Here is my code, please tell me where I'm going wrong: forms.py class AccountAuthenticationForm(forms.ModelForm): password = forms.CharField(label='Password', widget=forms.PasswordInput) class Meta: model= Account fields = ('email', 'password') def clen(self): email = self.cleaned_data['email'] password = self.cleaned_data['password'] if not authenticate(email=email, password=password): raise forms.ValidationError("Invalid login") views.py def login_view(request): context = {} user = request.user if user.is_authenticated: return redirect("home") if request.POST: form = AccountAuthenticationForm(request.POST) if form.is_valid(): email=request.POST['email'] password = request.POST['password'] user =authenticate(email=email, password=password) if user: login(request,user) return redirect("home") else: form = AccountAuthenticationForm() context['login_form'] = form return render(request, 'account/login.html', context) login.html {% extends 'base.html' %} {% block content %} <h2>Login</h2> <form method="post">{% csrf_token %} {% for field in login_form %} <p> {{field.label_tag}} {{field}} {% if field.help_text %} <small style="color:grey">{field.help_text}</small> {% endif %} {% for error in field.errors %} <p style="color:red">{{error}}</p> {% endfor %} {% if login_form.non_field_errors %} <div style="color:red";> <p>{{login_form.non_field_errors}}</p> </div> {% endif %} </p> {% endfor %} <button type="submit">Log in</button> </form> {% endblock content %} I'm just getting started with Django. I will be glad if you point out my mistake -
I can't save data of <select> in html
I have django application with form. in model LIVING_COUNTRIES = [ ('AFGANISTAN', 'Afganistan'), ('ALBANIA', 'Albania'), ('ALGERIA', 'Algeria'), ('ANGORRA', 'Andorra')] class Employee(models.Model): country_living = models.CharField(max_length=50, choices=LIVING_COUNTRIES, default=FRESHMAN, blank=True, null=True) in html <select name="country" id="id_category" data="{{ data.country }}"> {% for each in living_countries_list %} <option value="{{ each.0 }}" class="living_countries">{{ each.1 }}</option> {% endfor %} </select> in view context['has_error'] = True if context['has_error']: employees = models.Employee.objects.all() living_countries_list = LIVING_COUNTRIES return render(request, 'authentication/employee_register.html', context) So I have form rendered in get() method of class-based view. When I click submit post method checks for errors. If there are any context['has_error'] is set to true. For simplycity I've written it down anyway. And if it is true we render form again. I want to have previous choice of user still displayed in html. I've done it on other inputs by `data="{{ data.field }}". How would I do that here? -
How do I bring through my data in Django Template view?
I'm trying to display my data from my HealthStats model to my template, however I can only pull through the user field. I've added the other fields to my template, but they're not showing. I would also like to be able to filter the output to only show records of the logged in user. Models.py class HealthStats(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) date = models.DateField(auto_now=True) weight = models.DecimalField(max_digits=5, decimal_places=2) run_distance = models.IntegerField(default=5) run_time = models.TimeField() class Meta: db_table = 'health_stats' ordering = ['-date'] def __str__(self): return f"{self.user} | {self.date}" Views.py: class HealthHistory(generic.TemplateView): model = HealthStats template_name = 'health_hub_history.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['stats'] = HealthStats.objects.all() return context health_hub_history.html {% extends 'base.html' %} {% load static %} {% block content %} <div class="container-fluid"> <div class="row"> <div class="col-sm-12 text-center"> <h1>My Health History</h1> </div> </div> </div> <div class="container-fluid"> <div class="row justify-content-center"> <div class="col-auto text-center p-3"> <table class="table table-striped table-hover table-bordered"> <tr> <td>User:</td> <td>Weight (lbs):</td> <td>Date:</td> <td>Run Distance (km):</td> <td>Run Time (HH:MM:SS):</td> </tr> {% for stat in stats %} <tr> <td>{{ user }}</td> <td>{{ weight }} </td> <td>{{ date }}</td> <td>{{ run_distance }}</td> <td>{{ run_time }}</td> </tr> {% endfor %} </table> </div> </div> </div> {% endblock content %} Any help would be appreciated! -
How to serialize a foreign key relationship as key value pair django rest framework
I'm trying to serialize an relationship in DRF whereas I attempt to get the following output: "statistics":[ "Attacks":{ "id":971, "home_value":3, "away_value":2, "value":5 }, "Corners":{ "id":972, "home_value":0, "away_value":0, "value":0 } ] I wrote the following code for my serializer of this model: class StatisticSerializer(serializers.ModelSerializer): class Meta: model = Statistic fields = ['id', 'home_value', 'away_value', 'name', 'value'] def to_representation(self, instance: Statistic): representation = {instance.name: { "id": instance.id, "home_value": instance.home_value, "away_value": instance.away_value, "value": instance.value }} return representation Which gets me the following output: "statistics":[ { "Attacks":{ "id":971, "home_value":3, "away_value":2, "value":5 } }, { "Corners":{ "id":972, "home_value":0, "away_value":0, "value":0 } } ] Is there any way to get it as demonstrated in the first example using django rest framework? -
how to call a function when app start in django?
i want to call the daily_data_log_checker function in that MainConfig class so that it can run when the app start class MainConfig(AppConfig): default_auto_field = 'django.db.models.AutoField' name = 'main' def daily_data_log_checker(): import datetime from datetime import datetime from datetime import date from main.models.status import DailyMachinePerformance from main.management.commands.jobscheduler import log_daily_data now_time = datetime.datetime.now() today = date.today() if(now_time.hour>= 11): daily_machine_performance = DailyMachinePerformance.objects.filter(date = today) if(len(daily_machine_performance) == 0): log_daily_data() -
Simple quest in view and settings
Well, I working on this problem about 2 weeks. Searching in google a lot, experimenting with options. But that is just not working -_-. I can't even pinpoint what the problem is, probably in views or settings with join. Just look. I had a lot of errors, at this moment I see: No module named 'path', , line 1004, in _find_and_load_unlocked I know this problem is simple, but I tired to struggle :D Settings from pathlib import Path import os BASE_DIR = Path(__file__).resolve().parent.parent TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'path.to.inject_form', ], }, }, ] urls urlpatterns = [ path('form/', views.SignUpp, name="SignUpp"), path("",views.head.as_view(), name="mainpage"), path("stocks/", views.stockpage.as_view(), name="stockpage"), path("search/", SearchResultStocks.as_view(), name="search-Stocks"), ] + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) Views def SignUpp(request): if request.method == 'POST': form = UserSign(request.POST) if form.is_valid(): body = { 'Name': form.cleaned_data['Name'], 'email': form.cleaned_data['email'], 'Number': form.cleaned_data['Number'], } info_user = "\n".join(body.values()) send_mail( 'Sign', info_user, 'eric1122221@mail.ru', ['eric1122221@mail.ru'], fail_silently=False) form.save() return redirect("dental/mainpage.html") else: form= UserSign() context = { 'form': form } return render(request, 'base.html', context) class head(ListView): template_name = "dental/mainpage.html" model = signup class stockpage(ListView): template_name = "dental/stocks.html" model = stock context_object_name = "stocks" class SearchResultStocks(ListView): model = stock template_name … -
Migrating the database from legacy flask app to django
Hello i have an existing app made in Flask, it consist of simple database but it doesn't have migrations (flask-migrate) ever since and the data grows more. If i enable the migrations on django, could it screw the datas? and in case if i disable the migrations, can django writes up like the old existing ones? Here's my old db model (FLASK) from database.db import db class users(db.Model): id = db.Column(db.Integer, primary_key=True, autoincrement=True) name = db.Column(db.String(255), unique=True) project = db.Column(db.String(255)) reason = db.Column(db.String(255)) timestamp = db.Column(db.DateTime, default=now) And this is my new one (DJANGO) from django.db import models as db class users(db.Model): class Meta: managed = False id = db.AutoField(primary_key=True) name = db.CharField(max_length=255, unique=True) project = db.CharField(max_length=255) reason = db.CharField(max_length=255) timestamp = db.DateTimeField(auto_now_add=True) -
sorting in django admin list by a custom field alphabetically
I have a simple store / product relationship and I want to sort the products depending on the store name alphabetically. models: class Store(models.Model): name = models.CharField("name", max_length = 128) class Product(models.Model): number = models.PositiveIntegerField() name = models.CharField("name", max_length = 128) store = models.ForeignKey(Store, on_delete = models.CASCADE) and in the admin: class ProductAdmin(admin.ModelAdmin): list_display = ["number", "name", "get_store_name",] def get_store_name(self, obj): return f"""{obj.store.name}""" I know I cannot use order_by on custom fields. So I thought I need to override the get_queryset method probably? I found multiple examples to annotate by counted or calculated numbers, but never for strings. -
Optional URL for taggit Django
I'am using django-taggit in my project, to put tags on items. So i watched this tutorial to use the tags in class based views. I want to show all tags on top, and on click on the tags I want to show all items with the tag, and i've been using parameters in the url, to search for the items. But i want this parameter to be optional, so the user doesn't need to give a tag in the url. Is this possible? This is my URL so far: path('items/', views.ItemsView.as_view(), name='items'), -
Convert raw sql to django query
How can I convert this raw sql to django query?? knowledges.raw( ''' SELECT KnowledgeManagement_tblknowledge.KnowledgeCode,KnowledgeManagement_tblknowledge.KnowledgeTitle,KnowledgeManagement_tblknowledge.CreateDate,KnowledgeManagement_tblknowledge.CreatorUserID_id FROM KnowledgeManagement_tblknowledge LEFT JOIN KnowledgeManagement_tblusedknowledge ON KnowledgeManagement_tblknowledge.KnowledgeCode = KnowledgeManagement_tblusedknowledge.knowledge_id where register_status = 7 or register_status = 9 and Status = 1 Group by KnowledgeManagement_tblknowledge.KnowledgeCode order by count( KnowledgeManagement_tblusedknowledge.id) desc; ''' ) -
How to regroup entries in Django by model field (More complex query)?
First i'm not an exeperienced developer in Django, i use Django 4.0.6 on windows 10 and python 3.8.9 in a virtual environment. I need help with my query in Django: first here's my model: from django.db import models class MyWords(models.Model): WordText=models.CharField(max_length=1000, unique=True) WordStatus=models.IntegerField() WordType=models.CharField(max_length=30) and i have this sqllite database table with the following entries as example: db.sqlite3 MyWords Table: WordText WordStatus WordType Dog 0 Animal Cat 1 Animal Car 4 Object Lion 1 Animal Computer 4 Inanimate Object Stone 5 Inanimate Object Child 4 Human What i want to do is to get this info back this way: data == [ {'WordType':'Object', 'WordStatus':4,'WordText':'Car'}, {'WordType':'Animal', 'WordStatus':[0,1,1], 'WordText':'Dog','Cat','Lion'}, {'WordType':'Inanimate Object', 'WordStatus':[4,5], 'WordText':'Computer','Stone'}, {'WordType':'Human', 'WordStatus':4, 'WordText':'Human'} ] Essentially i want to regroup/categorize the entries by WordType so i can access them more easily. Is this possible in Django ORM? If yes, how? I first thought using something like a values_list with WordType as argument followed by a distinct and annotate, but i'm stucked. Something like this: data =MyWords.objects.all().values_list('WordType').distinct().annotate(WordStatus=?).annotate(WordText=?) I don't know if it's correct because i don't know what to replace the question marks with. I don't know if i'm on the correct path. So can anyone guide me please? N.B: I … -
Django Kubernetes Ingress CSRF Cookie not sent
Asking this question here because It's been a couple of days and I can't find anything useful. Problem: I have an app deployed to a Kubernetes cluster running on AWS EKS with a custom docker image on AWS ECR. The app works fine with GET requests but not with POST ones. The error given is Errore 403 forbidden CSRF Token not sent. Django version is 2.2.24 on DRF 3.11.2. I already added CSRF_TRUSTED_ORIGINS in settings.py, nothing changed. The ingress I'm using is AWS's Application Load Balancer set like this: apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: django labels: name: django annotations: alb.ingress.kubernetes.io/scheme: internet-facing alb.ingress.kubernetes.io/target-type: ip alb.ingress.kubernetes.io/backend-protocol: HTTP alb.ingress.kubernetes.io/listen-ports: '[{"HTTP":80}]' alb.ingress.kubernetes.io/group.name: "alta" alb.ingress.kubernetes.io/group.order: "2" alb.ingress.kubernetes.io/healthcheck-protocol: HTTP alb.ingress.kubernetes.io/healthcheck-port: traffic-port alb.ingress.kubernetes.io/healthcheck-path: /v1/app alb.ingress.kubernetes.io/healthcheck-interval-seconds: "15" alb.ingress.kubernetes.io/healthcheck-timeout-seconds: "5" alb.ingress.kubernetes.io/success-codes: "200" alb.ingress.kubernetes.io/healthy-threshold-count: "2" alb.ingress.kubernetes.io/unhealthy-threshold-count: "2" spec: ingressClassName: alb rules: - http: paths: - pathType: Prefix path: / backend: service: name: djangoapp-cluster-ip port: number: 80 Any help is much appreciated. -
Django - remove/hide labels for checkboxes
I would have thought this would be pretty simple but I have plugged away at this for some time and I can't figure it out. I have a multiple choice checkbox in a model form which is in a formset. All I want to do is remove the labels from the checkboxes. I can easily remove the label from the field but I can't figure out how to remove the labels from the checkboxes. I am trying to convert the display of the form to a grid. From this: To this: Here's my form code: class ResourceEditAddForm(forms.ModelForm): def __init__(self, *args, **kwargs): self.portfolio = kwargs.pop('portfolio') super(ResourceEditAddForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_show_labels = False self.fields["portfolio"].initial = self.portfolio self.fields["portfolio"].required = False self.fields["skills"].queryset = self.portfolio.getSkills() class Meta: model = Resource fields = ['portfolio', 'name', 'skills', 'pct_availability', 'cost_per_day', 'email', 'timezone', 'update_request_time', 'calendar', 'start_date', 'end_date'] widgets = { 'portfolio': forms.HiddenInput(), 'start_date': DateInput(), 'end_date': DateInput(), 'update_request_time': TimeInput(), 'skills': forms.CheckboxSelectMultiple(), } ResourceEditAddFormSet = modelformset_factory( Resource, form=ResourceEditAddForm, extra=0 ) I could build a manual form to achieve this but I want to keep using model forms as there's a few fields other than skills which are managed fine by the form. If anyone can tell me how to … -
Serialize nested JSON to Django models
how can I create a nested structure from a nested JSON? I want my Hobby to have a ForeignKey to the Profile. It cant be that hard, but I really dont understand the error. It even creates the objects and saves them in my database but still says it does not find the field. I Get the following error with my code: AttributeError: Got AttributeError when attempting to get a value for field `description` on serializer `HobbySerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `RelatedManager` instance. Original exception text was: 'RelatedManager' object has no attribute 'description'. serializers.py: class HobbySerializer(serializers.ModelSerializer): class Meta: model = Hobby fields = ["name", "description"] class ProfileSerializer(serializers.ModelSerializer): user_hobby23 = HobbySerializer(many=False) class Meta: model = Profile fields = ["testfield1", "display_name", "mobile", "address", "email", "dob", "user_hobby23"] def create(self, validated_data): user_hobby_data = validated_data.pop('user_hobby23') profile_instance = Profile.objects.create(**validated_data) Hobby.objects.create(user=profile_instance, **user_hobby_data) return profile_instance models.py: class Profile(models.Model): display_name = models.CharField(max_length=30) mobile = models.IntegerField() address = models.TextField() email = models.EmailField() dob = models.DateField() photo=models.FileField(upload_to='profile/',null=True,blank=True) status = models.IntegerField(default=1) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) testfield1 = models.TextField(null=True) class Hobby(models.Model): user=models.ForeignKey(Profile,on_delete=models.CASCADE,related_name='user_hobby23',null=True) name = models.CharField(max_length=30) description = models.TextField() status = models.IntegerField(default=1) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) views.py: class … -
How to call model method in ajax through views_api and assign the value to table data in DRF?
I am trying to understand the Django Rest Framework. As a beginner here, what I am trying is to call a method from a Model and update the value in the template. I am trying it from views_api.py with an ajax call. I was able to get other values, but I couldn't get three values. Here is what I have so far. reviews/models.py class Review(TimeStampedModel): project = models.ForeignKey('projects.Project', on_delete=models.CASCADE, related_name='reviews') fiscal_year = models.PositiveIntegerField(null=True, blank=True, db_index=True) fiscal_month = models.PositiveIntegerField(null=True, blank=True, db_index=True) has_validation = models.BooleanField('Has PFK', default=False) review_date = models.DateField(help_text='Date of the PFK', db_index=True) wp_validation_deadline = models.DateTimeField(blank=True, null=True, help_text='Deadline to validate WP') cutoff_date = models.DateTimeField(db_index=True, help_text='Up to when actuals are considered (date after accruals were entered)') fct_n_amount = models.DecimalField('FCT n amount', decimal_places=2, max_digits=12, null=True, blank=True) actuals_amount = models.DecimalField('Actual revenue traded', decimal_places=2, max_digits=12, null=True, blank=True, help_text='Cost to date (from monthly projectsales.xlsx)') events_amount = models.DecimalField('Total Events', decimal_places=2, max_digits=12, null=True, blank=True, help_text='In project currency (will be displayed in Thousands)') risks_real_amount = models.DecimalField('Total Risks - Most Likely', decimal_places=2, max_digits=12, null=True, blank=True, help_text='In project currency (will be displayed in Thousands)') risks_max_amount = models.DecimalField('Total Risks - Maximum', decimal_places=2, max_digits=12, null=True, blank=True, help_text='In project currency (will be displayed in Thousands)') opportunities_amount = models.DecimalField('Total Opportunities', decimal_places=2, max_digits=12, null=True, blank=True, help_text='In … -
Signature drawing for the form
For my application with Django, I want to make a signature drawing field after entering the necessary information in the form field. When I want to save and edit this form later, the signature drawn in that signature drawing place needs to be displayed again. I'm new to this and I have no idea how to do it, can you help with this? -
How to generate auto generate unique serial number by date and also It will be generate serial vise after delete in django
I have to generate serial number like TES-0922-1,TES-0922-2 and so on.... here TES is (company_lable) 0922 is (month and year) 1,2 is (serial number) I wish to generate unique number by date . If today is month 9 and year 22 and I am generating new data of this month then my serial number will be TES-0922-01. Also If I have serial numbers TES-0922-01,TES-0922-02,TES-0922-03 and If I am deleting TES-0922-01 from them. afterwards when I creating new data my serial number will be TES-0922-04 Also If I have serial numbers TES-0922-01,TES-0922-02,TES-0922-03,TES-0922-04 and If I am deleting TES-0922-01, TES-0922-04 from them. afterwards when I creating new data my serial number will be TES-0922-04 Note : I am saving that data in the database and handling them by django queryset. What I did is mentioned below but Its not working properly. Because I am counting my data by django queryset. views.py def sales_invoice(request): current_time = datetime.datetime.now() latest_year = current_time.year year=str(latest_year)[-2:] latest_month = current_time.month month="%02d" % (latest_month) company_label= Company_Setup.objects.get(id=request.session['company_id']) existing_label=Sales_Invoice.objects.filter(company=company_label).all() if not existing_label: gen_invoice_number=f"{company_label}-{month}{year}-1" else: total_sales = Sales_Invoice.objects.filter(company=company_label).all().count() + 1 gen_invoice_number=f"{company_label}-{month}{year}-{total_sales}" -
Difference between request.user vs. get_user(request) in Django?
I noticed there are two ways to get a user object from request (assuming user is already logged in and the session is valid): user = request.user user = get_user(request) where get_user() is imported from django.contrib.auth. What's the difference? get_user() seems to do a lot of validation for request session. Which is better? -
Several properties with the same type Django
I have two models class Manager(models.Model): name = models.CharField(max_length=250) def __str__(self): return self.name class Project(models.Model): title = models.CharField(max_length=250, null=True, blank=True) work_statement = models.TextField(null=True, blank=True) contract_id = models.CharField(max_length=250, null=True, blank=True) note = models.TextField(null=True, blank=True) customer = models.CharField(max_length=250, null=True, blank=True) #executer = models.ManyToManyField(Manager) deadline = models.DateTimeField(null=True, blank=True) So there is logic I want Model Project to has several managers as executers but not all of them how can i do it? so for example: Project "N" can include two managers for execution i know that this way is not correct class Project(models.Model): title = models.CharField(max_length=250, null=True, blank=True) work_statement = models.TextField(null=True, blank=True) contract_id = models.CharField(max_length=250, null=True, blank=True) note = models.TextField(null=True, blank=True) customer = models.CharField(max_length=250, null=True, blank=True) executer1 = models.ForeignKey(Manager) executer2 = models.ForeignKey(Manager) deadline = models.DateTimeField(null=True, blank=True) -
Is celery-beats can only trigger a celery task or normal task (Django)?
I am workign on a django project with celery and celery-beats. My main use case is use celery-beats to set up a periodical task as a background task, instead of using a front-end request to trigger. I would save the results and put it inside model, then pull the model to front-end view as a view to user. My current problem is, not matter how I change the way I am calling my task, it always throwing the task is not registered in the task list inside celery. I am trying to trigger a non-celery task(inside, it will call a celery taskthe , using celery beats module, Below is the pesudo-code. tasks.py: @app.shared_task def longrunningtask(): res = APIcall.delay() return res caller.py: from .task import foo def dosomething(input_list): for ele in input_list: res.append(longrunningtask()) return res Periodical Task : schedule, created = CrontabSchedule.objects.get_or_create(hour = 1, minute = 34) task = PeriodicTask.objects.create(crontab=schedule, name="XXX_task_", task='app.caller.dosomething')) return HttpResponse("Done") Nothing special about the periodical task, but This never works for me. It errored that not detected tasks or not registered tasks if I do not make the dosomething() as celery task. Problem is I do not want to make the caller function a celery task, the …