Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how do I arrange toast messages with javascript
I'm working on a toast message setup where when if multiple of them are active they're not visible except the one in the front (so maybe a margin of 15px between them would help) and display them on the bottom-corner of the screen(fixed) doesn't change position when scrolling and make them disappear after 3 secs one by one. How do I go about solving this with javascript? Maybe it's possible to target "color" as in "color-green". Thx for any help! {% if messages %} {% for message in messages %} {% if message.tags == 'success' %} <div class="color-green"> <div class="color-white"> <div class="icon-success"> <i class="fas fa-check icon"></i> </div> <div class="text"> <h2>{{message}}</h2> </div> </div> </div> {% elif message.tags == 'info' %} <div class="color-blue"> <div class="color-white"> <div class="icon-info"> <i class="fas fa-info icon"></i> </div> <div class="text"> <h2>{{message}}</h2> </div> </div> </div> {% elif message.tags == 'warning' %} <div class="color-orange"> <div class="color-white"> <div class="icon-warning"> <i class="fas fa-exclamation-circle icon"></i> </div> <div class="text"> <h2>{{message}}</h2> </div> </div> </div> {% elif message.tags == 'error' %} <div class="color-red"> <div class="color-white"> <div class="icon-cross"> <i class="fas fa-times icon"></i> </div> <div class="text"> <h2>{{message}}</h2> </div> </div> </div> {% endif %} {% endfor %} {% endif %} .color-green{ bottom: 0; position: absolute; background-color: #40ff00; box-shadow: 4px … -
Django: get the percentage of tasks completed by subproject in DetailView
I have three models, srv(the main project), project(the subprojects associated with the srv model), and finally todo(tasks associated with the project model). class Srv(models.Model): srv_year = models.CharField(max_length=4) slug = AutoSlugField(populate_from = 'srv_year', always_update = True) class Project(models.Model): srv = models.ForeignKey(Srv, on_delete=models.CASCADE, null = True, blank = True) project_title = models.CharField(max_length=200, unique = True) slug = AutoSlugField(populate_from = 'project_title', always_update = True) resume = HTMLField() pub_date = models.DateTimeField(auto_now_add = True) category = models.ManyToManyField(Category) state = models.BooleanField(blank=True, null = True, default = False) weighted = models.IntegerField(blank=True, null = True) class Todo(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE, null = True, blank = True) todo_title = models.CharField(max_length=200) slug = AutoSlugField(populate_from = 'todo_title', always_update = True, null = True) user = models.ForeignKey(User, on_delete=models.CASCADE, null = True, blank = True) pub_date = models.DateTimeField(auto_now_add = True) deadline_date = models.DateField(null = True) ordering_position = models.DecimalField(max_digits=5, decimal_places=2, null = True, blank = True) state = models.BooleanField(blank = True, null = True, default = False) how get the percentage of tasks completed by project, whose project is associated with a main srv? In my view class srvdetail(DetailView): model = Srv template_name = 'srv_detail.html' slug_field = 'slug' def get_context_data(self, *args, **kwargs): context = super(srvdetail, self).get_context_data(**kwargs) srv = self.get_object() srv_projects = srv.project_set.all() for … -
How to use Django template filter in for loop?
How can I filter specific field of a model in template while using for loop. code: {% for news in news_list|position:3 %} <img class="d-block w-100 rounded slideimage" style="height:415px" src="{{news.image_link}}" alt="First slide"> <h1 class="mb-2"> {{news.title}} </h1> {% endfor %} there is a 'position' field in news model,I want to get all the news that position equal 3.I tried {% for news in news_list|position:3 %} any friend can help? -
Python django django-crontab only runs once. How can I test it running the expected every minute?
I have installed django-crontab to the python virtual environment. I am attempting to add a row to a Google sheet daily, I know the function works so I just need a cron job to trigger it. Below is my folder structure: ├── api │ ├── utils │ | └── cron.py |---manage.py Here is my cron.py # For Google API to sheets import pygsheets # The ID of spreadsheet. SPREADSHEET_ID = 'abc123' def addToGraphs(): # Use service credentials print('Attempt CRON') gs = pygsheets.authorize(service_account_file='credentials.json') spreadsheet = gs.open_by_key(SPREADSHEET_ID) graphsWorksheet = spreadsheet.worksheet_by_title('Graphs') graphsWorksheet.append_table(["29/12/2020", 1, 2, 3]) return True In my settings.py I have added CRONJOBS like so: CRONJOBS = [ ('*/1 * * * *', 'utils.cron.addToGraphs') ] Using the commands that the documentation says, I am seemingly correctly adding the cron using: python manage.py crontab add . And then able to list that correctly using: python manage.py crontab show When I run it locally using: python manage.py crontab run {taskId} The function does print out "Attempt CRON" and adds the row to the Google sheet, yay! But only once... It then just ends. When I kick off the python django server with: python manage.py runserver I get no print statement and the Google doc … -
my python shows this error: Fatal error in launcher [WinError 5] because I renamed my user folder name
take note in those paths, olduser = My old user name renameduser = my new user name that I renamed from the old one I renamed my user folder name, anytime I try to use pip it shows this error Fatal error in launcher: unable to create process using '"c:\users"olduser"\appdata\local\programs\python\python39.exe" "c:\users"renameduser"\appdata\local\programs\python\python39.exe\Scripts\pip.exe" ': The system cannot find the file specified. and anytime I try to run python it shows access denied I've been trying many ways to fix this but it's not working because I renamed my user folder name somebody should please help me I beg of you -
Template Syntax Error: Could not pass the remainder
I am currently coding my first django website, and I am experiencing some troubles with the urls. Basically wrote this in my template. <div class="post-thumbnail"><a href="{{% url 'apps' 'translator' 'phrase' %}}"> Here's the urls.py path('apps/', AppsView.as_view(), name= 'apps'), path('translator/<str:phrase>/', TranslatorView.as_view(), name='translator'), When the code runs, a Template Syntax Error appears saying it couldn't parse the remainder % url 'apps' 'translator' 'phrase' %' from '% url 'apps' 'translator' 'phrase' %. I know there's something wrong with the way I wrote the url in the template. However, I don't know how to fix it. -
Use the Djongo library to connect to the AWS DynamoDB database
someone knows if you can use the Djongo library to connect to the AWS DynamoDB database. I know that the Pynamodb library can be used but it would not be connected to the django ORM Thanks. -
How to limit Django allowed username characters?
is it possible to limit the allowed special characters in Django's usernames? the default allowed characters are: Letters, digits and @/./+/-/_ I want to be: Letters, digits and ./_ Regards -
React Native image upload to Django
I am trying to upload form data, which contains images, to a Django REST backend. The issue is that the images are not being received - only the other data. The packages I am using are: apisauce (axios wrapper) corsheaders Django REST Framework React: import client from './client'; const endpoint = '/post/'; const getListings = () => client.get(endpoint); const addListing = listing => { const form = new FormData(); form.append('title', listing.title); form.append('price', listing.price); form.append('category', listing.category.value); form.append('description', listing.description); listing.image.forEach((image, index) => form.append('image', { name: 'image' + index, type: 'image/jpeg', image: image, })); const headers = { 'Content-Type': 'multipart/form-data' } console.log("form", form); return client.post(endpoint, form, {headers}); }; export default { addListing, getListings, }; The console shows the image as such: Array [ "image", Object { "image": "file:/data/user/0/host.exp.exponent/cache/ExperienceData/%25405starkarma%252Ftest1/ImagePicker/51b79c5d-709e-42db-bebe-c0cf1792f423.jpg", "name": "image0", "type": "image/jpeg", }, ], Django APIView: class PostAPIView(APIView): parser_classes = (MultiPartParser, FormParser) def post(self, request, *args, **kwargs): print(request.data) file_serializer = PostSerializer(data=request.data) if file_serializer.is_valid(): file_serializer.save() return Response(file_serializer.data, status=status.HTTP_201_CREATED) else: return Response(file_serializer.errors, status=status.HTTP_400_BAD_REQUEST) And the response that is printed/object created is: <QueryDict: {'title': ['dfsf'], 'price': ['123'], 'category': ['2'], 'description': ['']}> Anyone have any idea why the image will not come through? Thanks! -
Default image in django model File Field?
I want a default picture in the model file field, my code is not working. The file field is empty. file = models.FileField(upload_to='team_icons', null='True', blank='True', default='pictures/picture.png') -
I am getting an error from django send_messages() AttributeError 'str' object has no attribute send_messages()
I have no idea where to start looking for the str in send_messages(); I believe my URL path isn't configured properly but I am not getting an ImproperlyConf Url error. I have attached the code for the view the URL and the template from which I am trying to send the email #views.py def email_invite(request): profile = get_object_or_404(Profile, user=request.user) if request.method == 'POST': form = EmailInviteForm(request.POST) if form.is_valid(): cd = form.cleaned_data name = f'{cd["name"]}' subject = f'{cd["name"]} has sent you a invitation' email = f'{cd["email"]}' to = [f'{cd["to"]}'] comment = f'{cd["comment"]}' with open(str(settings.BASE_DIR.joinpath('templates/profiles/email/email_invite_message.txt'))) as f: invite_message = f.read() html_template = get_template('profiles/email/email_invite_message.html').render() msg = EmailMultiAlternatives(subject, comment, invite_message, [email], [to], name) msg.attach_alternative(html_template, "text/html") msg.send() messages.success(request, 'Your email has been sent') return redirect('home') # return HttpResponseRedirect(reverse('profiles:find_friends')) else: form = EmailInviteForm() template = 'profiles/email_invite.html' context = { 'form': form, } return render(request, template, context) The URL that I think is the root of the error #urls.py path('email-invite/', views.email_invite, name='email_invite'), #email_invite.html {% extends '_base.html' %} {% load crispy_forms_tags %} {% block extra_title %}Email an invite{% endblock extra_title %} {% block content %} <div class="container"> <h1>Send a friend an invite to join you</h1> <p class="pages-p"> Use the form to invite a friend or family member to … -
load dynamic data in html modal in Django
I have single html page with dynamic images from database in Django. I also have a modal in the same page set to invisible and opens when image is clicked. My intension is when I click on any image it should open a html model with the clicked image and its description text from db. How do I display data of the current clicked image and its description. I have tried to pass {{profile.image.url}} but this gives one information on click to all images. I didn't have to give sample code on this. -
I am trying to deploy an app to Heroku with Django_tables2 and receiving "ImportError: cannot import name 'FieldDoesNotExist' "
I have been stuck on this for days now and it is driving me crazy. I have a Django app that runs perfectly until I try to render a Django_tables2 table into the template. It works perfectly when I run on localhost but for some reason when I try to migrate or deploy to Heroku I get the following logs: (venv) home@Trevors-MacBook-Pro MHRH % heroku run python manage.py migrate Running python manage.py migrate on ⬢ medicinehatregionalhospital... up, run.1733 (Free) Traceback (most recent call last): File "manage.py", line 23, in <module> main() File "manage.py", line 19, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/__init__.py", line 377, in execute django.setup() File "/app/.heroku/python/lib/python3.8/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/app/.heroku/python/lib/python3.8/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/app/.heroku/python/lib/python3.8/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/app/.heroku/python/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/app/.heroku/python/lib/python3.8/site-packages/django_tables2/__init__.py", line 2, in <module> from .tables import Table, TableBase, … -
Django Context Processor more than one filter
Im new to Django and python and i have the context processor below but as soon as i try to filter by one than one option it returns an empty queryset? from . models import Job from datetime import date def add_variable_to_context(request): today = date.today() jobs = Job.objects.filter(date_due__lte=today,status='Assigned') overdue = 0 for job in jobs: overdue += 1 return { 'overdue': overdue, 'jobs': jobs, } Can you pass more than one filter in a context processor like you can in a view? -
The value of 'fieldsets[4][1]' must be a dictionary
I user AbstractUser to create my custom account model in Django. Now I have a class in admins.py like so: class CustomAccountAdmin(UserAdmin): model = CustomAccount add_form = CustomAccountCreationForm fieldsets = ( *UserAdmin.fieldsets,( ('Access', {'fields': ('status', 'team', 'role')} ), ('Other', {'fields': ('phone', 'address', 'description')} ) ) ) admin.site.register(CustomAccount, CustomAccountAdmin) I want to add more fields to my custom account admin and I get this error: django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: ERRORS: <class 'account.admin.CustomAccountAdmin'>: (admin.E010) The value of 'fieldsets[4][1]' must be a dictionary. System check identified 1 issue (0 silenced). This format is working properly but I want to add more: fieldsets = ( *UserAdmin.fieldsets,( ('Access', {'fields': ('status', 'team', 'role')} ) ) ) -
Though office 365 authenticated my credentials but still not login
I have implemented sign in office 365 integration in my app, though ms office 365 authenticated mt credentials but when it is redirecting it redirects me to the home page and I am still not login into the application any idea?? -
Visualize data from elasticsearch in django app
I'm currently struggling on how to approach this. Currently I have a web application built with django and I have quite some data in elasticsearch. The web app should retrieve data from elastic, process this data and present this data graphically to the user (pie charts, tables, ...). Processing the data from elasticsearch will require some sorting/aggregating/deduplicating/adding up/... . I'm considering the following approaches for now: Get data from elastic via normal queries, process data further in web app using standard python and visualize it using some library (e.g., d3.js). Get data from elastic via normal queries in kibana, visualize data in kibana and integrate visualization in web app (not sure if this is going to work). Get data via elastic eland, convert to pandas data-frame, process data with pandas and visualize data using some library (e.g., d3.js). I'm strongly considering this approach currently. Is one of this approaches a good idea, what would be a better approach? Btw: I have quite some experience in Splunk and with Splunk queries this could be done easily - but Splunk is too expensive for this project :( Thank you! -
django get view method name on permission classes like actions
I have a custom permission like: def has_permission(self, request, view): print("view", view) I am calling list() method of ListModelMixin. Here when I print the value of veiw it gives me class name of the view. But what I want is the name of the method that is being called, in this case list. In view set we can get method name from action attribute. Is there anyway I can get name of the method not the class ?? -
How to apply if else, if the keyword entered in search bar does not exists in Django
I have created a search button in my blogging application that returns the posts with the similar title. views.py has def search(request): query = request.GET.get('query') posts = Post.objects.filter(title__icontains=query).order_by('-date_posted') params = {'posts' : posts} return render(request, 'blog/search.html' , params) base.html <form method="get" class="form-inline my-2my-lg-0 " action="{% url 'search' %}"> <input class="form-control nav-item nav-link text-secondary" type="search" name="query" id="query" placeholder="Search" aria-label="Search"> <button class="btn btn-outline-success nav-item nav-link ml-1">Search</button> </form> and search.html {% for post in posts %} <!-- starting loop (posts is keyword from view) --> <article class="media content-section"> <img class="rounded-circle article-img" src="{{post.author.profile.image.url}}"> <div class="media-body"> <div class="article-metadata"> <a class="mr-2" href="{% url 'user-posts' post.author.username %}">{{ post.author }}</a> <small class="text-muted">{{ post.date_posted | date:"F d, Y" }}</small> </div> <h2><a class="article-title" href="{% url 'post-detail' post.id%}">{{ post.title }}</a></h2> <p class="article-content">{{ post.content|slice:":200" }}</p> {% if post.content|length > 200 %} <div class="btn-group-sm"> <a class="btn btn-outline-secondary" href="{% url 'post-detail' post.id%}">Read More &rarr;</a> </div> {% endif %} </div> </article> {% endfor %} Now if the the user enters a keyword that is similar to the title of any post then those posts are returned. If no post title matches that keyword a black page is returned. Instead of a blank page I want a paragraph saying that "no post matches the title " -
Django Debug View, in Production for Admins
I know that settings.DEBUG should be False in production. Nevertheless I would like to show the great django debug view in production, if the current user is authenticated as an admin. I read the Error Reporting Docs, but could not find a setting to turn this on. If it is easier to enable a different debug-view, this would be great, too. At least I want to see a nice stacktrace to understand quickly where the error comes from (without looking at logs). -
Update foreign key in Django rest framework model using viewsets.ModelViewSet view
I am relatively new to DRF and having hard time updating the foreign key in my model via POST request. # Model for Event. class Event(models.Model): heading = models.TextField() event_construction_site = models.ForeignKey( ConstructionSite, on_delete=models.CASCADE, related_name='construction_site_events', null=True) def __str__(self): return str(self.id) class ConstructionSiteShortSerializer(serializers.ModelSerializer): class Meta: model = ConstructionSite fields = ['id'] # Serializer for Event. class EventSerializer(serializers.ModelSerializer): event_construction_site = ConstructionSiteShortSerializer() event_posted_by = CustomUserSerializer() class Meta: model = Event fields = ('id', 'heading', 'event_construction_site') Structure of my GET response is as follows: { id: 1, heading: "Truck with formwork arrived", event_construction_site: { id: 3 } } My concern here is how can I update the id of event_construction_site? I tried updating it like as follows: { "heading": "a", "event_construction_site": {"id": 2} } Dute to id of event_construction_site being nested field I get an error that says => The `.create()` method does not support writable nested fields by default. -
Html email title get extra spaces python django
We are trying to implement the email function using python django and it shows extra spaces in the header in the mail box like the following screenshots Does anyone have ideas about this issue? It shows in Gmail and also Outlook. I already checked css and I think it doesn't cause this problem. -
How do I send a verification email using Django rest framework?
I have found this link which is very close to what I am trying to achieve but with no luck for me so far. I have email variables and other configuration set up in my settings and these are my urls.py ... path('api/v1/auth/', include('rest_auth.urls')), path('api/v1/auth/registration/', include('rest_auth.registration.urls')), re_path(r'^account-confirm-email/', VerifyEmailView.as_view(), name='account_email_verification_sent'), re_path(r'^account-confirm-email/(?P<key>[-:\w]+)/$', VerifyEmailView.as_view(), name='account_confirm_email'), ... when I am registering a new user, no problem, a token is returned and this is being printed in my console; 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: company@mail.cz To: mymail@gmail.com Date: Sat, 19 Dec 2020 18:24:23 -0000 Message-ID: <16084026335.1416.882339152> Hello from example.com! You're receiving this e-mail because user sstsringgg has given yours as an e-mail address to connect their account. To confirm this is correct, go to http://127.0.0.1:8000/api/rest-auth/account-confirm-email/MjU:1kqgtz:pZVAGbN8c4II4sI3mv8VvzVtnvo/ Thank you from example.com! example.com How do I switch from 'console printing' to real email sending? Any help would be much appreciated! -
How to insert multiple passanger informations like name, age, gender and berth information from html form in database using django
I am making a booking system in which I made a form which will ask form the number of passengers and on taking input it will make fields for the passengers. Now I want to insert the data into the database I do not how to do this, please help. -
How do i create object approval from aws management console or aws cli for S3 object
I am using Django boto3 module to upload images and videos to AWS S3 and also using cloudfront CDN. User create their account and upload images and videos to AWS S3 , but i want to put a check and implement admin approval for video and images . Currently, the images and videos uploaded in AWS s3 via Django app is public by default. Can it be possible via AWS management console or AWS cli to implement admin approval for images and videos? Please help.