Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
recipient_list isn't getting the email address in django
I'm having trouble with smtp email sending in django. I tried to get the email address using User model => get_email = User.objects.filter(is_admin=True).values_list('email') But when I pass it to recipient_list,it can't find the email address. Here is my views.py: from django.shortcuts import render from feedbacks.models import Feedback from django.contrib import messages from django.core.mail import send_mail from django.conf import settings from django.contrib.auth import get_user_model User = get_user_model() def feedback(request): status = Feedback.objects.all() get_email = User.objects.filter(is_admin=True).values_list('email') print(get_email) if request.method == 'POST': name = request.POST["name"] student_id = request.POST["student_id"] adviser_init = request.POST["adviser_init"] phone = request.POST["phone"] email = request.POST["email"] issues = request.POST["issues"] obj = Feedback.objects.create(name=name, student_id=student_id, adviser_init=adviser_init, phone=phone, email=email, issues=issues) obj.save() try: subject = 'Student Feedback' message = "Mail from Student ID:" + student_id + "\nIssue:" + issues + "" email_from = settings.EMAIL_HOST_USER send_mail(subject, message, email_from, [get_email]) messages.success(request, 'Your issue has been sent to our admin. ' 'Check feedback status for update. Thank You!') except: messages.error(request, 'Feedback Saved but not send to admin.') context = { 'status': status } return render(request, 'feedback/feedback.html', context) -
Wagtail with get_full_url is redirecting to non SSL link
I am using get_full_url to get the link of pages in my wagtail application but it redirects from HTTPs to HTTP, when I changed it to get_url pr pageurl in templates, it fixed the problem and all links were redirected to HTTPs (SSL) the only problem that I faced is in the footer as it is sent in email, and it creates a server error every time I send an email with the footer bein using pageurl this is the error that I got: raise ValueError("pageurl tag expected a Page object, got %r" % page) Exception Type: ValueError at /mission/accept_plan/ Exception Value: pageurl tag expected a Page object, got '' which does not happen with get_full_url here the code in the template: <a href="{% pageurl LIBRARY %}" referrerpolicy="origin"> library is being defined in context as this library = ( Site.find_for_request(request) .root_page.get_children() .type(LibraryPage) .first() ) return { "LIBRARY": library, } when I changed to this syntaxe: <a href="{{ LIBRARY_URL }}" referrerpolicy="origin"> library = ( Site.find_for_request(request) .root_page.get_children() .type(LibraryPage) .first() ) return { "LIBRARY_URL": library.get_full_url(), } with this last syntax no server error but it redirects to https when I am on the website is there a way to fix the get_full_url to … -
Django: send confirmation email to customer AND to admins
I am sending customers a confirmation email once the Stripe webhook handler says "Okay", but would also like to send an email to the admins, so they become aware of the new order waiting to be dealt with. I added ADMINS = [("my_name", "my_email")] to my project settings and the line mail_admins(subject_admin, body_admin) to my up to that moment functioning method in the Stripe WH handler, so: from django.core.mail import send_mail, mail_admins class StripeWH_Handler: [...] def _send_confirmation_email(self, order): send_mail(subject_customer, body_customer, my_email, [customer_email]) mail_admins(subject_admin, body_admin) [...] if order_exists: self._send_confirmation_email(order) [...] But adding that line makes the method throw a server error and my webhook fails. How can I send those two emails to both customer and admin correctly? Thank you! -
Dynamically change Django form choices depending on active tab
I have a page with 4 different tabs (music genres) displaying different information depending on the tab (songs vs number of listens). At the top of the page there is a form which allows you to filter out the information on each tab (currently from/to date). I would like to add a choice field to the form, but for the choices to change dynamically depending on which tab is active. I am not sure how to go about this, or if it is possible to pass the active tab information to the web server to use as a parameter in the request. views.py: class MusicDashboard(generic.TemplateView): template_name = "support/music/dashboard.html" form_class = forms.MusicFilter def get(self, request, *args, **kwargs): self.form = self.form_class(request.GET or None) return super().get(request, *args, **kwargs) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["form"] = self.form context["jazz"] = self._dashboard_context( models.Jazz, **kwargs ) context["classical"] = self._dashboard_context( models.Classical, **kwargs ) context["rock"] = self._dashboard_context( models.Rock, **kwargs ) context["country"] = self._dashboard_context( models.Country, **kwargs ) return context def _dashboard_context(self, music_cls, **kwargs): base_qs = music_cls.objects.all() from_date = self.request.GET.get("from_date") to_date = self.request.GET.get("to_date") if from_date: base_qs = base_qs.filter(released__gte=from_date) if to_date: base_qs = base_qs.filter(released__lte=to_date) ... # Some logic here to create a table of song vs amount of times listened to … -
AttributeError on signals.py when combine user and profile
after combined User with Custom Profile on the register template forms included with signals.py to synchronization with User models. The knowledge base was given the solution to add related_name to the models.py on OnetoOneFiedld and the issue still remains. AttributeError at /createuser 'User' object has no attribute 'profile' Request Method: POST Request URL: http://127.0.0.1:8000/createuser Django Version: 3.1.2 Exception Type: AttributeError Exception Value: 'User' object has no attribute 'profile' Exception Location: D:\Dev\main0\main\accounts\signals.py, line 16, in update_profile Python Executable: D:\Dev\main0\venv\Scripts\python.exe Python Version: 3.8.5 Python Path: ['D:\\Dev\\main0\\main', 'D:\\Dev\\main0\\venv\\Scripts\\python38.zip', 'c:\\python38\\DLLs', 'c:\\python38\\lib', 'c:\\python38', 'D:\\Dev\\main0\\venv', 'D:\\Dev\\main0\\venv\\lib\\site-packages'] Server time: Sun, 01 Nov 2020 14:34:42 +000 I try to find out what is the root cause for an error Here is the Signals.py file @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def update_profile(sender, instance, created, **kwargs): if created == False: instance.profile.save() and the views.py def CreateUser(request): if request.method == 'POST': first_name = request.POST['first_name'] last_name = request.POST['last_name'] username = request.POST['username'] password = request.POST['password1'] repassword = request.POST['password2'] email = request.POST['email'] if password == repassword: if User.objects.filter(username=username).exists(): messages.error(request, f'User {username} already existed!!!') return redirect('register-page') elif User.objects.filter(email=email).exists(): messages.error(request, f'email {email} already existed!!!') return redirect('register-page') else: user = User.objects.create_user( username=username, password=password, email=email, first_name=first_name, last_name=last_name ) user.save() profile = … -
How to include Many to Many Field in SubFactory (Django)?
I have two models: Project and Tag. In Project there is ManyToManyField: project_tags I have written factories for both of them. The problem is that I don't know how to include TagFactory to ProjectFactory I have tried: project_tags = factory.SubFactory(TagFactory) Error: TypeError: Direct assignment to the forward side of a many-to-many set is prohibited. Use project_tags.set() instead And also: Project.project_tags.set() Error: AttributeError: 'ManyToManyDescriptor' object has no attribute 'set' -
How do I rename image that I uploaded through Django Rest Framework
I have a problem in renaming an uploaded images. Instead of using the original name, I want my uploaded image to have the model['name'].jpg . I have no problems doing it if I upload it directly from django, but I cant figure out how do I do it if I upload the image through Django Rest Framework. Here is my model.py: class Shop(models.Model): date = datetime.datetime.now() year_now = int(date.strftime('%Y')) user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=20, unique=True) slug = models.SlugField(default='') logo = models.ImageField(upload_to=rename_and_path) industry = models.CharField(max_length= 20, choices=industry_choice) business_start = IntegerBoundedField(min_value=1950, max_value=year_now) franchise_start = IntegerBoundedField(min_value=1950, max_value=year_now) headquarter = models.CharField(max_length=100) units = models.IntegerField() description = models.TextField() joined = models.DateTimeField(auto_now_add=True) Here is my serializer.py: class ShopSerializer(serializers.ModelSerializer): class Meta: model = Shop fields= '['name', 'slug', 'logo', 'user', 'industry', 'business_start', 'franchise_start', 'headquarter', 'units', 'description', 'joined']' And here is my viewset in views.py: class ShopViewSet(ModelViewSet): queryset = Shop.objects.all() serializer_class = ShopSerializer lookup_field = 'slug' def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.initial_data['user'] = request.user.id serializer.initial_data['slug'] = slugify(request.data['name']) serializer.is_valid(raise_exception=True) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) So I would like to know how do I rename the uploaded image in logo field. Thanks in advanced. -
Django download file/csv file with model public properties
The model might have multiple rows from the database. For example, a User model with name, contact properties. If resultset from the database is passed, the downloaded file should contain the data. Otherwise, a file with only model properties as heading will be downloaded -
How to convert MSSQL script into django models
i have a already created database script in MSSQL and want to use it in django app. is there any way to convert that script into django models... -
Type Error while creating Nested Objects in Single Shot in Django REST Framework
I am trying to create a nested object in DRF, however, always end up with the following error: TypeError at /leads/lead/ create() takes 1 positional argument but 2 were given I am trying to receive the data through a model viewset. Each lead is supposed to have genres, languages and businesses (all three are many to many fields). This is my serializer create method: class LanguageSerializer(serializers.ModelSerializer): class Meta: model = Language fields = "__all__" class GenreSerializer(serializers.ModelSerializer): class Meta: model = Genre fields = "__all__" class BusinessSerializer(serializers.ModelSerializer): class Meta: model = Business fields = "__all__" class LeadSerializer(serializers.ModelSerializer): language_id = LanguageSerializer(many=True) genre_id = GenreSerializer(many=True) business_id = BusinessSerializer(many=True) class Meta: model = Lead fields = "__all__" def create(self, validated_data): language_data = validated_data.pop("language_id") genre_data = validated_data.pop("genre_id") business_data = validated_data.pop("business_id") languages = [] genres = [] businesses = [] lead = Lead.objects.create(**validated_data) for language in language_data: language_obj = Language.objects.create(language) lead.language_id.add(language_obj) for genre in genre_data: genre_obj = Genre.objects.create(genre) lead.genre_obj.add(genre_obj) for business in business_data: business_obj = Business.objects.create(business) lead.business_id.add(business_obj) return lead Here are the models: from django.db import models from django.conf import settings # Create your models here. class Genre(models.Model): name = models.CharField(max_length=255) ... class Language(models.Model): name = models.CharField(max_length=255) class Business(models.Model): ... name = models.CharField(max_length=255, choices=BUSINESS_CHOICES, default="other") ... … -
Problem launching docker-compose : python modules not installed
I'm getting python error, trying to do a "docker-compose up" in the app folder. I get theses errors : Traceback (most recent call last): File "/usr/lib/python3.8/site-packages/urllib3/connectionpool.py", line 670, in urlopen httplib_response = self._make_request( File "/usr/lib/python3.8/site-packages/urllib3/connectionpool.py", line 392, in _make_request conn.request(method, url, **httplib_request_kw) File "/usr/lib/python3.8/http/client.py", line 1255, in request self._send_request(method, url, body, headers, encode_chunked) File "/usr/lib/python3.8/http/client.py", line 1301, in _send_request self.endheaders(body, encode_chunked=encode_chunked) File "/usr/lib/python3.8/http/client.py", line 1250, in endheaders self._send_output(message_body, encode_chunked=encode_chunked) File "/usr/lib/python3.8/http/client.py", line 1010, in _send_output self.send(msg) File "/usr/lib/python3.8/http/client.py", line 950, in send self.connect() File "/usr/lib/python3.8/site-packages/docker/transport/unixconn.py", line 43, in connect sock.connect(self.unix_socket) FileNotFoundError: [Errno 2] No such file or directory During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/lib/python3.8/site-packages/requests/adapters.py", line 439, in send resp = conn.urlopen( File "/usr/lib/python3.8/site-packages/urllib3/connectionpool.py", line 726, in urlopen retries = retries.increment( File "/usr/lib/python3.8/site-packages/urllib3/util/retry.py", line 403, in increment raise six.reraise(type(error), error, _stacktrace) File "/usr/lib/python3.8/site-packages/urllib3/packages/six.py", line 734, in reraise raise value.with_traceback(tb) File "/usr/lib/python3.8/site-packages/urllib3/connectionpool.py", line 670, in urlopen httplib_response = self._make_request( File "/usr/lib/python3.8/site-packages/urllib3/connectionpool.py", line 392, in _make_request conn.request(method, url, **httplib_request_kw) File "/usr/lib/python3.8/http/client.py", line 1255, in request self._send_request(method, url, body, headers, encode_chunked) File "/usr/lib/python3.8/http/client.py", line 1301, in _send_request self.endheaders(body, encode_chunked=encode_chunked) File "/usr/lib/python3.8/http/client.py", line 1250, in endheaders self._send_output(message_body, encode_chunked=encode_chunked) File "/usr/lib/python3.8/http/client.py", line 1010, in _send_output self.send(msg) … -
Django - get user id from username
I would like to get user posts on a profile page. My current code is: # views.py def show_blog(request, username): # If username exists if User.objects.filter(username = username).exists(): # Get user data and rendert the page user_data = {'user': User.objects.get(username = username)} user_posts = {'posts': Post.objects.filter(author = user_data.id)} return render(request, "blogs/show_blog.html", user_data) return HttpResponse(404) # show_blog.html - later, I'll make it show user posts <h1>@{{ user }}</h1> <p>{{ user.first_name }} {{ user.last_name }}</p> Now, the problem is this error: AttributeError at /blogs/testuser/ 'dict' object has no attribute 'id' When I go to: /blogs/testuser -
How to loop through multiple array based on foreign key selection
I am trying to create a django react app. I am trying to fetch datas from django to react. I am stuck where i need to loop through multiple arrays. This is my serializer.py class ServiceSerializer(serializers.ModelSerializer): class Meta: model = Service fields = ('id', 'title', 'description') class TechnologiesAndFrameworkSerializer(serializers.ModelSerializer): class Meta: model = TechnologiesAndFramework fields = ('id', 'title', 'description', 'service') This is my models.py class Service(models.Model): title = models.CharField(blank=False, null=False, max_length=256) description = models.CharField(blank=False, null=False, max_length=256) def __str__(self): return self.title class TechnologiesAndFramework(models.Model): title = models.CharField(blank=False, null=False, max_length=256) description = models.CharField(blank=False, null=False, max_length=256) service = models.ForeignKey(Service, on_delete=models.CASCADE, null=True) def __str__(self): return self.title This is my views.py class ServiceViewSet(viewsets.ModelViewSet): serializer_class = ServiceSerializer queryset = Service.objects.all() permission_classes = [permissions.AllowAny] class TechnologiesAndFrameworkViewSet(viewsets.ModelViewSet): serializer_class = TechnologiesAndFrameworkSerializer queryset = TechnologiesAndFramework.objects.all() permission_classes = [permissions.AllowAny] So at backend, services model has Frontend Backend Deployment And my TechnologiesAndFramework has Django React JS Docker Wagtail Bootstrap Postgres I want to loop through TechnologiesAndFramework based on the Services. So the output should be like this. Frontend React JS Wagtail Bootstrap Backend Django Postgres Deployment Docker How can i achieve this format? Currently this is how my react code looks like const [service, setService] = useState([]); const [framework, setFramework] = useState([]); useEffect(() => … -
DocuSign Connect - Error - The remote server returned an error: (503) Server Unavailable
DocuSign Connect Push is showing Error - The remote server returned an error: (503) Server Unavailable. When I tried the same with postman the api is working. Any help will be appreciated.The project is hosted in heroku. -
Retreive specific data inside json body as list in django
In purpose to delete multiple data using function Product.objects.in_bulk([pk1,pk2,pk3,...]).delete() I'm trying to grab pk value from json as list for in_bulk function param. my json : [ { "Pk": 1, "Product": "testing" }, { "Pk": 2, "Product": "testing" } ] But i don't know how to achieve this in django (i'm new in django from .NET backgroud). Should i iterate each object in json in order to get each pk or there's smartest way to get list pk value ? -
Restrict every page usertype in Django
I'm been confused on how can I restrict page access without using Global variable. it's to hassle to create request.session in every pages just to get the value of the previous def function. I know there's a way such decorators etc. but I cannot found yet the best way how to implement it. Can anyone help me? Below I been using Global variable in usertype request.session['Usertype'] = usertype. Thanks for the help. def example_login(request): usertype = "Admin" request.session['type_user'] = usertype return redirect ('dashboard') def dashboard(request): value_usertype = {'usertype_var':request.session['type_user']} return render(request,'dashboard.html', value_usertype) def anotherview(request): // too hassle to create another request.session in every page value_usertype = {'usertype_var':request.session['type_user']} return render(request,'dashboard.html', value_usertype) -
Error in django unittest: 'object has no attribute' object
I started testing views, but I found an error in the test, tell me where I went wrong, I'm just starting to learn, so don't judge strictly моя views: `class MovieDetailView(Genre, DetailView): model = Movie slug_field = "url" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["star_form"] = RatingForm() return context ` my test looks like this: `def test_starform_set_in_context(self): request = RequestFactory().get('some-slug') view = MovieDetailView() view.setup(request) context = view.get_context_data() self.assertIn('star_form', context))` url: `path("<slug:slug>/", views.MovieDetailView.as_view(), name="movie_detail"),` -
Django contact form: email not sending
I'm currently building a contact form for my website in Django. The only problem is that the email is not being sent when the form is submitted. This is the code: settings.py: EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = "c******o@gmail.com" EMAIL_HOST_PASSWORD = '****' EMAIL_PORT = '587' views.py: sender_name = form.cleaned_data['nome_completo'] sender_email = form.cleaned_data['email'] message = "{0} has sent you a new message:\n\n{1}".format(sender_name, form.cleaned_data['messaggio']) send_mail('New Enquiry', message, sender_email, ['c******o@gmail.com']) My thought: Since I'm in a virtualenv, when I submit the form, the terminal displays that it was successfully submitted, and gets me back the code right, maybe the email is not sent because of that, or maybe because I'm using a gmail account? Thanks! -
bootstrap disappears in django-tables2
I have defined DJANGO_TABLES2_TEMPLATE = "django_tables2/bootstrap4.html" and bootstrap works ok on my table. Then I add this #attrs = {"class": "table_hover"} and bootstrap settings dissapares/corrupts on the table. Django version is 3.1.2 Any suggestions? Here is the code: import django_tables2 as tables from .models import State class StateTable(tables.Table): class Meta: model = State attrs = {"class": "table_hover"} orderable = True exclude = ("field_id", ) -
ValueError at /profiles/followers/admin/ Cannot query "flash": Must be "User" instance
Here I am confuse with a queryset. I just want to grab the list of followers of my followers. e.g: if user1 is in my followers list and i can see him inside the follower list template but I also want see how many followers and following does user1 have. Right now i am facing an error : ValueError at /profiles/followers/admin/ Cannot query "flash": Must be "User" instance. views.py user = context['user'] # user = self.request.POST.get("close") # print() myfollowers = user.is_following.all() myfollowers_data = [] for target_list in myfollowers: single_follower = UserProfile.objects.filter(user=target_list) single_follower_count = single_follower.is_following.count() myfollowers_data.append(single_follower_count) if more information is require than tell me in comment session, i will update my question with that information. -
how can i delete file when object is delete in Django?
i want to delete file when object is deleting or delete old file when object is updating. i am using django-cleanup for handling this logic. i am facing file required error with django-cleanup! when i try to create a new story every time FileField show error (file is required). i also define null=True in file attribute class Article(models.Model): title = models.CharField(max_length=255, help_text="Short title") content = RichTextUploadingField(blank=True) file_data = models.FileField(upload_to='stories', null=True) def __str__(self): return self.title -
I keep getting this error in django. Apparently there is something wrong with my js and urls file
[01/Nov/2020 11:56:54] "GET /static/js/moviesjs.js HTTP/1.1" 404 1668 [01/Nov/2020 11:56:54] "GET /static/js/moviesjs.js HTTP/1.1" 404 1668 This is the error it's throwing. This is my js code. $(document).ready(function() { $("#createButton").click(function() { var serializedData = $("#createMoviesForm").serialize(); $.ajax({ url: $("createMoviesForm").data('url'), data: serializedData, type: 'post', success: function(response) { $("#MovieInfo").append('<div class="card, mb=1" data-id="' + response.movieposts.id + '"><div class="card-body">' + response.movieposts.name_of_movie + '<button type="button" class="close float-right"><span aria-hidden="true">&times;</span></button></div></div>') } }) $("#createMoviesForm")[0].reset(); }); $("#movieInfo").on('click', '.card', function() { var dataId = $(this).data('id'); $.ajax({ url: '/movieposts/' + dataId + '/completed/', data: {} }) }) }); -
How can i run a Django management command in production?
I have a Django app running on a DigitalOcean using Nginx and Gunicorn with systemd, now i added to Django a management command that should run along with the Django app and perform some action. The problem is that the management command needs to run "indefinitely" just like Django does. In order to run it, in development i would do manage.py command, but of course i can't do this every time on production. Do i have to create a new systemd service for it? Thanks in advance! -
Why do we need "serialize" model field attribute?
In django.db.models.fields.__init__.py there is a class Field, that is inherited by CharFeld and others and takes some boolean serialize attribute class Field(RegisterLookupMixin): def __init__(self, verbose_name=None, ... serialize=True, ...): ... I can not find docs about it here https://docs.djangoproject.com/en/3.1/ref/models/fields/#field-attribute-reference So, why is it here and is it safe to rely on it in some custom serialization technics? -
datetime.date.today() in Django (Dash app)
I have a Plotly Dash app running in Django using the django-plotly-dash package. (https://django-plotly-dash.readthedocs.io/en/latest/) The app is live here: https://www.sunfire.xyz/data/tca There is a date picker on the dashboard, and the code for the element is this: from datetime import date, datetime, timedelta html.Div([ dcc.DatePickerRange( id='date-picker-range', min_date_allowed=date(2020, 10, 21), max_date_allowed=date.today(), initial_visible_month=date.today(), start_date=date.today() - timedelta(days=7), end_date=date.today(), display_format='DD/MM/YYYY', ), ], className="plotly-datepicker"), The max_date_allowed and the default end_date should both be datetime.date.today() (which is 1st November as I'm typing this), however it seems like today() is returning the day that the django application was started. In fact, right now it's weirdly setting max_date_allowed to 31st October, but end_date is 30th Oct. If I restart the server it works correctly, and will display 1st November. How do I get date.today() to correctly display today's date when the application is running for multiple days? FYI the views.py file for this app is importing the Dash App from .dashapps import tca_log_plotter