Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can i send my template values to database using Jquery, Ajax in django?
1.jquery $(textbox).on('click','.save',function(e){ e.preventDefault(); var x = $('#input_msg').val(); $.ajax({ url:'newpostx/', type: $(this).attr('method'), data: x, headers:{ 'X-CSRFToken':'{{csrf_token}}' } }).done(function(msg) { document.location = "http://127.0.0.1:8000/newpostx/" alert("save data") }).fail(function(err){ alert('no data was saved') }) }); home.html $(container).on('click','.show', function () { //On click of link, textbox will open console.log(count[1]) msg_bubble = 1; $("div.popup").show(); var num = $(this).attr('value'); console.log(num,'num') $(textbox).append('Grid No_ '+ num +'Bot MessagesType any text here Add Message BubbleSelect InputText InputButtonsStar RatingsCalendar & TimeImage/File InputSelect User Input: Name -->Type Input:File UploadTake PhotoFile Upload & Take PhotoButton Add ButtonNumber of stars:345Steps in stars:0.51Type Input:NameFull NameEmailMobilePasswordCustom TextCalendarData Limitation TypeAbsolute DateRelative DateMin DateMax DateTimeAppointment Duration15 minutes30 minutes1 hour2 hourStart Time09:00 AM10:00 AM11:00 AM12:00 AMEnd Time09:00 AM10:00 AM11:00 AM12:00 AMCancelSave') $("#input_msg").val() $("#input_msg"+num).text(window.localStorage.getItem(key+num)) console.log(count[num-1]) for(var i=2; iType any text here'); $(".container_inside").append(structure); $("#add_msg_"+num+i).text(window.localStorage.getItem(num+i)); } }); 3.views.py def post_new(request): if request.method == "POST": new_poll= text() #call model object d= request.POST new_poll.message= d['message'] new_poll.save() print(new_poll) return render(request, "loggedin.html") 4.models.py class text(models.Model): message = models.TextField(max_length=250) time = models.DateTimeField(default=datetime.now) 5.urls.py path('newpostx/',views.post_new,name='post_new'), -
"Error: Couldn't find that app. › › Error ID: not_found." when running heroku commands in console
Heroku sees my app in the list of apps, but I can't access it with any commands. I constantly getting the error "Couldn't find that app". I tried all these: heroku run python manage.py migrate -app my-api heroku run python manage.py migrate heroku run python manage.py createsuperuser -app my-api Although when I try to run commands for 'heroku apps' in my console, says I have one app called my-api. I followed other similar questions and tried the git remote commands beforehand but still failed. Example: heroku apps heroku git:remote -app my-api -
"Failed building wheel for psycopg2==2.8.6" - MacOSX using virtualenv and pip
I need install psycopg2==2.8.6 because when I installed latest version I get UTC error. I solve UTC error with install psycopg2==2.8.6 in my manjaro os but i try install this in my macOS and i got this: ld: warning: directory not found for option '-L/usr/local/opt/openssl/lib/' ld: library not found for -lssl clang: error: linker command failed with exit code 1 (use -v to see invocation) error: command '/usr/bin/clang' failed with exit code 1 [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. ERROR: Failed building wheel for psycopg2 -
Django DetailView page - inline formset not saved in SQL
I am trying to implement Django inline formset to my DetailView. According to documentation it is much better to separate Detail and Form views and bring them back together in the third view and this is what I did. My form is visible in my template file but after submission, nothing happens. It is returning correctly to my product detail view but no data is saved to SQL. Can you please let me know what am I doing wrong? models.py class Product(models.Model): title = models.CharField('title', max_length=400, blank=False, null=False, help_text='max 400 characters', default='') class CERequest(models.Model): author = models.CharField(max_length=255, blank=True, null=True) related_component = models.ForeignKey(CostCalculator, on_delete=models.CASCADE, blank=True, null=True, default=1) number_of_units = models.IntegerField(default=0) related_product = models.ForeignKey(Product, on_delete=models.CASCADE, null=True, blank=True, related_name='related_product_ce_request') created = models.DateTimeField(default=timezone.now) total_price = models.IntegerField(verbose_name='Price (€)', default=0, blank=True, null=True) forms.py class CalculatorFormProduct(forms.ModelForm): author = forms.CharField(widget = forms.HiddenInput(), required = False) number_of_units = forms.IntegerField(help_text='Only numeric values are allowed.', min_value=0) total_price = forms.IntegerField(widget = forms.HiddenInput(), required = False) created = forms.DateTimeField(widget = forms.HiddenInput(), required = False) class Meta: model = CERequest fields = ('author', 'created', 'related_product', 'related_component', 'number_of_units') CalculatorFormsetProduct = inlineformset_factory(Product, CERequest, form=CalculatorFormProduct, fields=('author', 'related_product', 'related_component', 'created', 'number_of_units'), extra=3, can_delete=False) views.py class ProductView(LoginRequiredMixin, DetailView): model = Product template_name = 'hubble/ProductDetailView.html' def get_success_url(self): return reverse('product', kwargs={'slug': … -
how can i py my icons in my webapp in a better position?
i'm working with django-python making a webapp, but i have a problem, i have 4 icon in my first row and two icons under them, the problem is, above the lower icons are attached to the upper icons, this is the home.html file: {% extends 'dashboard/base.html' %} {% load static %} {% block content %} <section class="container text-center"> <h3>Welcome</h3> <hr> <br> <div class="row"> <div class="col-md-3"> <a href="{% url 'notes' %}"> <div class="card"> <img class="card-img-top" src="{% static 'images/notes.jpg' %}" alt="Notes image"> <div class="card-body"> <h5 class="card-title "> Notes </h5> Create Notes to refer them later. They are stored permanently until deleted </div> </div> </a> </div> <div class="col-md-3"> <a href="{% url 'homework' %}"> <div class="card"> <img class="card-img-top" src="{% static 'images/homework.jpg' %}" alt="Notes image"> <div class="card-body"> <h5 class="card-title "> Homework </h5> Add homeworks and assign them deadlines. They will be displayed prioritised by deadlines </div> </div> </a> </div> <div class="col-md-3"> <a href="{% url 'youtube' %}"> <div class="card"> <img class="card-img-top" src="{% static 'images/youtube.jpg' %}" alt="Notes image"> <div class="card-body"> <h5 class="card-title "> Youtube </h5> Search Youtube and select your desired video to play it on youtube </div> </div> </a> </div> <div class="col-md-3"> <a href="{% url 'todo' %}"> <div class="card"> <img class="card-img-top" src="{% static 'images/todo.jpg' %}" alt="Notes … -
How to fix FileNotFoundError: [Errno 2] No such file or directory:? (HEROKU)
I am trying to push my Django + React app to heroku. I have configured the path for my static files at below in settings.py STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'app/laundryman_frontend/build/static') ] The build is successful when I push to heroku but when I run heroku run python manage.py collectstatic I get the error FileNotFoundError: [Errno 2] No such file or directory: '/app/laundryman_frontend/build/static' My guess is that, Heroku is not looking does not recognise the path that I have set for the static files. Kindly help me solve this issue -
How to run parallel tasking with celery django?
I am looking to run tasks in parallel with django celery. Let's say the following task: @shared_task(bind=True) def loop_task(self): for i in range(10): time.sleep(1) print(i) return "done" Each time a view is loaded then this task must be executed : def view(request): loop_task.delay() My problem is that I want to run this task multiple times without a queue system in parallel mode. Each time a user goes to a view, there should be no queue to wait for a previous task to finish Here is the celery command I use : celery -A toolbox.celery worker --pool=solo -l info -n my_worker1 -------------- celery@my_worker1 v5.2.7 (dawn-chorus) --- ***** ----- -- ******* ---- Windows-10-10.0.22000-SP0 2022-08-01 10:22:52 - *** --- * --- - ** ---------- [config] - ** ---------- .> app: toolbox:0x1fefe7286a0 - ** ---------- .> transport: redis://127.0.0.1:6379// - ** ---------- .> results: - *** --- * --- .> concurrency: 8 (solo) -- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker) --- ***** ----- -------------- [queues] .> celery exchange=celery(direct) key=celery I have already tried the solutions found here but none of them seem to do what I ask StackOverflow : Executing two tasks at the same time with … -
Matching data from two functions in django context?
I'm struggling with matching contexts in my django project. I want to insert a .annotate() queryset, perfectly in just a set variable. I know it sounds weird but it's the best as I can describe it. I tried using .filter(), as it makes sense to me logically, but it doesn't quite work. my views.py from django.shortcuts import render from django.db.models import Count from django.db.models import Sum from .models import Offer_general from .models import Offer_details import datetime # Create your views here. def offer_general_list(request): #queryset = Offer_general.objects.filter(status=1).order_by('-id') context = {} context["data"] = Offer_general.objects.filter(status=1).order_by('-id')#stuff from Offer_general context["test"] = Offer_details.objects.values('fk_offer_general_id').annotate(sum=Sum('fk_offer_general_id')) return render(request, "index_offers.html", context) def offer_general_details(request): context = {} context["data"] = Offer_details.objects.all() return render(request, "offer_detail.html", context) models.py from django.db import models from django.contrib.auth.models import User from django.db.models import Count STATUS = ( (0,"Inactive"), (1,"Active") ) class Offer_type(models.Model): type = models.TextField() class Meta: ordering = ['-type'] def __str__(self): return self.type class Offer_general(models.Model): offer_name = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) status = models.IntegerField(choices=STATUS, default=0) type = models.ForeignKey(Offer_type, on_delete= models.PROTECT) class Meta: ordering = ['-id'] def __str__(self): return self.offer_name class Offer_localization(models.Model): localization = models.TextField() class Meta: ordering = ['-localization'] def __str__(self): return self.localization class Offer_details(models.Model): slug = models.SlugField(max_length=200, unique=True) localization = models.ForeignKey(Offer_localization, on_delete= models.PROTECT, default="Opole") … -
Getting TypeError: Form.__init__() missing 1 required positional argument: ‘request’ even though I have passed request in both GET and POST methods
I have a form, which I am initializing its field with some data passing to it from view in its __init__() method to be shown on front end, using HttpRequest object. Even though, I have passed the HttpRequest object named request in both GET and POST methods, I am still getting the following error on POST request: TypeError at /accounts/invite-user/cancel/ InviteUserCancelForm.__init__() missing 1 required positional argument: 'request' Error full details are: Traceback Switch to copy-and-paste view D:\Projects\meistery\venvs\inviteandresetpass\lib\site-packages\django\core\handlers\exception.py, line 55, in inner response = get_response(request) … Local vars D:\Projects\meistery\venvs\inviteandresetpass\lib\site-packages\django\core\handlers\base.py, line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) … Local vars D:\Projects\meistery\venvs\inviteandresetpass\lib\site-packages\django\views\generic\base.py, line 84, in view return self.dispatch(request, *args, **kwargs) … Local vars D:\Projects\meistery\venvs\inviteandresetpass\lib\site-packages\django\contrib\auth\mixins.py, line 73, in dispatch return super().dispatch(request, *args, **kwargs) … Local vars D:\Projects\meistery\venvs\inviteandresetpass\lib\site-packages\django\contrib\auth\mixins.py, line 109, in dispatch return super().dispatch(request, *args, **kwargs) … Local vars D:\Projects\meistery\venvs\inviteandresetpass\lib\site-packages\django\views\generic\base.py, line 119, in dispatch return handler(request, *args, **kwargs) … Local vars D:\Projects\meistery\venvs\inviteandresetpass\lib\site-packages\django\views\generic\edit.py, line 151, in post form = self.get_form() … Local vars D:\Projects\meistery\venvs\inviteandresetpass\lib\site-packages\django\views\generic\edit.py, line 39, in get_form return form_class(**self.get_form_kwargs()) … My forms.py is: class InviteUserCancelForm(forms.Form): invitations = forms.ChoiceField( widget=forms.RadioSelect, choices=(('test_invite','test_invite'),) ) def __init__(self, request: HttpRequest, *args, **kwargs): super (InviteUserCancelForm, self).__init__(*args, **kwargs) if "invitations" in args: self.fields['invitations'] = forms.ChoiceField( label="Your Invitations", widget=forms.RadioSelect, choices=request["invitations"] ) … -
Django ValueError when A field is empty
i have a ModelForm which is like this : Forms.py : class send_to_evaluatorForm(forms.ModelForm): class Meta: model = send_to_evaluator exclude = ('Creater_UserID','mozo1_id','mozo2_id','mozo3_id','knowledge') so the problem comes when i leave a field empty and submit to save it... but when everything is filled and nothin left empty the code runs ok. a part of my view : if request.method == "POST": form = send_to_evaluatorForm(request.POST) mozo3=request.POST.get('mozo3') mozo1=request.POST.get('mozo1') mozo2=request.POST.get('mozo2') if form.is_valid: obj = form.save() the error happens because the form doesnt validate and while i was debugging it i noticed that a field is required here is my model if you want to have a look...if i let nazar empty my form doesnt save it models.py: mozo1_id = ForeignKey(topic1,on_delete=models.PROTECT,blank=True, null=True) mozo2_id = ForeignKey(topic2,on_delete=models.PROTECT,blank=True, null=True) mozo3_id = ForeignKey(topic3,on_delete=models.PROTECT,blank=True, null=True) nazar = TextField(verbose_name='point_of_view',max_length=4000) create_date = IntegerField(default=LibAPADateTime.get_persian_date_normalized(), blank=True, null=True) Creater_UserID = ForeignKey(Members,on_delete=models.PROTECT,blank=True, null=True) knowledge = ForeignKey(TblKnowledge,on_delete=models.PROTECT,blank=True, null=True) def __str__(self): return str(self.id) -
Django - how get the average time of a person that answered
I would like to get the Average time of answers of each person. Model: class Person(models.Model): uid = models.UUIDField(default=uuid.uuid4, primary_key=True) first_name = models.CharField(max_length=255, blank=True) last_name = models.CharField(max_length=255, blank=True) email = CIEmailField() class CoursePerson(models.Model): uid = models.UUIDField(primary_key=True, default=uuid.uuid4) course = models.ForeignKey( Course, related_name="courses_persons", on_delete=models.CASCADE ) person = models.ForeignKey( "Person", related_name="courses", on_delete=models.CASCADE ) created_at = models.DateTimeField(auto_now_add=True) start_at = models.DateTimeField() class CoursePersonPasswordFormSubmission(models.Model): uid = models.UUIDField(primary_key=True, default=uuid.uuid4) text_mask = models.CharField(max_length=255) text_length = models.IntegerField() created_at = models.DateTimeField(auto_now_add=True) course_person = models.ForeignKey( CoursePerson, related_name="password_submissions", on_delete=models.CASCADE ) I've started to write the the def_queryset function. Everything on the beginning is ok since I have to filter stuff before do that logic: def get_queryset(self): accounts = get_account_ids(self.request) course_person_queryset = CoursePerson.objects.filter( account__in=accounts, is_in_analytics=True, status__gte=CoursePerson.StatusChoices.OPEN, course__type="form" ) course_person_queryset = filter_base_analytics( self.request, course_person_queryset, date_start=self.request.GET["date_start"], date_end=self.request.GET["date_end"], ) ...I'm blocked here... But now, I have to render a list of person with their Average of delay of response. Means, the initial message time sent to the user is course_person__start_at and the answer time of the person is password_submissions__created_at what I've tried: person_queryset = models.Person.objects.filter( courses__in=course_person_queryset.values_list('uid', flat=True), courses__password_submissions__created_at__isnull=False, courses__emails_person__opened_at__isnull=False, ).annotate( first_password=Subquery( CoursePersonPasswordFormSubmission.objects.filter( course_person_id=OuterRef("uid") ) .order_by("created_at") .values("uid")[:1] ), ) But this can't work as a person can have multiple course_person. and these course_person can have multiple … -
Visual Studio Code Automatically adds useless code
enter code hereI recently switched to VSC, installed python, pylance plugins. Everything seemed to be working fine, but when I started working with django, vsc started automatically when selecting an option in views.py CBV including Optional: str etc, for example context_object_name: Optional[str] Here I click Enter And then it automatically adds I don't want to remove hints in the code and automatic addition, but I also don't want him to add unnecessary -
Django Authentication Login From Active directory
How can I authenticate and login the user from Active Directory? This is my code Authenticate.py: from .models import User from ldap3 import ALL, Server, Connection, NTLM from ldap3.core.exceptions import LDAPException from django.contrib.auth.backends import ModelBackend def validate_user_credentials(username, password): server = Server(host='@xxxDomain', use_ssl=False, get_info=ALL) try: with Connection( server, authentication="NTLM", user=f"{''}\\{username}", password=password, raise_exceptions=False, ) as connection: print(connection.result['description']) return True except LDAPException as e: print(e) return False class UserAuth(ModelBackend): def authenticate(self,request,username=None,password=None,**kwargs): try: if (validate_user_credentials(username, password)): print("Helloooooooooooooo") user = User.objects.get(username=username) print(user) return user return None except User.DoesNotExist: return None def get_user(self, user_id): try: return User.objects.get(username=user_id) except User.DoesNotExist: return None views.py: class UserLoginView(View): form_class = UserLoginForm def get(self, request): form = self.form_class return render(request, 'login/login.html', {'form': form}) def post(self, request): form = self.form_class(request.POST) if form.is_valid(): cd = form.cleaned_data userexistindb = User.objects.filter( username=cd['username'], is_user_local=False).exists() username = cd['username'] password = cd['password'] try: if userexistindb: try: user = authenticate( request, username=username, password=password) if (user is not None): login(request=request, user=user) messages.success( request, 'Loged in success', 'success') return redirect('login:result') else: messages.error(request, 'us', 'warning') except User.DoesNotExist: messages.error( request, 'Invalid User/Password', 'warning') except User.DoesNotExist: username = None messages.error( request, 'Invalid User/Password', 'warning') return render(request, 'login/login.html', {'form': form}) The result is the sessionid It is created,The username and password are correct and the … -
Migrations Error in Django: AttributeError: 'str' object has no attribute '_meta'
I know this has been asked before. But, I tried the available solutions. Those don't seem to work in my case unless I missed something unintentionally. I dropped all the tables/relations from the connected database and deleted all the previous migration files except the init.py. And then ran the makemigrations command which worked fine. But got this error after running migrate. Here is the error: Applying book.0001_initial... OK Applying reader.0001_initial...Traceback (most recent call last): File "/home/brainiac77/github/bookworms_backend/backend/manage.py", line 22, in <module> main() File "/home/brainiac77/github/bookworms_backend/backend/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/brainiac77/Installations/anaconda3/lib/python3.9/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/home/brainiac77/Installations/anaconda3/lib/python3.9/site-packages/django/core/management/__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/brainiac77/Installations/anaconda3/lib/python3.9/site-packages/django/core/management/base.py", line 414, in run_from_argv self.execute(*args, **cmd_options) File "/home/brainiac77/Installations/anaconda3/lib/python3.9/site-packages/django/core/management/base.py", line 460, in execute output = self.handle(*args, **options) File "/home/brainiac77/Installations/anaconda3/lib/python3.9/site-packages/django/core/management/base.py", line 98, in wrapped res = handle_func(*args, **kwargs) File "/home/brainiac77/Installations/anaconda3/lib/python3.9/site-packages/django/core/management/commands/migrate.py", line 290, in handle post_migrate_state = executor.migrate( File "/home/brainiac77/Installations/anaconda3/lib/python3.9/site-packages/django/db/migrations/executor.py", line 131, in migrate state = self._migrate_all_forwards( File "/home/brainiac77/Installations/anaconda3/lib/python3.9/site-packages/django/db/migrations/executor.py", line 163, in _migrate_all_forwards state = self.apply_migration( File "/home/brainiac77/Installations/anaconda3/lib/python3.9/site-packages/django/db/migrations/executor.py", line 248, in apply_migration state = migration.apply(state, schema_editor) File "/home/brainiac77/Installations/anaconda3/lib/python3.9/site-packages/django/db/migrations/migration.py", line 131, in apply operation.database_forwards( File "/home/brainiac77/Installations/anaconda3/lib/python3.9/site-packages/django/db/migrations/operations/models.py", line 93, in database_forwards schema_editor.create_model(model) File "/home/brainiac77/Installations/anaconda3/lib/python3.9/site-packages/django/db/backends/base/schema.py", line 440, in create_model if field.remote_field.through._meta.auto_created: AttributeError: 'str' object has no attribute '_meta' reader.0001_initial.py # Generated by … -
is there any python or django package that contains all address?
A few years ago I was working with a package for addresses, that package includes region, countries, states, cities, areas, sub areas...etc. It contains great data and all data connected together, but unfortunately I forgot it and what it's name. Now I spent a lot of hours to find it or any other library that contains the same info, but no results. anyone can help me by suggest a library, not apis no google maps. many thanks in advance. -
How to use AND in Django?
This is in my views.py win = Bid.objects.filter(auction__closed=True) f = Bid.objects.get(user=request.user) I want to do this foo = Bid.objects.filter(auction__closed=TRUE AND user=request.user) How to achieve this in django? -
Gunicorn Django response statusText missing
I have a Django DRF/React setup using React and JWT for authorisation. On local runserver, I send the request for token, I recieve access and refresh tokens. When the access token expires, I have an Axios interceptor set which checks the error response and sends new response with refresh token. All passes and works fine. if ( error.response.data.errors[0].code === "token_not_valid" && error.response.status === 401 && error.response.statusText === "Unauthorized" ) { I noticed on server (Gunicorn), that the process all works fine, access token received and works as expected until expiry, but the refresh token request doesn't even send. Then after some debugging I noticed the gunicorn server sends the same response but without statusText. I am only assuming it is something to do with Gunicorn as that is the only difference than running code on runserver locally. On image, Left side is local response. Right side is server response. Any reason I would not receive the statusText? Any setting I need to be aware of? -
How to get a specific id for my task in Django?
I have a django app in which I log in as an admin and add a tasks for a specific employee. Then I log in as the employee and I have to end the task when it's done. I display my active tasks in an table in a html template and I want to make the ended task is_active = 0 to check that the task is done. I also want to store the date when the task was done in closed_at. My models.py: class Employee(models.Model): id = models.AutoField(primary_key=True) user = models.OneToOneField(User, on_delete=models.CASCADE) objects = models.Manager() address=models.TextField() created_at = models.DateTimeField(auto_now_add = True) updated_at = models.DateTimeField(auto_now_add = True) active_tasks = models.IntegerField(default = 0) completed_tasks = models.IntegerField(default = 0) daily_r = models.IntegerField(default = 0) weekly_r = models.IntegerField(default = 0) monthly_r = models.IntegerField(default = 0) annual_r = models.IntegerField(default = 0) class Tasks(models.Model): id = models.AutoField(primary_key=True) employee_id = models.ForeignKey(Employee,blank=True,null=True,on_delete=models.CASCADE) is_active = models.IntegerField(default = 1) headline = models.CharField(max_length = 100) body = models.TextField() created_at = models.DateTimeField(auto_now_add = True) assigned_at =models.DateTimeField(auto_now_add = True) closed_at = models.DateTimeField(auto_now_add = True) My views.py def viewActiveTasks(request): current_user = request.user current_user_id = current_user.id employees = Employee.objects.filter(user_id = current_user_id) user_employees = User.objects.filter(is_employee=1) tasks = Tasks.objects.filter() return render(request, "employees_active_tasks.html", {'employees':employees,'user_employees':user_employees,'tasks':tasks}) def endTask(request): employee=Employee.objects.get(user_id=request.user) … -
Django bulk update/replace substring keeping the previous value
I have a model with two fields: field_a and field_b field_a field_b JPY 6 blabla JPY 677 blabla I would like to replace / update the contents of field_a but keeping the old values (numbers) and just changing the currency. For instance, this would be a desired result: field_a field_b USD 6 blabla USD 677 blabla What I've found/tried after some research: currency = 'USD' ExampleModel.objects.update( field_a=Replace('field_a', Value('old_text?'), Value(currency + old_text_digits?)) ) The problem is, I don't know how can I access the old_text for each line in the table and I don't know how to manipulate the new text to include the currency + previous numbers. Any help would be appreciated -
How to send an email through Sendgrid, as a reply to some email I received through Sendgrid inbound parse using Django?
So I am sending my email using sendgrid personalization something like this: message = { "personalizations": context["personalizations"], "from": {"email": context["sender_email"]}, "subject": context["subject"], "content": [{"type": MimeType.html, "value": context["body"]}], "reply_to": {"email": context["reply_to"]} } sg = SendGridAPIClient(os.environ.get("SENDGRID_API_KEY")) sg.send(message) Here context["personalization"] is an object as below: { "to": [{"email": applicant.email}], "custom_args": { "email_id": str(correspondance.id), "env": settings.ENVIRONMENT } } Sending and receiving the emails work fine. The problem is that I can't send an email as a reply to some email. Like a user sends me an email which I receive through sendgrid's inbound parse. Now I want to reply to the email I received. A solution I found on the internet was that I have to add an 'in_reply_to' ID which I receive as Message_ID in inbound parse but that didn't work. I did something like this: message = { "personalizations": context["personalizations"], "from": {"email": context["sender_email"]}, "subject": context["subject"], "content": [{"type": MimeType.html, "value": context["body"]}], "reply_to": {"email": context["reply_to"]}, "in_reply_to": message_id } sg = SendGridAPIClient(os.environ.get("SENDGRID_API_KEY")) sg.send(message) Here the message_id is Message_ID I received in the inbound email's json. -
Should I use stored procedure on Django
My boss wants me to use his stored procedure on my django project. But his sp is kinda simple and I can probably create it using django's queryset API his sp involves inserting items to a item_table then insert also into transaction_logs_table. his reasoning So it can be reuse we have mvc programmer who still uses sp on his code his planning on developing on mobile My Question is should I use sp on django? or when should I use it -
Django post form fields to another page
I have a Django form that takes filter options for a report. The report page is a separate view that renders the report based on the form data. My first pass at this, I simply set the action of the form to the report page and method to GET. The form data was then passed directly the report view via the querystring which I would use GET to retrieve. The problem with this was that this bypassed form validation since the the form did not post back to its own view. My next pass, I removed the form action (so it would post back to itself) and used form_valid (I am using class based views) to encode the form data and redirect to the report view like so: ReportOptionsView(FormView) form_class = OptionsForm template_name = 'my_report_options.html' report = reverse_lazy('my_report') def form_valid(self, form): qstr = urlencode(form.cleaned_data) return redirect(self.report+"?"+qstr) The report page works the same -I just retrieve the information from the querystring to filter the models and display the report. I would prefer the form data not appear on the querystring of the report page. When I tried to redirect to the report page using a POST method is where I starting … -
Djongo+Mongo add expiration (auto-delete) to model objects
Is there a simple way in Django to add an expiration date to documents via the model meta? For example, in pymongo you can do something like this: mongo_col.ensure_index("date", expireAfterSeconds=3*60) -
How to annotate related objects with filter?
class Item(models.Model): name = models.CharField(max_length=255) user = models.ForeignKey(User) class Document(models.Model): doc_type = models.CharField(max_length=10, default="DOC") item = models.ForeignKey(Item, related_name="docs") uploaded_at = models.DateTimeField(auto_now_add=True) @api_view(["GET"]) def get_items(request): # docs__uploaded_at should be from objects having doc_type="DOC" only items = Item.objects.prefetch_related("docs").filter(user=request.user).annotate(date=Max("docs__uploaded_at").order_by("-date") Here I want to order items queryset based on document uploaded_at field. An Item can have multiple or None documents as well so order the items based on last document date with DOC as doc_type and if it has none then keep it at the last. NOTE: I am using django 1.9 -
In PDF generation which font family is suitable for multi language support?
Currently we use xhtmpdf that use UTF8. that not supporting some character