Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Web Socket is working in local but not in production
I develop a web app using django channels. It is working properly in local but not in production. here is my configurations. I didn't know what I'm missing. project.service asgi.py here is nginx configurations. upstream channels-backend { server 127.0.0.1:9001; } server { listen 80; server_name edseedwhiteboard.yarshatech.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/sandeep/EdSeed_WhiteBoard; } location /media/ { root /home/sandeep/EdSeed_WhiteBoard; } location /ws/ { proxy_pass http://channels-backend; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection “upgrade”; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; } location / { include proxy_params; proxy_pass http://unix:/run/whiteboard.sock; } } and here is actual error after depoyed. -
Django Save Multiple Objects At Once
I have been practicing Django for a while now. Currently I am using it in a project where I'm fetching Facebook data via GET requests and then saving it to an sqlite database using Django models. I would like to know how can I improve the following code and save a list of Facebook posts and their metrics efficiently. In my current situation, I am using a for loop to iterate on a list containing several Facebook Posts and their respective metrics which is then associated to the specific Django model and finally saved. def save_post(post_id, page_id): facebook_post = Post(post_id=post_id, access_token=fb_access_token) post_db = PostsModel(page_id=page_id, post_id=post.post_id) post_db.message = facebook_post.message post_db.story = facebook_post.story post_db.full_picture = facebook_post.full_picture post_db.reactions_count = facebook_post.reactions_count post_db.comments_count = facebook_post.comments_count post_db.shares_count = facebook_post.shares_count post_db.interactions_count = facebook_post.interactions_count post_db.created_time = facebook_post.created_time post_db.published = facebook_post.published post_db.attachment_title = facebook_post.attachment_title post_db.attachment_description = facebook_post.attachment_description post_db.attachment_target_url = facebook_post.attachment_target_url post_db.save() post_db is a Django model object instantiated using PostsModel while Post is a normal Python Class which I wrote. The latter is simply a collection of GET requests which fetches data from Facebook's Graph API and returns JSON data whereby I associate relevant data to class attributes (message, 'shares_count`). I read about the bulk_create function from Django's documentation … -
How can I receive the recorded file with django?
I record the audio file by using 'XMLHttpRequest' recorder in javascript. (record, save and upload are done) I changed this file into blob and sent to server. I tried to check it with django but it was empty {}. How can I receive the recorded file with django? -
How to change admin panel pages separately for each model?
I need to add on the root model page (not a page for record editing) some fields for editing records in other models and the save button to save them. For example This fields going to save data in tables with one record limitation so each field will save data to specified record in specified model. This is only example. So how to make custom editions on model pages in admin panel? Is it possible? -
can something happen like changing the parameters of django model fields according to conditions changing parametrs of timefield
Iam working on a project and I have the following model : class Meeting(models.Model): topic = models.CharField(max_length=200, null=True) subject = models.ForeignKey(Subject, on_delete=models.SET_NULL, null=True) date = models.DateField(default=date.today, null=True) STATUS = ( ('Incomplete', 'Incomplete'), ('Concluded', 'Concluded'), ('Deleted', 'Deleted') ) STD = ( ('8', '8'), ('9', '9'), ('10', '10') ) std = models.CharField(max_length=3, choices=STD, null=True) link = models.URLField(max_length=500, null=True) status = models.CharField(max_length=40, null=True, choices=STATUS, default="Incomplete") participents = models.ManyToManyField(Student, blank=True) time = models.TimeField(auto_now_add=False, null=True) def __str__(self): return self.topic so what I want is if a user is trying to edit a meeting , the date should not be added by default , but the user should select it , and if the user creates meeting then by default todays date should be added . my views.py function for updating meeting: @allowed_users(allowed_roles=['Teachers']) def upd_meeting(request, id): meeting = Meeting.objects.get(id=id) form = MeetingCreationForm(instance=meeting) if request.method == "POST": form = MeetingCreationForm(request.POST, instance=meeting) print(request.POST["topic"]) if form.is_valid(): form.save() return redirect('dashboard_pg') else: return HttpResponse("Something went wrong pls try again") context = {'form': form} return render(request, 'main/crt_meeting.html', context) my forms.py file : class MeetingCreationForm(ModelForm): date = forms.DateField() class Meta: model = Meeting fields = ['topic', 'subject', 'std', 'link', 'time', 'date'] -
CSS files not updating on Heroku
Hi, i am running a Django webapp on a Heroku dyno. My problem is the following one: Sometimes, CSS files are not updated after deploy. They are updated on the GitHub repo, but not in the server. I have manually checked them using:heroku run bash -a myapp**, and the code is different from github (I am sure that I checked the deployed branch), they remain in older versions. Static files are served correctly, i do not get any 404 and it only happens with CSS files. I have tried `heroku restart -a myapp`, but it does not work. If I rename the files, the problem is solved, but as you can imagine this is not a viable solution. I use the GitHub deploy method, so I do the add, commit, push cycle and then i manually select and deploy the branch from the heroku dashboard. Does anyone know how can i solve this without changing files' names? Thanks! -
How to I make my review model form show the name of the current user when rendered in template
I am trying yo create a review form in django. I have rendered the form but I would like the form to display the name of the current logged in user. To enable me associate each review with a user. here is my model: class Review(models.Model): company = models.ForeignKey(Company, null=True, on_delete=models.SET_NULL) # SET_NULL ensures that when a company is deleted, their reviews remains reviewers_name = models.CharField(max_length=250, verbose_name='Reviewed By: (Your Name)') review_text = models.TextField(max_length=500, verbose_name='Your Review: (Maximum of 200 Words)') rating = Int_max.IntegerRangeField(min_value=1, max_value=5) date_added = models.DateField('Review Date', auto_now_add=True) Here is my view: def submit_review(request): form = ReviewForm() if request.method == 'POST': form = ReviewForm(request.POST) if form.is_valid: form.save() # gets the company that was immediately submitted in the review form company = request.POST.get('company') # gets the rating that was immediately submitted in the review form rating = request.POST.get('rating') # uses the name of the company submitted to instantiate the company from the Company database companyone = Company.objects.get(pk=company) """ emloys companyone above to retrieve already existing average rating associated with it adds this to the current rating sent by the user and stores the total back to the average rating field of companyone """ companyone.average_rating = round((int(rating) + int(companyone.average_rating))/2) companyone.save() return redirect('review-submitted') … -
Django error when using mysql-connector-python
I want to set the mysql database using mysql-connector-python for setting up a web site made with Django using a database backend but I get this error: django.core.exceptions.ImproperlyConfigured: 'mysql.connector.django' isn't an available database backend. Try using 'django.db.backends.XXX', where XXX is one of: 'mysql', 'oracle', 'postgresql', 'sqlite3' My credentials (name, user, password, host, port) works fine, so the problem isn't here. DATABASES = { 'default': { 'ENGINE': 'mysql.connector.django', 'NAME': 'library', 'USER': 'username', 'PASSWORD': 'password', 'HOST': '127.0.0.1', 'PORT': '3306', 'OPTIONS': { 'autocommit': True, 'use_pure': True, }, } } I'm using python 3.8.5 and mysql-connector-python 8.0.21 and I understand that mysql-connector-python, starting from version 8.0.13, has a bug, which makes it impossible to use with Django and to avoid the bug I added ‘use_pure’: True in database options. But it doesn't work. I found this question but it doesn't say anything about using ‘use_pure’: True. If the mysql-connector-python isn't compatible with python 3, what can I use instead? (I can't wait for the support release). -
Django - Disable Foreign key constraints is failing
For some reasons I am trying to temporarily disable foreign key constrains check on MySQL. It is forced and enabled by default by django. Trying to disable it manually fails with syntax error as below. Python 3.6/Django2.2 (Pdb) cursor.db.cursor().execute("SET FOREIGN_KEY_CHECKS=0;") *** django.db.utils.OperationalError: near "SET": syntax error I saw different posts using the above command and that it should work. Any help or pointer for what I am missing will be very helpful. -
django view dont show anything
I'm working to create an event page in my Django work. Although I wrote a code to obtain database data when I try to load the front page(from exhibition_view.html), just the exhibition.view_html loads and no article return and does not show in that page. the weird thing is that seminar_view and exhibition_view are the same, and seminar_view does work! I tried very much to solve the issue, but had no idea what is happening! below is my code: Model.py from django.db import models from django.utils import timezone from tinymce.models import HTMLField class EventType(models.Model): name = models.CharField(max_length=20) def __str__(self): return self.name class Meta: verbose_name_plural = "Event Types" def get_deleted_event_type(): return EventType.objects.get(name='no-category') class Event(models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) EVENT_CHOICES = ( ('seminar', 'seminar'), ('exhibition', 'exhibition'), ) title = models.CharField(max_length=255) slug = models.SlugField(max_length=250, unique_for_date='publish', allow_unicode=True, unique=True) body = HTMLField() publish = models.DateTimeField(default=timezone.now) created_on = models.DateTimeField(auto_now_add=True) last_modified = models.DateTimeField(auto_now=True) events = models.ForeignKey(EventType, on_delete=models.SET(get_deleted_event_type)) event_type = models.CharField(max_length=15, choices=EVENT_CHOICES, default='seminar') status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft') event_index = models.IntegerField() class Meta: ordering = ('-publish',) verbose_name_plural = "Events" def __str__(self): return self.title Views.py from django.shortcuts import render from .models import Event from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from django.db.models import Q def seminar_detail(request, slug): … -
'Department' object is not iterable in Django?
I coundn't find the mistakes here. Department's objects and Year's objects are already created inside admin panel. So the field department and years in ClassForm should be rendered as CharField with choices. Why when I submitted the form I got the error? class Department(models.Model): name = models.CharField(max_length=100) class Year(models.Model): department = models.ManyToManyField(Department) years = models.CharField(max_length=20) class Class(models.Model): teacher = models.ForeignKey("account.CustomUser", on_delete=models.CASCADE) department = models.ForeignKey(Department, on_delete=models.CASCADE) years = models.ForeignKey(Year, on_delete=models.CASCADE) subject = models.CharField(max_length=200, unique=True) # forms.py class ClassForm(forms.ModelForm): class Meta: model = Class fields = ['department', 'years', 'subject'] #view.py def createClassView(request): if request.method == "POST": form = app_forms.ClassForm(request.POST, instance=request.user) if form.is_valid(): form.save() return JsonResponse({'success': True}, status=200) else: return JsonResponse({'error': form.errors}, status=400) return HttpResponse("Class Create View") error I got Traceback (most recent call last): File "/Users/muongkimhong/Developments/itc-attendance/env/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/Users/muongkimhong/Developments/itc-attendance/env/lib/python3.8/site-packages/django/core/handlers/base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/muongkimhong/Developments/itc-attendance/env/lib/python3.8/site-packages/django/contrib/auth/decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "/Users/muongkimhong/Developments/itc-attendance/attendance/app/views.py", line 63, in createClassView form.save() File "/Users/muongkimhong/Developments/itc-attendance/env/lib/python3.8/site-packages/django/forms/models.py", line 461, in save self._save_m2m() File "/Users/muongkimhong/Developments/itc-attendance/env/lib/python3.8/site-packages/django/forms/models.py", line 443, in _save_m2m f.save_form_data(self.instance, cleaned_data[f.name]) File "/Users/muongkimhong/Developments/itc-attendance/env/lib/python3.8/site-packages/django/db/models/fields/related.py", line 1670, in save_form_data getattr(instance, self.attname).set(data) File "/Users/muongkimhong/Developments/itc-attendance/env/lib/python3.8/site-packages/django/db/models/fields/related_descriptors.py", line 992, in set objs = tuple(objs) TypeError: 'Department' object is not iterable -
How can I resolve the argument of type 'WindowsPath' is not iterable in django? not opening any pdf or csv files
'''Traceback (most recent call last): File "C:\Users\Hassam Chaudhary\AppData\Local\Programs\Python\Python37\lib\wsgiref\handlers.py", line 138, in run self.finish_response() File "C:\Users\Hassam Chaudhary\AppData\Local\Programs\Python\Python37\lib\wsgiref\handlers.py", line 196, in finish_response self.close() File "C:\Users\Hassam Chaudhary\AppData\Local\Programs\Python\Python37\lib\site- packages\django\core\servers\basehttp.py", line 111, in close super().close() File "C:\Users\Hassam Chaudhary\AppData\Local\Programs\Python\Python37\lib\wsgiref\simple_server.py", line 38, in close SimpleHandler.close(self) File "C:\Users\Hassam Chaudhary\AppData\Local\Programs\Python\Python37\lib\wsgiref\handlers.py", line 334, in close self.result.close() File "C:\Users\Hassam Chaudhary\AppData\Local\Programs\Python\Python37\lib\site- packages\django\http\response.py", line 252, in close signals.request_finished.send(sender=self._handler_class) File "C:\Users\Hassam Chaudhary\AppData\Local\Programs\Python\Python37\lib\site- packages\django\dispatch\dispatcher.py", line 175, in send for receiver in self._live_receivers(sender) File "C:\Users\Hassam Chaudhary\AppData\Local\Programs\Python\Python37\lib\site- packages\django\dispatch\dispatcher.py", line 175, in <listcomp> for receiver in self._live_receivers(sender) File "C:\Users\Hassam Chaudhary\AppData\Local\Programs\Python\Python37\lib\site- packages\django\db\__init__.py", line 57, in close_old_connections conn.close_if_unusable_or_obsolete() File "C:\Users\Hassam Chaudhary\AppData\Local\Programs\Python\Python37\lib\site- packages\django\db\backends\base\base.py", line 514, in close_if_unusable_or_obsolete self.close() File "C:\Users\Hassam Chaudhary\AppData\Local\Programs\Python\Python37\lib\site- packages\django\db\backends\sqlite3\base.py", line 248, in close if not self.is_in_memory_db(): File "C:\Users\Hassam Chaudhary\AppData\Local\Programs\Python\Python37\lib\site- packages\django\db\backends\sqlite3\base.py", line 367, in is_in_memory_db return self.creation.is_in_memory_db(self.settings_dict['NAME']) File "C:\Users\Hassam Chaudhary\AppData\Local\Programs\Python\Python37\lib\site- packages\django\db\backends\sqlite3\creation.py", line 12, in is_in_memory_db return database_name == ':memory:' or 'mode=memory' in database_name TypeError: argument of type 'WindowsPath' is not iterable [24/Sep/2020 04:10:17] "GET / HTTP/1.1" 500 59 I tried almost all ways that are saved in this site even 10-year-old post tried. But still, the error remains the same. I am not using any file to open on python or on a web app but still facing this error. -
Cannot check multiple lines string in django
I actually want to check the answer from user is correct or incorrect. When I tried in dummy data with pure python code, it work properly. But, when I try to add it into django, it doesn't valid. I also tried 3 methods anyway, but still doesn't work. In my mind, perhaps because \n issue. class UserAnswerView(APIView): allowed_methods = ('post',) permission_classes = (permissions.AllowAny,) # just for test serializer_class = UserAnswerSerializer def validate_answer(self, exercise_id, user_answer): exercise = Exercise.objects.get_or_none(id=exercise_id) if exercise and user_answer: if isinstance(user_answer, str): correct_answers = exercise.answer_set.published() # [method 1] # return correct_answers.filter(Q(answer__icontains=user_answer)).exists() # [method 2] # for correct_answer in correct_answers: # if correct_answer.answer in user_answer: # return True # [method 3] return any(c.answer in user_answer for c in correct_answers) return False Here is the models.py; class Exercise(TimeStampedModel): id = models.BigAutoField(primary_key=True) title = models.CharField(_('Title'), max_length=200) order = models.PositiveIntegerField(_('Order'), default=1) course = models.ForeignKey(Course, on_delete=models.CASCADE) sort_description = models.TextField(_('Sort Description')) description = models.TextField(_('Description')) initial_script = models.TextField(_('Initial Script'), blank=True) objects = CustomManager() def __str__(self): return self.title class Answer(TimeStampedModel): id = models.BigAutoField(primary_key=True) exercise = models.ForeignKey(Exercise, on_delete=models.CASCADE) answer = models.TextField(_('Answer'), help_text=_('The correct answer')) objects = CustomManager() def __str__(self): return self.answer[:50] In my test, I put this codes into the user_answer form and also correct_answer. from datetime … -
Change the text on Django Admin's "Add another SomeObject"-button when showing inlines
With the following code, I get a Django Admin UI, where I on the Person page can add a number of Measurement's. The link / button shows the text "Add another Measurement". How can I change that text? class Person(models.Model): class Meta: db_table = 'people' verbose_name = "Person" verbose_name_plural = "People" name = models.CharField(max_length=100, null=False, blank=False) class Measurement(models.Model): class Meta: db_table = 'measurements' verbose_name = "Measurement" verbose_name_plural = "Measurements" value = models.IntegerField(null=False) person = models.ForeignKey(Person, null=False, on_delete=CASCADE) class MeasurementInline(InlineModelAdmin): model = Measurement extra = 0 class PersonAdmin(admin.ModelAdmin): fields = ('name',) list_display = ('name',) inlines = [MeasurementInline] -
Convert into lower case while saving in database Django
I am adding few names in my database using the admin panel. How can I convert the the name string to lowercase before saving? -
How can I use select_related in case like this?
I have this models class Person(models.Model): name = models.CharField() ... class Names(models.Model): person = models.ForeignKey(Person) .... class Address(models.Model): person = models.ForeignKey(Person) .... class Occupation(models.Model): person = models.ForeignKey(Person) .... I want to fetch data by join all tables but i keep get error.. any help please? -
How to use related_query_name in GenericRelation as you would use related_name in ManyToManyField?
I am trying to implement a Django tagging system using a GenericRelation instead of a ManyToManyField. My Tag model is defined as follows: class Tag(models.Model): tag = models.SlugField() content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() tagged_object = GenericForeignKey() Since in my app I am tagging Definitions, my Definition model has a GenericRelation to the Tag model described above as follows: class Definition(models.Model): ... tags = GenericRelation(Tag, related_query_name="definition") Now, I am trying to query my database to get all the Definitions tagged with a certain Tag. If I used a ManyToManyField for tags in my Definition model and included a related_name of, say, "tag_definitions" I would have been able to achieve that like so: tag.tag_definitions.all() Because I am using GenericRelation, however, this is not possible. How can I achieve this using related_query_name? -
How to use different css for queryset objects?
I have different styles of heading in a 5- column layout newspaper template. I want to apply different css to the title of each column. The queryset is the {% block content %}How can I iterate over the queryset objects and apply different css to each {{ post.title }} variable? <div class="content"> <div class="collumns"> {% block content %} {% endblock %} </div> <div class="collumn"><div class="head"><span class="headline hl1">May the Force be with you</span><p><span class="headline hl2">Let go your conscious self and act on instinct</span></p> </div> -
AttributeError: 'set' object has no attribute 'items' in django
I am customizing in the DRF to give an error response value if a null value is entered in the body or title. However, after squeezing the code, the test results in the following error. AttributeError: 'set' object has no attribute 'items' I don't know what this error means, and I don't know why it happens. Can you tell me what the problem is in my code? Here's my code. views.py class CreatePostView (ModelViewSet) : serializer_class = PostSerializer permission_classes = [IsAuthenticated] queryset = Post.objects.all() serializers.py class PostSerializer (serializers.ModelSerializer) : author = serializers.CharField(source='author.username', read_only=True) title = serializers.CharField(allow_null=True) text = serializers.CharField(allow_null=True) image = ImageSerializer(many=True) class Meta: model = Post fields = ['pk', 'author', 'title', 'text', 'like', 'liker', 'image', 'view'] def validate (self, attrs) : title = attrs.get('title', '') text = attrs.get('text', '') error = {} if title is None and text is None : error['message'] = '제목과 본문을 넣어주세요.' raise serializers.ValidationError(error) if title is None : error['message'] = '제목을 넣어주세요.' raise serializers.ValidationError(error) if text is None : error['message'] = '본문을 넣어주세요.' raise serializers.ValidationError(error) return attrs def create (self, validated_data) : return Post.objects.create(**validated_data) -
Nuxt Axios works only during deploy
I've recently made a blog where I post things but I found one little problem. I'm using Nuxt With Axios as frontend and Django as backend hosted on heroku. The thing is, when I run the frontend on my localhost everything works like a charm. No error, no cors problem. Everything simply goes as expected until I deploy the frontend to Netlify. From there it goes weird. The Axios seems to work only during the deploy phase and doesn't update anything that goes afterwards. For Better image: Imagine your site is up With some Posts and you decide to put another post in Django. This post is simply ignored by the website and doesnt show up. There is also no error in the console. But once I redeploy the site, it magically loads it. Im really lost. If anyone knows how to solve this I'd be really grateful. Writing on phone so sorry for styling if it sucks. I'll post code later -
Django test without vpn
I want to test my function, where I add a new object to a database and then (still in this function) the object is being sent to a server. The problem is that to send the object to a server I need to run VPN. I'm wondering is there a way to run this function in my test, but skip the line responsible for sending the object to the server, or somehow simulate this behavior? Currently, I'm not able to run my test because I'm getting Failed to establish a new connection: [Errno 110] Connection timed out My test looks like this: def test_create_ticket_POST_adds_new_ticket(self): response = self.client.post(self.create_ticket_url, { 'title': 'test title', 'description': 'test description', 'grant_id': 'test grant id', }) result_title = Ticket.objects.filter(owner=self.user).order_by('-last_update').first().title result_count = Ticket.objects.filter(owner=self.user).count() self.assertEquals(response.status_code, 302) self.assertEquals(result_title, 'test title') self.assertEquals(result_count, 1) And the post request is calling this function: @login_required @transaction.atomic def create_ticket(request): if request.method == 'POST': ticket_form = TicketForm(request.POST) tags_form = TagsForm(request.POST) attachments = AttachmentForm(request.POST, request.FILES) if ticket_form.is_valid() and attachments.is_valid() and tags_form.is_valid(): jira = JIRA(server=JIRA_URL, basic_auth=(jira_user, jira_password)) new_issue = add_issue(request, jira, ticket_form) add_attachments(request, jira, new_issue) set_tags(request, new_issue, tags_form) messages.info(request, _(f"Ticket {new_issue} has been created.")) return redirect(f'/tickets/{new_issue}/') else: ticket_form = TicketForm() tags_form = TagsForm() attachments = AttachmentForm(request.POST, request.FILES) return … -
i want to add custom field in django-allauth SignupForm
i wanted to add custom field with django-allauth SingupForm and adding new field like phone number. i already managed to add this field in Postgresql on my own(without migrations,but by my hands). this is my postgresql screen In my signup page i have these fields already but i can't managed to add "phone" to my database, i really want to make it! please someone help me. forms.py from allauth.account.forms import SignupForm from django import forms class CustomSignupForm(SignupForm): first_name = forms.CharField(max_length=30, label='Voornaam') last_name = forms.CharField(max_length=30, label='Achternaam') phone = forms.CharField(max_length=30, label='phone') def __init__(self, *args, **kwargs): super(CustomSignupForm, self).__init__(*args, **kwargs) self.fields['first_name'] = forms.CharField(required=True) self.fields['last_name'] = forms.CharField(required=True) self.fields['phone'] = forms.CharField(required=True) def save(self, request): user = super(CustomSignupForm, self).save(request) user.phone = self.cleaned_data.get('phone') user.save() return user def signup(self,request,user): user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.save() return user settings.py ACCOUNT_FORMS = {'signup': 'registration.forms.CustomSignupForm'} -
SMTPAuthenticationError at /
Iam trying to send an email with my django app to my email. and its firing the above error. my Login credentials in my settings are correct and i have turned on less secure apps and DisplayUnlockCaptcha but it still persists. nvironment: Request Method: POST Request URL: http://localhost:8000/ Django Version: 3.0.9 Python Version: 3.8.3 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'shield_sec'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/apple/projects/Django/ingabo_sec/shield_sec/views.py", line 17, in contact send_mail ( File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/mail/__init__.py", line 60, in send_mail return mail.send() File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/mail/message.py", line 284, in send return self.get_connection(fail_silently).send_messages([self]) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/mail/backends/smtp.py", line 102, in send_messages new_conn_created = self.open() File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/mail/backends/smtp.py", line 69, in open self.connection.login(self.username, self.password) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/smtplib.py", line 734, in login raise last_exception File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/smtplib.py", line 723, in login (code, resp) = self.auth( File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/smtplib.py", line 646, in auth raise SMTPAuthenticationError(code, resp) Exception Type: SMTPAuthenticationError at / Exception Value: (535, b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8 https://support.google.com/mail/?p=BadCredentials 138sm1136246lfl.241 - gs settings.py STATIC_URL = '/static/' … -
how to filter spetember in datefield django?
Hope You Are Good I Have This Model: class Task(models.Model): .... timestamp = models.DateField(auto_now_add=True) now I want to get only September tasks not matter what date is, I want to filter or grep September 2020 tasks how can I achieve this? -
Django - import constants's variable from variable
I've a Django application and I'd like to import from myapp.constants the MYCONSTANT variable in a way that myapp and MYCONSTANT is stored in a variable: VAR1='myapp' VAR2='MYCONSTANT' and I'd like to import it using the variables. from VAR1.constants import VAR2 , but of course it does not work. How can I achieve this? Is there any similar way to using apps.get_model() ?