Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to fix error "'ManyRelatedManager' object has no attribute 'field_name'"
I am trying to extract some the student_ID and student_name from a model which has a manytomanyfield relations. unfortunately, i don't know how to go about that. The method i tried resulted into the attribute error i got. models.py class add_courses(models.Model): Course_Name = models.CharField(max_length=200, blank=True) Manager_Name = models.ForeignKey(Manager_login_information, on_delete=models.CASCADE, blank=True) description = models.TextField(default='', blank=True) syllabus = models.TextField(default='', blank=True) classroom = models.CharField(choices=choices, default='in person', max_length=12, blank=True) course_code = models.CharField(max_length=14, default='', blank=True) student = models.ManyToManyField(add_students_by_manager, blank=True) def __str__(self): return self.Course_Name class add_students_by_manager(models.Model): manager_ID = models.ForeignKey(Manager_login_information, on_delete=models.CASCADE) student_ID = models.CharField(max_length=200) student_name = models.CharField(max_length=200) phone_number = models.CharField(max_length=200) address = models.CharField(max_length=200) dob = models.CharField(max_length=200) major = models.CharField(max_length=200) password = models.CharField(max_length=200) def __str__(self): return self.student_name @staticmethod def matching_loging_stu(userID): try: return add_students_by_manager.objects.get(student_ID=userID) except: return False views.py def assignment_page(request): if request.method == "POST": get_course_name = request.POST.get('get_course_name') add_courses_get = add_courses.objects.get(Course_Name=get_course_name) stu_course_all_stu = add_courses.objects.filter(Course_Name=add_courses_get) print(stu_course_all_stu) for m in stu_course_all_stu: print(m.student.student_ID) print(m.student.student_name) context = {"stu_course_all_stu":stu_course_all_stu, "get_course_name":get_course_name} return render(request, 'assignment_page.html', context3) -
Is it possible to pass a specific value to a django formset?
So I've been playing with Django formsets for about a week and I'm about ready to throw out Django altogether. Just kidding. Kinda. :). I have the standard inline formset implementation working finally as I documented here. How do I properly implement Django formsets with a CreateView ( Class Based View )? Hope it helps someone. Now I'm trying to leverage this code by trying to pass a specific queryset to it as shown below. class PlayerFormSet(PlayerFormSet,BaseInlineFormSet): def __init__(self, *args, **kwargs): super(PlayerFormSet, self).__init__(*args, **kwargs) self.queryset = Player.objects.filter(team_pk=20) As shown above, if I hard code a value, no worries it works to populate my formset. Although hardcoding this value is of little value to the implementation. I have researched form_kwargs, played around with numerous implementations as shown throughout SO, about passing a value but nothing I try works other than the code above for one team obviously and I can't for the life of me figure out how to do something like: class PlayerFormSet(PlayerFormSet,BaseInlineFormSet): def __init__(self, *args, **kwargs): super(PlayerFormSet, self).__init__(*args, **kwargs) self.queryset = Player.objects.filter(self.object.team_pk) Or... class PlayerFormSet(PlayerFormSet,BaseInlineFormSet): def __init__(self, *args, **kwargs): super(PlayerFormSet, self).__init__(*args, **kwargs) self.queryset = Player.objects.filter(self.instance.team_pk) I know the pk, it can clearly be passed here in a hardcoded fashion...And … -
Unable to save scrapped images to models or database using beautifulsoup and django
The following images were scrapped with beautiful soup https://people.net/wp-content/uploads/2021/03/ad1-746x375.jpg https://people.net/wp-content/uploads/2020/08/caroon-1-600x375.jpg something like this brought the images images = [i['data-src'] for i in soup.find_all('img', {'class','attachment-jnews-750x375 size-jnews-750x375 lazyload wp-post-image'})] but am unable to save the images scrapped above like this because it will bring an error Post.objects.create( title=title, content_1=paragraphs, image=images, sources=lnk, ) this will bring an error when i try saving to models class Post(models.Model): title = models.CharField(max_length=250, blank = True, help_text='Maximum 160 Title characters.') image = models.FileField(upload_to='images', blank=True, null=True, help_text='You must upload original image before continuing.') if file and not file._committed: AttributeError: 'list' object has no attribute '_committed' and I try using for loop but the same error exist too for image in images: / Post.objects.create(title=title, content_1=paragraphs, image=images, sources=lnk, ) and I got this error also if file and not file._committed: AttributeError: 'list' object has no attribute '_committed' i think i need help immediately and i know this great people here will help me out. -
can you help me to know this error (Django Rest API )I am just learning now and new at REST API
import requests URL= "http://127.0.0.1:8000/stuinfo/2" r = requests.get(url = URL) data = r.json() print(data) python myapp.py Traceback (most recent call last): File "C:\Users\sunny\Desktop\Carry_Wire\Django_REST\ENV\lib\site-packages\urllib3\connection.py", line 170, in _new_conn (self._dns_host, self.port), self.timeout, **extra_kw File "C:\Users\sunny\Desktop\Carry_Wire\Django_REST\ENV\lib\site-packages\urllib3\util\connection.py", line 96, in create_connection raise err File "C:\Users\sunny\Desktop\Carry_Wire\Django_REST\ENV\lib\site-packages\urllib3\util\connection.py", line 86, in create_connection sock.connect(sa) ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\sunny\Desktop\Carry_Wire\Django_REST\ENV\lib\site-packages\urllib3\connectionpool.py", line 706, in urlopen chunked=chunked, File "C:\Users\sunny\Desktop\Carry_Wire\Django_REST\ENV\lib\site-packages\urllib3\connectionpool.py", line 394, in _make_request conn.request(method, url, **httplib_request_kw) File "C:\Users\sunny\Desktop\Carry_Wire\Django_REST\ENV\lib\site-packages\urllib3\connection.py", line 234, in request super(HTTPConnection, self).request(method, url, body=body, headers=headers) File "c:\users\sunny\appdata\local\programs\python\python37\lib\http\client.py", line 1229, in request self._send_request(method, url, body, headers, encode_chunked) File "c:\users\sunny\appdata\local\programs\python\python37\lib\http\client.py", line 1275, in _send_request self.endheaders(body, encode_chunked=encode_chunked) File "c:\users\sunny\appdata\local\programs\python\python37\lib\http\client.py", line 1224, in endheaders self._send_output(message_body, encode_chunked=encode_chunked) File "c:\users\sunny\appdata\local\programs\python\python37\lib\http\client.py", line 1016, in _send_output self.send(msg) File "c:\users\sunny\appdata\local\programs\python\python37\lib\http\client.py", line 956, in send self.connect() File "C:\Users\sunny\Desktop\Carry_Wire\Django_REST\ENV\lib\site-packages\urllib3\connection.py", line 200, in connect conn = self._new_conn() File "C:\Users\sunny\Desktop\Carry_Wire\Django_REST\ENV\lib\site-packages\urllib3\connection.py", line 182, in _new_conn self, "Failed to establish a new connection: %s" % e urllib3.exceptions.NewConnectionError: <urllib3.connection.HTTPConnection object at 0x0000015898D193C8>: Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it During handling of the above exception, another exception … -
Django UserCreationForm turning popup validation errors into in-line errors
I have created a user registration form using Django's inbuilt registration/validation, and I can't figure out how to modify the display of the popup style validation errors. I've noticed that validation errors are displayed in two forms: If any required field is not filled, or if the email field doesn't contain an '@' symbol, the validation error will be displayed in a popup message (screenshot 1). If an error is not raised due to any of the reasons in (1), but for some other reason (i.e. passwords are too short or don't match; username is already taken), errors will be displayed in the form of an unordered list with class name 'errorlist' (screenshot 2, errors in dark red). I don't really like the look of the popup style errors, and I would like to display them in the same way as the in-line errors. How should I go about doing this? Form code: from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User class CreateUserForm(UserCreationForm): class Meta: model = User fields = ['username','email','password1','password2'] HTML: {% extends 'base/main.html' %} {% load static %} {% block css %} <link rel="stylesheet" type="text/css" href="{% static 'css/register.css' %}"> {% endblock css %} {% block content %} <div … -
Form wont appear in admin side of website and confused as to why and wondering if someone else could see why
models.py class Contact(models.Model): BookID = models.CharField(max_length=30) BookTitle = models.CharField(max_length=30) Author = models.CharField(max_length=35) UploadImage = models.ImageField(upload_to='ContactImg') def __str__(self): return self.BookId forms.py class ContactForm(forms.Form): BookID=forms.CharField(max_length=30,required=True) BookTitle=forms.CharField(max_length=30,required=True) Author=forms.CharField(max_length=35,required=True) UploadImage=forms.ImageField() class Meta: model = Contact fields = ('BookID', 'BookTitle', 'Author','UploadImage') Views.py def ContactUs(request): context_dict = {} if request.user.is_authenticated: context_dict['logged_in'] = True else: context_dict['logged_in'] = False user_form=ContactForm() if request.method == 'POST': user_form = ContactForm(request.POST) if user_form.is_valid(): # we load our profile instance Contact.BookId = user_form.get('BookId') Contact.BookTitle = user_form.get('BookTitle') Contact.Author= user_form.get('Author') Contact.UploadImage= user_form.get('UploadImage') Contact.save() return redirect('readingTime:home') else: # Invalid form # messages.error(request, 'Form contains errors. Double check') print(user_form.errors) messages.error(request, 'Form contains errors. Double check') # user_form = user_form.errors # user_form = RegisterForm() else: # Blank form since we do not have an HTTP POST user_form = ContactForm() return render(request,"readingTime Html {% extends 'readingTime/base.html' %} {% load staticfiles %} {% block style_css %} <link rel="stylesheet" type="text/css" href="{% static 'css/ContactUs.css' %}" xmlns="http://www.w3.org/1999/html"/> {% endblock %} {% block navigation_bar %} <div class="navigation-bar"> <a href="/readingTime/">home</a> {% if logged_in %} <a href="/readingTime/logOut/" class="right">Sign Out</a> <a href="/readingTime/signIn/" class="right">My account</a> <a href="/polls/" class="right">User Polls</a> {% else %} <a href="/readingTime/register/" class="right">Register</a> <a href="/readingTime/signIn/" class="right">Sign In</a> <a href="/readingTime/signIn/" class="right">Poll Results</a> {% endif %} </div> {% endblock %} {% block body_block %} <div class="main" > <h1>Contact … -
How to work with docker containers created by cookiecutter-django?
I started a project using cookiecutter-django. I use docker. I also use wsl 2 (ubuntu 20.04) on windows 10. I edit using vscode started from wsl shell. When I create a new file using a remote docker command, e.g. when I issue docker-compose -f local.yml --rm django python manage.py startapp appname , the new files have the user and group root, and then I need to fix owner and group to my user to edit the files created this way. The questions are: Is this the way I am supposed to work? Should I edit directly in the container created, so that things like mypy linting and code completion would work better hopefully. Can you give steps to do that for a docker noob? -
Passing value from one html template to another in Django
I am making a web project using Django and relatively new to Django. I am stuck at the following part I want to get user input from one html search box and display it on another html page. This is my first page <html> <head> <title>Title</title> <style type="text/css"> #title{margin-top:150px;font-size:40px; font-family:"roboto"; text-align:center; color:grey} #info_text{margin-top:10px;font-size:15px; font-family:"roboto"; text-align:center; color:grey} #search_bar{height:40px;margin-top:20px;margin-bottom:9px;width:50%; margin-left: 24%} #search_button{height:50px;margin-top:20px;width:20%;margin-left: 40%;background-color:grey; font-size:40px; font-family:"roboto"; text-align:center; color: white} </style> </head> <body id="body"> <div> <h1 id="title">Enter Value</h1> <form action="result" method="POST"> {% csrf_token %} <input id="search_bar" type="text" name="search_box" onfocus="this.value=''"> <input type="submit" value="Search" id="search_button"> </form> </div> </body> </html> This is my view.py file from django.shortcuts import render # Create your views here. def home(request): return render(request, 'templates/home.html') def result(request): raw_details = None if request.method == 'GET': raw_deatils = request.POST.get('search_box', None) print(raw_details) return render(request, 'templates/result.html', raw_details) Please help Thankyou -
normalize different date formats
I am trying to work with an XML data that has different kinds of (string) date values, like: 'Sun, 04 Apr 2021 13:32:26 +0200' 'Sun, 04 Apr 2021 11:52:29 GMT' I want to save these in a Django object that has a datetime field. The script that I have written to convert a str datetime is as below: def normalise(val): val = datetime.strptime(val, '%a, %d %b %Y %H:%M:%S %z') return val Although, this does not work for every datetime value I scrape. For example for above 2 examples, the script works for the first one but crashes for the second. What would be an ideal way of normalising all the datetime values ? -
can't makemigrations in wagtail
I'm trying to migrate this model, and I get this error message. You are trying to add a non-nullable field 'id' to secondsection without a default; I'm using wagtail 2.11.3 and python 3.6 I want to generate the following: in CMS to add a title for the page description and three sections the first section will have : 1- text 2- image 3- title the second section will have: 1- a title 2- three blocks with title subtitle and text the third section will have : 1- title 2-text 3-image I've seen this solution, it didn't work from django.db import models from wagtail.core.fields import * from wagtail.admin.edit_handlers import * from wagtail.images.edit_handlers import * from modelcluster.fields import ParentalKey from wagtail.core.models import Orderable class AboutUs(Page): """About us Model""" templates = 'aboutus/about_us.html' description = models.TextField(blank=True, null=True) banner_image = models.ForeignKey( "wagtailimages.Image", null=True, blank=True, on_delete=models.SET_NULL, related_name="+", ) first_section_title = models.CharField(max_length=100, blank=True, null=True) first_section_text = models.TextField(max_length=100, blank=True, null=True) first_section_image = models.ForeignKey( "wagtailimages.Image", null=True, blank=True, on_delete=models.SET_NULL, related_name="+", ) second_section_title = models.CharField(max_length=100, blank=True, null=True) third_section_title = models.CharField(max_length=100, blank=True, null=True) third_section_Text = models.TextField(blank=True, null=True) third_section_image = models.ForeignKey( 'wagtailimages.Image', null=True, blank=True, on_delete=models.SET_NULL, related_name="+", ) content_panels = Page.content_panels + [ MultiFieldPanel( [ FieldPanel('description'), ImageChooserPanel('banner_image') ], heading='Banner Section' ), MultiFieldPanel([ FieldPanel('first_section_title'), FieldPanel('first_section_text'), … -
Django forms select from choices or enter new data
I have a Django form in which for some fields I pull choices from my database, shown below. I have another field in which the user has to manually type in the data. Is it possible to give that field choices that are present from the database and an option to enter the data if the choice isn't there? Example: The field name is player and I would like to have all the players already in database as options to choose from and if it is a new player, the option to enter it. Is that what a TypedChoiceField is? I have been trying to find examples but no luck. thanks! forms def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) team_names = TeamName.objects.filter(league__name='MLB').order_by('name') teams = [(team.id, team.name)for team in team_names] self.fields['team'].choices = teams -
What is the best choice of models for a multiple choice quiz app created with Django?
I know there's a similar questions to this one here. My question builds on that answer. I am building a web app that will allow a user to create quizzes for educational purposes. This implies that there will be hundreds of questions created. In the quoted answer the method suggested is to use a ForeignKey relationship as such: class Question(models.Model): prompt = models.TextField (max_length=300) answer = models.CharField (max_length=50) class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice = models.CharField (max_length=300, blank=True) However, the problem with this method is that if I have 300 questions, that will create 1200-1800 or choice entries. As there are more and more questions created, that number will grow by 10. As an educator, I plan to use this for my work (I have several thousand questions) and share the app with other teachers who will all be adding and sharing their own questions. I am concerned that on a larger scale this will create performance issues with the database. What has been suggested to me is to use this approach instead: class Question(models.Model): prompt = models.TextField (max_length=300) answer = models.CharField (max_length=50) class ChoiceList(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice1 = models.CharField (max_length=300, blank=True) choice2 = models.CharField (max_length=300, blank=True) … -
Create path with pk in router. Django
I need to create one more endpoint in my urls. Now i have this: router = DefaultRouter() router.register('collection', CollectionViewSet, basename='collection') urlpatterns = router.urls urlpatterns += [ path('collection/<int:pk>/video/', CollectionVideoViewSet.as_view({'get': 'list'}), name='collection-videos') ] But i need to set this 'collection/<int:pk>/video/' path to router because i want to have pk after it. Like this - 'collection/<int:pk>/video/<int:pk>'. But if create router.register('collection/<int:pk>/video', CollectionViewSet, basename='video') and go to http://0.0.0.0:8000/api/collections/v1/collection/1/video/ got an error Page not found (404) and see that django have api/collections/ v1/ ^collection/<int:pk>/video/$ [name='collection-list'] path in urls but don't go to it. What i have to do? -
changing Arrow Color for users
iam a Django BackEnd Developer and i have created a Blog i just want to know how to color slected Arrow after user Vote for specific Post and save it this is Arrow Html: <a href="{% url 'home:post-vote-up' id=posts.id %}"><i class="fas fa-arrow-up"></i></a> <p class="lead">{{posts.votes}}</p> <a href="{% url 'home:post-vote-down' id=posts.id %}"><i class="fas fa-arrow-down"></i> </a> -
How to get only month name and total in Django
I am trying to get only month name and count number from Data = QuerySet [{'month': datetime.datetime(2021, 3, 1, 0, 0, tzinfo=<DstTzInfo 'Asia/Dhaka' +06+6:00:00 STD>), 'count': 2 }] If I use Data[0]['month'] result is showing like (2021, 3, 1,0,0, ...) but I need to see only as March How can I view the month? Thanks in advance. -
Pip freeze > requirements doesn't work well with anaconda
I am trying to create a virtual environment based on another, for this, I want to extract the information from the libraries for a Django environment with pip freeze> requirements.txt But the output is asgiref @ file:///tmp/build/80754af9/asgiref_1605055780383/work certifi==2020.12.5 cffi==1.14.5 chardet==4.0.0 cryptography==3.4.7 cycler==0.10.0 Django @ file:///tmp/build/80754af9/django_1613762073373/work django-clear-cache==0.3 djangorestframework==3.12.4 idna==2.10 kiwisolver==1.3.1 matplotlib==3.4.1 numpy==1.20.2 Pillow==8.2.0 psycopg2 @ file:///C:/ci/psycopg2_1612298766762/work pycparser==2.20 PyMySQL==1.0.2 pyparsing==2.4.7 PyQt5==5.15.4 PyQt5-Qt5==5.15.2 PyQt5-sip==12.8.1 python-dateutil==2.8.1 pytz @ file:///tmp/build/80754af9/pytz_1612215392582/work requests==2.25.1 six==1.15.0 sqlparse @ file:///tmp/build/80754af9/sqlparse_1602184451250/work urllib3==1.26.4 wincertstore==0.2 When I try pip install -r requirements.txt doesn't work. Output Processing c:\tmp\build\80754af9\asgiref_1605055780383\work ERROR: Could not install packages due to an OSError: [Errno 2] No such file or directory: 'C:\\tmp\\build\\80754af9\\asgiref_1605055780383\\work' So I need a way to extract info with pip and install it with pip in another environment. -
Django | Why are my added fields to my CreateView not saved to the database/ or aren't rendered?
For a couple of days I'm stuck on a part of my Django project, where I want to add some extra fields for the user to fill in when they create a post. The problem is that the extra fields are not showing up on the page, or are saved in the database. I'm seeing these added fields on the create post template, so they are showing up and I can use them in the form (I'm using Cripsy forms), but after submitting, its not being saved (or something?) I'm using the CreateView and use a ModelForm to add those fields. I've followed all of the steps from the Django documentation but I can't solve it. I'm still a beginner, but I've looked everywhere for answers but nowhere I can find a specific solution to this problem. Please take a look at my code. I'm using the Django Post model: class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField(max_length=300) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) I've added a forms.py file where my ModelForm is located which holds the extra fields: class AddPostCreateForm(forms.ModelForm): # forms.ModelForm i.p.v. forms.Form omdat ik gebruik maak … -
When I open the model, one field value is replaced automatically
everyone! Have a stupid issue: When I open the employee model (in django admin), one field (employee_type) value is replaced automatically, idk why... Example: I create employee, define employee type as manager, save. In DB value is manager. After that, I open employee and see employee type as sewer and if I save, that value will saved in DB. I created text choices for this field, and In DB field is defined as enum. I tried to research the issue, value isn't used from DB, always first value from text choices is used. By the way, I created same fields (enum in DB and text choices in the model) in other model. And all works properly. How can I fix it??? Models.py with the issue: class Employee(models.Model): class EmployeeType(models.TextChoices): SEWER = 'SEWER', _('Sewer') MANAGER = 'MANAGER', _('Manager') UNDEFINED = 'UNDEFINED', _('Undefined') id = models.OneToOneField(User, models.CASCADE, db_column='id', verbose_name=_('User'), primary_key=True) employee_type = models.CharField(db_column='Employee type', verbose_name=_('Employee type'), max_length=9, choices=LabourIntensity.choices, default=LabourIntensity.MEDIUM) phone = models.CharField(db_column='Phone', verbose_name=_('Phone'), max_length=255) work_xp = models.IntegerField(db_column='Work XP', verbose_name=_('Work XP'), blank=True, null=True) Another one models.py. With same fields but without issues: class Order(models.Model): class OrderStatus(models.TextChoices): CREATED = 'Created', _('Created') CANCELLED = 'Cancelled', _('Cancelled') IN_PROGRESS = 'In progress', _('In progress') COMPLETED = 'Completed', … -
Framework, front-end, back-end, full stack? Or not to learn a framework?
I have several questions. I am a student and am training in web development. I have practically finished developing my first site which uses HTML, CSS, Javascript, PHP and MySQL. I want to acquire a certain ease in web development, but in theory this will not become my job, nor my daily life. I am about to start a bigger project (several months of development to be expected) because I am starting to be confident and have the capacities of my ambitions (not crazy either). Basically I'm more Python, not web development. So I would like to know if it is important to learn a framework? Especially since not wishing to be professionalized, therefore not specialized in front-end or back-end, I would prefer to solidify myself in full-stack knowledge for the moment. I have heard of Symfony (PHP), Node.js (JS), Bootstap (JS), etc ... But these are specialized front or back frameworks. If I have to learn a framework I would prefer it to be full-stack. And I ask myself the question if Django will not be what I need since it is a Python web framework. But is it good? Is it "full-stack" or just back-end? Isn't it a … -
Django querryset annotate and aggregation
I have a few models for which I am trying to create custom managers and query sets. In this example, I want to get the total paid amount throughout all the orders for each customer. But unfortunately, I will keep getting the wrong values, why?! Here is an example of some of my models: class customer(models.Model): name = models.CharField(max_length=100, blank=False, null=False) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="customer") objects=CustomerManager() #My customer manager class order(models.Model): paid = models.DecimalField(default=0.00, max_digits=30, decimal_places=2) customer = models.ForeignKey(customer, on_delete=models.CASCADE, related_name="order") class order_item(models.Model): quantity = models.PositiveIntegerField(default=0, null=False) price = models.DecimalField(decimal_places=2, max_digits=30, default=0.00) product = models.ForeignKey(product, on_delete=models.CASCADE, related_name="order_item") order = models.ForeignKey(order, on_delete=models.CASCADE, related_name="order_item") Here is my manager: class CustomerManager(models.Manager): def get_queryset(self): return CustomerManagerQuerry(self.model, using=self.db) def get_customer_stats(self): return self.get_queryset().customer_stats() Querryset: class CustomerManagerQuerry(models.QuerySet): def customer_stats(self): table = self.annotate(total_paid=Sum('order__paid', output_field=FloatField())) return table.values('total_paid') My goal is to get the summation of paid attributes throughout the orders for the customer. When the order object includes only one order_item the querryset outputs the correct value, But when the order object contains more than one order_item I will get the wrong result. For example when I run the code customer.objects.get_customer_stats() for only one customer who has only one order with the paid amount of 10.0, I will … -
How to send excel file as a download link button by email using celery?
I need to send an excel file as a download link button in html template by Email using celery my question: do I need to use a field to save the file and use it as a url ? or can I send the export data directely to the html template button as a file ? can I : send the file with generate http so can the user download it ? the target: the data is huge and limit of gmail is 20mb for a file attached,for this need to make it as a download link button not send it as an attached file task.py dataset = OrderResource().export(queryset=queryset) export_data = format_type.export_data(dataset) # Send E-mail start here NotificationSender.send(user, SalesReportEmail(file_name, export_data, content_type)) the celery here is for send the file and email and it doesn't return any thing to the views.py and for that I think I can't use http response the process : the user select the file format then the function send this format to celery "task.py" to collect data and send it by email as a file download link, the funcion here "in views.py " only shows pop up message say that "Please allow few minutes, the report … -
Django dj-rest-auth + react: What is the best way to activate your email when ACCOUNT_EMAIL_VERIFICATION = 'mandatory'?
I'm currently building a django & dj-rest-auth + react project and have my allauth ACCOUNT_EMAIL_VERIFICATION = 'mandatory'. Currently and by default, the email activation link can only make a GET request to dj_rest_auth.registration.views.VerifyEmailView (source code) that only accepts a POST request with the activation key as a body param: Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit Subject: [example.com] Please Confirm Your E-mail Address From: webmaster@localhost To: firstlast@email.com Date: Sun, 04 Apr 2021 09:56:05 -0000 Message-ID: <161753016543.13016.12022069896332406678@DESKTOP-LFBEG3D> Hello from example.com! You're receiving this e-mail because user firstlast@email.com has given your e-mail address to register an account on example.com. To confirm this is correct, go to http://localhost:8000/users/registration/account-confirm-email/MjQ:1lSzUD:OVzw0T279ufU2FyzHhKbWo2oilnya9x9vfQLJ6WgEzw Thank you for using example.com! example.com [04/Apr/2021 02:56:05] "POST /users/registration/ HTTP/1.1" 201 18797 And I don't know how to make a POST request through a link that's embedded in an email sent by Django. My current solution is to modify the get_email_confirmation_url method by replacing the absolute_uri with my frontend react route. Then from there I'll make a POST request to VerifyEmailView so that the user doesn't have to look at my backend views. Is there a good or standard way to dynamically add my frontend domain instead of hardcoding http://localhost:5000 and https://production.com into my … -
Django Subdomains
I want to create a mutitenant site with subdomains. Meaning, users will sign up with email, password and company name. Although, I am still experimenting with the email. Upon register, they will be redirected to a subdomain like company_name.domain.com. Right now, I am using the package Django-Subdomains I have setup as specified in their doc. But I dont quite get how to set up the views. For instance, my register view is this class RegisterStaff(View): template = 'account/register.html' def get(self, request, ): register_form = StaffRegisterationForm() context = { 'register_form': register_form, } return render(request, template_name=self.template, context=context) def post(self, request): register_form = StaffRegisterationForm(request.POST) if register_form.is_valid(): staff = register_form.save() password = register_form.cleaned_data['password1'] email = register_form.cleaned_data['email'] print(dir(request)) my_user = authenticate(request, email=email, password=password) login(request, my_user, ) request.subdomain = request.user.email print(request.subdomain) return redirect('account:dashboard', subdomain=request.subdomain) else: print(register_form.errors) return HttpResponse('form is invalid') and I have my dashboard vies below. class Dashboard(View): template = 'account/dashboard.html' def get(self, request): try: staff = Staff.objects.get(email=request.subdomain) except Staff.DoesNotExist: raise Http404 Normaly, I would thought that after registration, I should be redirected to email.domain.com. But I get a 404 instead. Please help if you are familiar with this package. my Url from Django.urls import path from .views import RegisterStaff, Dashboard, LogoutUser,LoginUser app_name = 'account' … -
property field is not shown in api call in django rest framework
I am trying to add a property field to my serializer while creating Order objects creating the OrderItem objects at the same time. But it is not shown in the result while calling the post api. There is no price filed in the result as shown here. My models: class OrderItem(models.Model): #user = models.ForeignKey(User,on_delete=models.CASCADE, blank=True #orderItem_ID = models.UUIDField(max_length=12, editable=False,default=str(uuid.uuid4())) orderItem_ID = models.CharField(max_length=12, editable=False, default=id_generator) order = models.ForeignKey(Order,on_delete=models.CASCADE, blank=True,null=True,related_name='order_items') item = models.ForeignKey(Product, on_delete=models.CASCADE,blank=True, null=True) order_variants = models.ForeignKey(Variants, on_delete=models.CASCADE,blank=True,null=True) quantity = models.IntegerField(default=1) #total_item_price = models.PositiveIntegerField(blank=True,null=True,default=0) ORDER_STATUS = ( ('To_Ship', 'To Ship',), ('Shipped', 'Shipped',), ('Delivered', 'Delivered',), ('Cancelled', 'Cancelled',), ) order_item_status = models.CharField(max_length=50,choices=ORDER_STATUS,default='To_Ship') @property def price(self): return self.quantity * self.item.varaints.price # return total_item_price My serializers: class OrderItemSerializer(serializers.ModelSerializer): order = serializers.PrimaryKeyRelatedField(read_only=True) price = serializers.ReadOnlyField() class Meta: model = OrderItem fields = ['id','order','orderItem_ID','item','order_variants', 'quantity','order_item_status','price'] # depth = 1 Here I have put price in the serializer field, there is no error, but it doesnt show the price in the api in postman. class OrderSerializer(serializers.ModelSerializer): billing_details = BillingDetailsSerializer() order_items = OrderItemSerializer(many=True) user = serializers.PrimaryKeyRelatedField(read_only=True, default=serializers.CurrentUserDefault()) class Meta: model = Order fields = ['id','user','ordered_date','order_status', 'ordered', 'order_items', 'total_price','billing_details'] # depth = 1 def create(self, validated_data): user = self.context['request'].user if not user.is_seller: order_items = validated_data.pop('order_items') billing_details = validated_data.pop('billing_details') order = … -
unable to read .replit: unable to decode .replit: Near line 5 (last key parsed 'run'): Key 'run' has already been defined
so effectively I am tryinning to run a Django website that i can share the link. The issue is the RUN file with the .replit file. I need to pip install crispy forms then run the server. How can this be accomplished in the .replit file? tried the following: language = "python3" run = "pip install django-crispy-forms" run = "python manage.py runserver 0.0.0.0:3000"