Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Likes as a many to many
I'm making a public prayer journal in full stack(react w/ nextjs and python w/ django) where you can also add and like verses. As the title says the likes are the many to many but I need it to where any component that displays verse likes will need all of the likes for a user and store them in state. If a verse is in the userLikes for a user, the like button should get checked on render. I need a change handler to submit a userlike to the api whenever the like button is checked, and delete a userlike whenever the like button is unchecked. But I'm unsure of how it's supposed to look exactly, I have trouble translating sentences to code. I already have the api views and data module, as seen below: user_like class LikeView(ViewSet): def retrieve(self, request, pk): try: user_like = UserLike.objects.get(pk=pk) serializer = UserLikeSerializer(user_like) return Response(serializer.data) except UserLike.DoesNotExist as ex: return Response({'message': ex.args[0]}, status=status.HTTP_404_NOT_FOUND) def list(self, request): user_likes = UserLike.objects.all() verse = request.query_params.get('verse', None) user = request.query_params.get('user', None) if verse is not None: user_likes = user_likes.filter(verse_id=verse) if user is not None: user_likes = user_likes.filter(user_id=user) serializer = UserLikeSerializer(user_likes, many=True) return Response(serializer.data) def update(self, request, pk): user_like … -
TypeError: Cannot read properties of undefined (reading 'params') Django + React
Uncaught TypeError: Cannot read properties of undefined (reading 'params') Unabel to navigate to id can anyone help? i am woriking on django as backend and react as frontend class ArticleDetail extends React.Component{ state={ article:{} } componentDidMount(){ const id = this.props.match.params.id; axios.get(`http://127.0.0.1:8000/api/${id}`) .then(res =>{ this.setState({ article:res.data }); console.log(res.data) }) } render(){ return( <Card title={this.state.article.title} > <p>{this.state.article.content }</p> </Card> ) } }``` TypeError: Cannot read properties of undefined (reading 'params') Unabel to navigate to id can anyone help? i am working on react + django. My data from server in list is showing but when i try to navigate to particular data id it shows error -
How to add validators and constraints on Django admin form with bulk inline data
I have 3 simple Django models to create a reservation system class User(models.Model): first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) class Activity(models.Model): title = models.CharField(max_length=255) category = models.CharField(max_length=255) start_reservation = models.DateTimeField() end_reservation = models.DateTimeField() max_capacity = models.IntegerField() def clean(self): if self.start_reservation > self.end_reservation: raise ValidationError("Start date must be before end date") class Reservation(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) activity = models.ForeignKey(Activity, on_delete=models.CASCADE) class Meta: unique_together = ['user', 'activity'] My admin forms look like this @admin.register(User) class UserAdmin(admin.ModelAdmin): pass class ReservationAdmin(admin.TabularInline): model = Reservation extra = 0 @admin.register(Activity) class ActivityAdmin(admin.ModelAdmin): inlines = [ReservationAdmin] When I save an ActivityAdmin form, how can I ensure, that the number of reservations for a specific activity does not go over the max_capacity? I tried using the clean method on the reservation like this: class Reservation(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) activity = models.ForeignKey(Activity, on_delete=models.CASCADE) class Meta: unique_together = ['user', 'activity'] def clean(self): print(self.activity.reservation_set.count()) if self.activity.reservation_set.count() >= self.activity.max_capacity: raise ValidationError("Max capacity reached") But in the console, it prints the amount of reservations before any of the form data is saved to the DB. For example when I create a brand new activity (max_capactiy = 2) and I add 3 inline reservations, the console says: 0 0 0 even though … -
How to use import Geopackage data to my Django RESTful API?
I want to create a full-stack web application to let users query parks and greenspace in the UK, something like this: https://www.barnet.gov.uk/directories/parks. I want to build a Django RESTful API to query parks and greenspaces data. I am still a beginner and I am still learning. I have never imported large amounts of data to my app/database before. Usually, I manually input the data one by one for my RESTful APIS. This time, I don't want to manually input all the data. I want to build a project that is based on real-world data. Therefore, I found a public dataset for parks and greenspace (?), https://www.data.gov.uk/dataset/4c1fe120-a920-4f6d-bc41-8fd4586bd662/os-open-greenspace. I find it hard to understand what is the page about. I downloaded the Geopackage/gpkg file and I don't know how to use it. Here are some questions I have in mind: Is this the data I am looking for? Does the data contains info about the park, such as the park name? Or does it only store the geo location of the park? What I want to do is somehow transform this gpkg file into data I can play with in my Django RESTful API. And then I will write some API endpoints … -
django adding extra data to IntegerChoices
I need to add extra data to enum Class IntegerChoice in django. I have carefully read the answer here How to add extra data to TextChoices? but it does not seem to work. the definition of my enum type is : class FabricType (models.IntegerChoices): """an enumeration class with type, subclass and key words added first item is the code, second is translated verbose name, third is choice specific help, third is Group fourth is a list of keywords anychange in the number will require migration but adding new keywords will not """ CASTON = (1, _('Caston'), _('Basic'), []) JERSEY = (2, _('Jersey'), _('Basic'), []) TUBULAR = (3, _('Tubular'), _('Basic'), []) def __new__(cls, value, label, group, keywords, ): obj = int.__new__(cls, value) obj._value_ = value obj.group = group obj.keywords = keywords obj.help = help return obj def help_dict(cls): """help_dict for the FabricType""" help_dict = {'CASTON': _('the first few rows of a knit'), 'JERSEY': _('help_text'), 'TUBULAR': _('help text') return help_dict I have declared the EnumMixin as follows : class EnumMixin: ''' an Enum which Converts a DB value back to its Choices value''' def __init__(self, *args, enum=models.Choices, **kwargs): self.__enum = enum self.help_dict = kwargs.get('help_dict', None) kwargs.pop('help_dict', None) # it sets choices for … -
How to set the current proper date and time to "DateField()" and "TimeField()" respectively as a default value by "TIME_ZONE" in Django Models?
The doc says below in DateField.auto_now_add. *I use Django 4.2.1: Automatically set the field to now when the object is first created. ... If you want to be able to modify this field, set the following instead of auto_now_add=True: For DateField: default=date.today - from datetime.date.today() For DateTimeField: default=timezone.now - from django.utils.timezone.now() So, I set timezone.now and date.today to datetime's DateTimeField() and date1's DateField() respectively and I also set current_date which returns timezone.now().date() and current_time which returns timezone.now().time() to date2's DateField() and time's TimeField() respectively as shown below: # "models.py" from django.db import models from datetime import date from django.utils import timezone def current_date(): return timezone.now().date() def current_time(): return timezone.now().time() class MyModel(models.Model): datetime = models.DateTimeField(default=timezone.now) # Here date1 = models.DateField(default=date.today) # Here date2 = models.DateField(default=current_date) # Here time = models.TimeField(default=current_time) # Here Then, I set 'America/New_York' to TIME_ZONE in settings.py as shown below: # "settings.py" LANGUAGE_CODE = "en-us" TIME_ZONE = 'America/New_York' # Here USE_I18N = True USE_L10N = True USE_TZ = True But, date1's DateField() and time's TimeField() show UTC(+0 hours)'s date and time on Django Admin as shown below: Next, I set 'Asia/Tokyo' to TIME_ZONE in settings.py as shown below: # "settings.py" LANGUAGE_CODE = "en-us" TIME_ZONE = 'Asia/Tokyo' # Here … -
SyntaxError: Unexpected token '*' error when i try to load my javascript
i am getting this error SyntaxError: Unexpected token '*'. import call expects exactly one argument. when i load my javascript file in my django project. this is my code btw import * as THREE from 'three'; const scene = new THREE.Scene(); const camera = new THREE.PerspectiveCamera(75,window.innerWidth/window.innerHeight,0.1,1000); const renderer = new THREE.WebGLRenderer({ canvas: document.querySelector("#bg"), }); renderer.setPixelRatio(window.devicePixelRatio); renderer.setSize(window.innerWidth,window.innerHeight); camera.position.setZ(30); renderer.render(scene,camera); const geometry = new THREE.OctahedronGeometry(1,0); const color = new THREE.Color(134, 0, 255); const mat = new THREE.MeshBasicMaterial({color: color,wireframe: true}); const torus = new THREE.Mesh(geometry,mat); scene.add(torus); function animate(){ requestAnimationFrame(animate); renderer.render(scene,camera); } animate() i have already tried: looking if i have the correct javascript version that supports import i have and looking if i load the file correctly and triple checking if i have installed three correctly aswell. but for some reason it just does not work. -
IN DRF, how to create a POST serializer where I can add multiple values of a Foreign Key field
These are 2 models I have: class Skill(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name + " - ID: " + str(self.id) class Experience(models.Model): consultant = models.ForeignKey("Consultant", related_name="experience", on_delete=models.CASCADE) project_name = models.CharField(max_length=100) company = models.CharField(max_length=100) company_description = models.TextField(null=True, blank=True) from_date = models.DateField() to_date = models.DateField() project_description = models.CharField(max_length=100) contribution = models.TextField() summary = models.TextField() is_pinned = models.BooleanField(default=False) role = models.CharField(max_length=100, null=True) skill = models.ForeignKey("Skill", related_name="experience", on_delete=models.CASCADE) I want to do something that is quite common but apparently not possible out of the box with DRF: I want to have an endpoint /experience/ with a POST method where I can send a LIST of skill ids (skill field, ForeignKey). For example: { "project_name": "Project AVC", "company": "XYZ Company", "company_description": "Description of XYZ Company", "from_date": "2022-01-01", "to_date": "2022-12-31", "project_description": "Description of Project ABC", "contribution": "Contributions to Project ABC", "summary": "Summary of Experience", "is_pinned": false, "role": "Consultant", "skills_ids": [1,2,3], "consultant": 1 } If there are Skill records in the DB with ids 1,2,3 then it will create 3 records in the experience table (one for each skill ofc) . If there's no skill with such id, then during validation it should return an error to the user informing so. The name of the … -
i need help in django views and date
I'm new to Django and trying to do something here. Even if it is out of date, you cannot edit it because less than 1 hour is left. i get the error Thanks for your help. if shop.manager != user: messages.error(request, "You are not the manager.") return redirect('home') shop_datetime = timezone.make_aware(datetime.combine(shop.date, shop.hour)) if shop_datetime <= now: messages.error(request, "You cannot edit it because it is out of date.") return redirect('shopdetail', slug=slug) if last_edit_time >= now: messages.error(request, "You cannot edit this as there is less than 1 hour left.") return redirect('shopdetail', slug=slug) if request.method == "POST": form = ShopUpdateForm(request.POST, instance=shop) if form.is_valid(): if form.cleaned_data['date'].date() < date.today(): form.add_error('date', 'You cannot add anything to the previous date') else: etkinlik = form.save(commit=False) etkinlik.slug = slug etkinlik.save() return redirect('shopdetail', slug=slug) else: form = ShopUpdateForm(instance=shop) data = create_calendar(year, month) return render(request, 'shop/edit_shop.html', {'form': form, **data}) -
Search query when the search sentence is less than characters
Good afternoon. A question. How can such a search be implemented in Django ORM(or SQL query) There is an arbitrary table with the field name "description". There is one entry, and the value of the field "description" is python. How to formulate a database search query to get this record if the incoming sentence looks like this: python-is a great programming-language. Thank you. Requests of the form ` Entry.objects.get(headline__icontains="Lennon") are not suitable because there are fewer characters in the searched sentence -
Styles in css file not showing on html template
css not linking in django iam trying to create an ecommerce website for my project and made a css file and linked it to the base template. But those results are not to be seen. settings.py STATIC_URL = "static/" STATICFILES_DIRS = [ os.path.join(BASE_DIR,"static"),] Base template css linking <link rel="stylesheet" type="text/csss" href="{% static '/css/custom.css' %}"> CSS body{font-family: 'Roboto', sans-serif; background-color:#D3D3D3; } .text-center{ font-family:roboto; } .card-title{ font-weight:bold; font-family:'Roboto', sans-serif; } /*footer*/ .foot{ background-color:blue; position:fixed; bottom:0; left:0; height:10px; width:100%; } h2{ font-family:'roboto',sans-serif; } /*cart-icons*/ .custom_icon{ margin:7px; font-size:20px; color:blue; } /*invoice*/ .inv{ display:block; } urls.py from django.urls import path from cart import views app_name='cart' urlpatterns=[ path('cart_view',views.cart_view,name='cart_view'), path('add_cart/<int:p>',views.add_cart,name='add_cart'), path('add_cart/<int:p>',views.add_cart,name='add_cart'), path('minus/<int:p>',views.minus,name='minus'), path('delete/<int:p>',views.delete,name='delete'), path('order',views.order,name='order'), path('invoice',views.invoice,name='invoice'), ] I linked the css to base template, but not seeing any results, inline styling is working though. project structure -
Get value of a field from a foreigKey in Django Models
I have two classes in my Database in Django class Test(models.Model): sequenzaTest = models.ForeignKey("SequenzaMovimento", null=True, on_delete=models.SET_NULL) class SequenzaMovimento(models.Model): nomeSequenza = models.CharField(max_length=50, blank=False, null=False) serieDiMovimenti = models.TextField(blank=False, null=False, default="") Now, every Test object created can be associated with just one SequenzaMovimento object. Different Test objects can have the same SequenzaMovimento Now, I know the primary key of my Test. How do I find the serieDiMovimenti inside the SequenzaMovimento object which is linked to the Test object? I can get the sequenzaTest from the Test object with testo_sequenza = Test.objects.get(pk=idObj) testo_sequenza.sequenzaTest but I can't find to understand how access serieDiMovimenti -
Access json field's dict value which is inside list using queryset
I have django model named Blog with fields title, data class Blog(models.Model): title = models.CharField(max_length=100) data = models.JSONField(default=dict) I have about ten of instances with data field value like Instance 1 [ { "name": "random" } ] Instance 2 [ { "name": "fact" } ] Instance 3 [ { "name": "fact" } ] Instance 1 [ { "name": "random" } ] Instance 1 [ { "name": "random" } ] And I am trying to sort the the blogs based on data field name key is used, and show it like random, 3 fact, 2 and I am intending it to do it more efficiently with database functions. top_used_names = Blog.objects.annotate( name=RawSQL("REGEXP_REPLACE("data", '^.\*\\"name\\": \\"(.\*?)\\".\*$', '\\\\1')", params=\[\]) ).values('name').annotate( count=Count('name') ).order_by('-count')\[:5\] but It showed me errors. then I tried using top_used_names = Blog.objects.annotate( name=Cast(KeyTextTransform("name", "data"), output_field=TextField()) ).values("name") it also showed me errors. I have spent hours but it is still showing the error Any help would be much Appreicated. -
Dynamic django inline_formset using pure javascript
I was searching on working examples for django inline_formset with javascript and found this post Add a dynamic form to a django formset using javascript in a right way. In the process, I tried to convert the Jquery portion into pure javascript? I have tried const btnAddMoreImg = document.querySelector('#add-image-button'); btnAddMoreImg.addEventListener('click', (evt) => { evt.preventDefault(); let count = document.querySelector('#item-images').children.length; let tmplMarkup = document.querySelector('#images-template').innerHTML; let compiledTmpl = tmplMarkup.replace(/__prefix__/g, count); $('#item-images').append(compiledTmpl); // how to convert this to pure javascript? // update form count document.querySelector('#id_images-TOTAL_FORMS').setAttribute('value', count + 1); }) This works but there is still this jquery code $('#item-images').append(compiledTmpl) which I tried to change to document.querySelector('#item-images').append(compiledTmpl), but the end result would be a string of html tags instead of a new form added. -
Django - INTEGRITY ERROR on column that no longer exists
I am getting this error: IntegrityError at /register/ null value in column "total_daily_mission_progress" violates not-null constraint DETAIL: Failing row contains (363, 0, 374, free, 0, null, unranked, 0, , odifj@gmail.com, 0, f, [], 0, {}, {}, t, null, null, null, null, null, {}, null, null, No phone number set, This user has not set a description yet., /static/images/profilepictures/defaultavatar.png, {}, {}, {}, {}, {}, 0). However, the column total_daily_mission_progress no longer exists in my UserDetail model. I deleted it a while ago and migrated. However, this issue comes up every time I try to create a new UserDetail model. Why is this occuring? I don't have the total_daily_mission_progress anywhere in my code. And how can I fix it? EDIT: Here is my output after running python3 manage.py showmigrations --verbosity 2 [X] 0001_initial (applied at 2022-12-29 19:39:10) [X] 0002_logentry_remove_auto_add (applied at 2022-12-29 19:39:10) [X] 0003_logentry_add_action_flag_choices (applied at 2022-12-29 19:39:10) auth [X] 0001_initial (applied at 2022-12-29 19:39:09) [X] 0002_alter_permission_name_max_length (applied at 2022-12-29 19:39:11) [X] 0003_alter_user_email_max_length (applied at 2022-12-29 19:39:11) [X] 0004_alter_user_username_opts (applied at 2022-12-29 19:39:11) [X] 0005_alter_user_last_login_null (applied at 2022-12-29 19:39:12) [X] 0006_require_contenttypes_0002 (applied at 2022-12-29 19:39:12) [X] 0007_alter_validators_add_error_messages (applied at 2022-12-29 19:39:12) [X] 0008_alter_user_username_max_length (applied at 2022-12-29 19:39:12) [X] 0009_alter_user_last_name_max_length (applied at … -
Django Application not getting registered in admin site
I have created new application in Django project but it is not showing in admin page . I have updated the admin.py file as well I am looking for solution to get my app registered in admin page . I have tried everything I could find in google . admin.py file from django.contrib import admin # Register your models here. from .models import * admin.site.register(packagedrop) Modle class packagedrop(models.Model): pkgID = models.AutoField(primary_key=True) envname = models.CharField(max_length=64) CreatedDate = models.DateField(auto_now_add=True) product = models.CharField(max_length=64) prodhier = models.CharField( max_length=25) prodversion = models.CharField( max_length=40) initiator = models.CharField(max_length=100) Description = models.TextField(max_length=200) Status = models.CharField(max_length=100, default='Submitted' ) updated_time = models.DateTimeField(auto_now_add=True) -
Deploying Django Web App with GPU-Intensive Deep Learning Models?
What is the recommended approach for deploying my Django web application that includes multiple components (database, views, authentication) alongside GPU-intensive Deep learning models (e.g., deezer/spleeter and pyannote/speaker-diarization)? Should I deploy everything on a single server with a powerful GPU, or is it better to separate the deep learning models and deploy them on a dedicated server with a powerful GPU while deploying the web application on a traditional server (e.g., DigitalOcean, Heroku) within a Docker container, and then call the models from the web app? Please give me recommandations about the bests (cheapest) GPU servers providers. -
django: allow allowed_hosts to work with debug = True also
I have a requirement that my django app ALLOWED_HOSTS=["somedomain.com"] work when DEBUG=True Because it only works for DEBUG=False Can anyone suggest how to achieve this. -
Why django-social-auth in djoser don't find client_id in authorization_url if client_id is provided
Why django-social-auth in djoser don't find client_id in authorization_url if client_id is provided I trying authenticate user with djoser + django-social-auth(front: Vue, back: django). When I request to http://127.0.0.1:8000/auth/o/google-oauth2?redirect_uri=http://localhost:8080, url response with client_id=None in authorization_url. Here are my settings and response. AUTHENTICATION_BACKENDS = [ 'fapp.auth_backend.AuthWithEmailAndPasswordOnly', 'social_core.backends.google.GoogleOAuth2', ] DJOSER = { 'PASSWORD_RESET_CONFIRM_URL': '#/password/reset/confirm/{uid}/{token}', 'USERNAME_RESET_CONFIRM_URL': '#/username/reset/confirm/{uid}/{token}', 'ACTIVATION_URL': '#/activate/{uid}/{token}', 'SOCIAL_AUTH_ALLOWED_REDIRECT_URIS': [ 'http://localhost:8080', 'http://localhost:8000' ], 'SOCIAL_AUTH_GOOGLE_OAUTH2_CLIENT_ID': '***' } And response "authorization_url": "https://accounts.google.com/o/oauth2/auth?client_id=None&redirect_uri=http://localhost:8080&state=dpcVJ92tDbxvxMvmn4m3wiCOTw5b0Pcx&response_type=code&scope=openid+email+profile" After this response I tried go to authorization_url with changed client_id to SOCIAL_AUTH_GOOGLE_OAUTH2_CLIENT_ID and it's work fine. -
How to filter data on many to many fields and apply ANY and OR operators in Django
I have 3 Models defined in my code Day, AllocationType and EmployeeAllocation. I am trying to solve a problem for following scenarios. Scenario 1: If person A is allocated to project P1 from 01-06-2023 to 30-06-2023 for dyas M,T,W,T,F. If end user try to allocate person A in that date period or days then end user should get a validation error. Person A is allocated. Scenario 2 If person B is allocated to project P2 from 01-06-2023 to 30-06-2023 for days M,W,F. If end user try to allocated person B than end user should able to allocated Person B between 01-06-2023 and 30-06-2023 for days T,T. I am novice in Django and not able to figure out how to write a condition for checking above scenarios. Model Definitions class Day(models.Model): Name = models.CharField(max_length=10) def __str__(self): return self.Name class AllocationType(models.Model): Name = models.CharField(max_length = 100) ColorCode = models.CharField(max_length = 50) def __str__(self): return self.Name class EmployeeAllocation(models.Model): Employee= models.ForeignKey(Employee, null=False, on_delete= MY_PROTECT, related_name='employee_allocation') Project= models.ForeignKey(Project, null=False, on_delete=MY_PROTECT, related_name='employe_allocation_project') AllocationType = models.ForeignKey(AllocationType, null=False, on_delete=MY_PROTECT, related_name="employee_allocation_type") StartDate = models.DateField() EndDate = models.DateField() Days = models.ManyToManyField(Day, null=False, blank=False, related_name='emoloyee_allocation_day') Comments = models.CharField(max_length=200, null=True, blank=True) def get_absolute_url(self): return reverse('employee-allocation-list') def __str__(self): return self.Employee.FirstName -
How to filter Django ManyToManyField by Id
I have two models: class Category(models.Model): name = models.CharField(max_length=255) class Company(models.Model): name = models.CharField(max_length=255) category = models.ManyToManyField(Category, related_name='companies') products = models.TextField() bulletpoints = models.TextField() website = models.CharField(max_length=750) articles = models.TextField() Now I want to filter the Objects in the Company model by the id of the categories, which I put them in. I tried several options including everything from that question: https://stackoverflow.com/questions/2218327/django-manytomany-filter for example: Company.objects.filter(companies__in=[category_id]) Company.objects.filter(companies__id=category_id) Company.objects.filter(category_id=category_id) Company.objects.filter(companies__id__in=category_id) -
Prefetch and merge two reverse foreign key of same model in queryset
I have a problem, maybe somone has a solution for me. I have two models: class Task(models.Model): class Meta: db_table = "task" class Rule(models.Model): to_task = models.ForeingKey(Task, related_name="to_task_rules") from_task = models.ForeignKey(Task, related_name="from_task_rules") class Meta: db_table = "rule" I want to loop into tasks and display all concerned distinct rules by current task by prefetching to_task_rules and from_task_rules in a field task_rules, but without success Django does not seems to provide way to do that. I try to make prefetch with to_attr="task_rules", but, we cannot use twice same name. # This solution does not work. to_attr cannot be have same name twice. # In this case, i do not known how filter for having distinct results Task.objects.prefetch( Prefetch("from_task_rule", queryset=Rule.objects.all(), to_attr="task_rules"), Prefetch("to_task_rule", queryset=Rule.objects.filter(...), to_attr="task_rules") ) Anybody have an idea, excluded to prefetch during loop for preventing N+1 query ? Thanks -
What are alternative options for configuring Postfix for sending newsletter emails through Django?
I am trying to send a newsletter from my site. On average, 500 emails should be sent per mailing list. I'm trying to set up Postfix to do this and send emails through it. smtpd_relay_restrictions = permit_mynetworks permit_sasl_authenticated defer_unauth_destination myhostname = example.com alias_maps = hash:/etc/aliases alias_database = hash:/etc/aliases mydomain = example.com myorigin = $mydomain mydestination = www.$mydomain, $myhostname, localhost.localdomain, localhost, localhost.$mydomain, $mydomain relayhost = mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128 mailbox_size_limit = 0 recipient_delimiter = + inet_interfaces = loopback-only inet_protocols = all milter_default_action = accept milter_protocol = 2 smtpd_milters = inet:127.0.0.1:8891 non_smtpd_milters = inet:127.0.0.1:8891 I want to send emails using django. And I use postfix mailing user, but when I try to send an email, nothing happens. EMAIL_HOST = 'localhost' EMAIL_PORT = 25 EMAIL_HOST_USER = 'mailing@example.com' EMAIL_HOST_PASSWORD = '******' EMAIL_USE_TLS = True EMAIL_USE_SSL = False SERVER_EMAIL = 'mailing@example.com' DEFAULT_FROM_EMAIL = 'mailing@example.com' What am I doing wrong and how to fix it? Or maybe there are alternative options for my task, thanks in advance. Set up postfix to send emails using Django. The error does not occur, but the letters do not come. -
Module 'projectname' has no attribute 'celery'
I want to call a url after a hour so I added celery and with the help of ChatGPT I did upto here taskapp/tasks.py (Newly Created but not registered in settings.py told by ChatGPT) from celery import shared_task import requests @shared_task def call_url_task(): # Perform the task you want to execute every hour response = requests.get("https://myurl.com") # Replace with your desired URL # Process the response or perform any other actions if needed if response.status_code == 200: print("URL called successfully.") and Here's my views.py of actual app starting lines from taskapp.tasks import call_url_task from celery.schedules import crontab from celery.task import periodic_task @periodic_task(run_every=crontab(minute='*')) def schedule_task(): call_url_task.delay() # Call the task asynchronously using delay() settings.py from celery import Celery app = Celery('projectname') app.config_from_object('django.conf:settings', namespace='CELERY') ... CELERY_BROKER_URL = 'redis://localhost:6379' CELERY_RESULT_BACKEND = 'redis://localhost:6379' Error I am facing: $ celery -A projetname worker --loglevel=info Usage: celery [OPTIONS] COMMAND [ARGS]... Try 'celery --help' for help. Error: Invalid value for '-A' / '--app': Unable to load celery application. Module 'projectname' has no attribute 'celery' I tried checking the installation of Redis and Celery and they are installed already. I couldn't find solution for my problem on ChatGPT even. Have I done something wrong? I have also seen … -
Django model constrains
I am trying to create an Asset management system and the model AssetLog is responsible of making sure that a user is assigned to a single computer and a computer is assigned to a single user. And i have managed to set that up but now, Trying to update an object from current to previous is now not allowing me to do so even using the Django Admin panel class AssetLog(models.Model): Used = "U" Previous = "P" Current = "C" status_choices = [ (Used, "Used"), (Previous, "Previous"), (Current, "Current"), ] status = models.CharField( max_length=1, choices= status_choices, default=Current, ) user_id = models.ForeignKey(Account,on_delete=models.CASCADE) asset_num = models.ForeignKey(Computer,on_delete=models.CASCADE) allocated_on = models.DateTimeField(auto_now_add=True) updated_on = models.DateTimeField(auto_now=True) Location = models.ForeignKey(Location,on_delete=models.CASCADE) def clean(self): # Checking if the user and the computer have been logged a = AssetLog.objects.filter(Q(asset_num=self.asset_num) & Q(user_id=self.user_id)).exists() b = AssetLog.objects.filter(Q(asset_num=self.asset_num)).exists() c = AssetLog.objects.filter(Q(user_id=self.user_id)).exists() try: if a: computer = AssetLog.objects.get(asset_num=self.asset_num) if computer.status == 'C': msg = 'The Asset is being used by- ' + computer.user_id.first_name raise ValidationError(msg) elif b: computer = AssetLog.objects.get(asset_num=self.asset_num) if computer.status == 'C': msg = 'The Asset is being used by- ' + computer.user_id.first_name raise ValidationError(msg) elif c: computer = AssetLog.objects.get(user_id=self.user_id) if computer.status == 'C': msg = 'The User has a machine allocated to …