Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can i pass data from template in Django to Javascript in this specific case
I am using Google map api and i am trying to pass the data (longitude and latitude) to the template then use the data in the javascript to show a specific location. location.html {% for venue in property_listing %} {{ venue.address }}</br> <div id="long">{{ venue.longitude }}</br> <div id="lat">{{ venue.latitude }}</br> {% endfor %} javascript of the same page <script> var latitude = REPLACE HERE; var longitude = REPLACE HERE; // Initialize and add the map function initMap() { // The location of Uluru var uluru = {lat: latitude, lng: longitude}; // The map, centered at Uluru var map = new google.maps.Map( document.getElementById('map'), {zoom: 15, center: uluru}); // The marker, positioned at Uluru var marker = new google.maps.Marker({position: uluru, map: map}); } </script> I am tried to replace the value literally but it wont work. What is the best way to solve this? -
Appending lazy-loaded elements to ul causes scrollTop to jump to zero
I'm using waypoint.js library to detect when the user has scrolled to the bottom of the ul. this then triggers an axios call to my server, returning an html string. I am creating elements from this string using a template tag, removing some elements, and then appending these elements to the ul. The issue I keep running into occurs only on mobile devices. After I append these elements, and set the scrollTop to where the user was scrolled to before appending, the scroll bar jumps to the top. I have tried using setTimeout() to stall the setting of scrollTop, which works, but you can see the scrollTop jump from 0 to the saved value which is very unsightly. Container: <ul id="container" style="overflow-y: scroll;" > {% include 'myapp/items.html' %} </ul> Items: {% if content.has_previous %} <li class="loadPrev" id="loadPrev-{{content.previous_page_number}}" onclick="getPrevRows('{{ some_variable }}','{{ content.previous_page_number }}');"> </li> {% endif%} {% for item in content %} <li> nested stuff </li> {% endfor %} {% if content.has_next %} <li class="loadMore" id="loadMore-{{content.next_page_number}}" onclick="getMoreRows('{{ bookdetails.url }}', '{{ content.next_page_number }}');"> </li> {% endif %} Javascript: function getMoreRows(some_variable, page) { # destroy current waypoints so they dont get triggered again on append waypoint.destroyAll() axios.get(`my_view_url/?page=${page}`).then((res) => { let container = document.getElementById('container'); … -
Django not parsing form from POST request
I'm trying to parse an HTML form (created by Django) into a form object. This is my models.py: class Person(models.Model): name = models.CharField(max_length=14) user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True) forms.py: from django.forms import ModelForm from findapp.models import Person class PersonForm(ModelForm): class Meta: model = Person fields = ["name"] And views.py: def index(request): if request.method == 'GET': form = PersonForm() return render(request, "findapp/person.html", {"form": form}) elif request.method == 'POST': form = PersonForm(request.POST) print(form.name) The issue is that when submitting the form, I get the error 'PersonForm' object has no attribute 'name'. I've tried using request.POST["name"] instead, but that didn't work either. Here's the post data: csrfmiddlewaretoken '7RrJCisgaI6lndW3hDRi6L0MAe7OXOqcaqQe8LNu3ghgqk2Bj4jcSRGjjWEggwUi' name 'test' -
How to attach file buffer to Django Mail Queue
i have been trying to attach a xls buffer or a pdf buffer to django mail queue, but i couldn't. I try using FileResponse or HttpResponse and converting to Django File object but not fails. This is what i tryed: new_message = MailerMessage() new_message.subject = "Test" new_message.to_address = "test@gmail.com" new_message.from_address = "noreply@gmail.com" file_attachment = FileResponse('file_content_buffer', content_type='application/vnd.ms-excel') new_message.add_attachment(file_attachment) new_message.save() I got an error: 'FileResponse' object has no attribute 'file' I know that the attatchment method wait for a File Object as the documentation says: https://django-mail-queue.readthedocs.io/en/latest/usage.html#attaching-files Any idea? Thanks -
Redirecting to Admin Change Form and Return to Originating Page
Context I am creating an internal company database where all users will also have access to the admin interface (albeit with limited permissions). Further, I am creating web apps alongside the admin interface that are being hosted by Django and are written in Python, so it is easy to import functions from Django directly. Just fyi, the app being creating in this context is a Plotly Dash app, so I am not writing HTML directly, but instead using the Dash html library. Predicament I would like to include buttons on my Dash page that allow a user to modify a particular data entry, or add a new one, all via the same admin interface they already have access to. This means clicking the button will take them to the correct admin page, and then redirect back to the Dash app. Current implementation I have attempted to implement this by using Django's reverse url function to point to 'admin:app_model_change', and this seems to work perfectly. However, once the data is saved in the admin form, it redirects back to the admin page which lists all data, as would occur from within the admin. I would need for the redirect to point … -
Heroku not creating migrations dir?
look this: (venv) backend > heroku run ./manage.py makemigrations blog › Warning: heroku update available from 7.19.4 to 7.26.2 Running ./manage.py makemigrations blog on ⬢ webstation... up, run.1553 (Free) Migrations for 'blog': blog/migrations/0001_initial.py - Create model BlogPage - Create model BlogPageTag - Create model BlogPageViews - Add field tags to blogpage and (venv) backend > heroku run ls blog › Warning: heroku update available from 7.19.4 to 7.26.2 Running ls blog on ⬢ webstation... up, run.4984 (Free) admin.py apps.py code_block.py __init__.py models.py __pycache__ tests.py views.py wagtail_hooks.py first, says that the migration was created, and I have a migrations directory inside the blog, second, the "migrations" directory does not exist. I've run "makemigrations" several times, and always runs this, but the directory is never created. -
m2m returns None
When a user changes the URL of an object, the object should be removed and a new object should be created: ### other fields here ### issue = models.ManyToManyField(Issue, null=False, blank=False,) def __init__(self, *args, **kwargs): super(MyModel, self).__init__(*args, **kwargs) self.__original_url = self.url def save(self, *args, **kwargs): if self.url != self.__original_url: my_new_object = MyModel.objects.create(####) my_new_object.save() my_new_object.issue.add(self.issue) The problem is that self.issue is retuning None. I also tried my_new_object.issue.add(MyModel.objects.get(pk = self.id).issue) Same thing. What's wrong with this ? -
How do I use submit form button without refreshing the page?
I have a function in views.py which takes input (through the post-request on html page) and appends it to a list and then returns the newly appended list. Upon submitting, the whole page refreshes. I have a background element (a video on a loop). In my html file, I have changed the button type from type="submit" to type="button", which prevents the page from re-loading and continues to play background video correctly. However it doesn't seem to run my main function. I thought maybe using type="button" and then making a to run the function might work, but I might be wrong on that. I have read solutions others have posted with Javascript and AJAX; I tried to copy and paste some, but without success. I am new to programming and would really appreciate feedback and help! Thanks Tobias in views.py : def test5(request): pd = [8, 24, 'kb'] user_data = {} if request.method == 'POST': x = request.POST.get('x') pd.append(x) return render(request,'app/test5.html',{'data': pd}) in test5.html : {% extends 'app/testbase.html' %} <!-- this brings in my background video --> {% block content %} This is a test<br> [8, 24, 'kb'] <br> <script> function click_action() { } </script> <form method="post" action="/app/test5/" id="post-form"> {% csrf_token … -
Why are happening that error input is display none?
When I send my formulary the check is false and it must to render a validation error but the error is sended however it isn't rendering How can I resolve this problem Note: I add manually the small tag that appear at the bottom of the check. -
django-plotly-dash div size too small and wont change
Using Django-plotly-dash module and dash app is rendering in a very small window. is there something specific other than typical css that i can do to render this full page? I have tried updating style of the specific div as well as updating the style in the entire page. ... {% extends 'base_page.html' %} {% block content %} <head> </head> <body> {%load plotly_dash%} <div class={% plotly_class name="SimpleExample"%}> {% plotly_app name="SimpleExample" %} </div> </body> {% endblock %} ... Expecting div to be full page however it is only rendering a very small window -
django import data from views.py
I need the code of some kind in the file tree outside of where views.py is located to have a better order I have linux deepin 15.10, django 1.11 and python 2.7 This is the tree Prueba2 apps IA __init_.py codeneedit.py test_app views.py I have a file in dir IA thats need run in test_app/views.py -
How to call a view based on radio button selection in django
I am using Django for my project, I am completely new to web development and Django. Here is my requirement: I will be having 2 radio buttons, and based on the selection of radio button, few check boxes should be displayed. User will choose the check boxes and click on GO, now some script executes in the back end and a heat map will be displayed for selected check boxes. Is it possible to do the task1 using Django? If yes, how can we achieve that? Thanks, Yogi. -
Does someone have a good idea to learn Django with a simple but complete project?
I want to develop a website with Django because is very popular in the world and also it will be a good opportunity for my personal career. I need an idea for a simple but complete project with Django. Any Advice please ? -
What is it working bad and not allow to generate radius select with Django?
I am trying to do a radio select or a simple select with Django but I don't get that works. I hope a formulary with some images that can be selected with a radius bottom and the image at the top. I have tried something but when I try to print in html with a for to put a img tag near the radio select it doesn't work (The code in html that add the image isn't showing because I haven't done yet due to don't work the "for" in HTML). However with {{profile_form.choice_picture|as_crispy_field}} works fine but I can put url value as an image: html: <form action="{% url 'edit_profile' %}" method="post"> {% csrf_token %} {% for radio in profile_form.picture_choice %} {{ radio.choice_label }} <span class="radio">{{ radio.tag }}</span> {% endfor %} {{profile_form.choice_picture|as_crispy_field }} {{ user_form|crispy }} {{ profile_form.description|as_crispy_field }} <input class="btn btn-outline-info my-2 my-sm-0" type="submit" value="Guardar"> <a href="{% url 'profile' %}" class="btn btn-primary">Cancelar</a> </form> model: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) picture = models.CharField(default='users/img/default.png', blank=False, null=False, max_length=200) description = models.TextField(max_length=250, blank=True) played_tournaments = models.PositiveIntegerField(default=0) won_tournaments = models.PositiveIntegerField(default=0) def __str__(self): return f'{self.user.username} Profile' class Picture(models.Model): name = models.CharField(max_length=200, blank=False, null=False, unique=True) image = models.ImageField(upload_to='users/static/users/img', null=False, unique=True) def __str__(self): return str(self.name) forms: … -
How to get an image to display using python Django?
I am currently trying to get a profile image to be displayed on a webpage that I am building using Django. I have followed some tutorials, but the image is still not being shown. I am thinking that the issue is small but I cannot find what I either need to change or add to my code to get an image to be displayed. I have created a media folder inside the project's root directory. Within the media folder there is a profile_pics folder. I have also added a default.jpg file within the media folder. ----This is the MEDIA_ROOT and MEDIA_URL in settings.py------ MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' ---This is at the end of my urls.py file------ if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) ---This is the Model that holds the image to be displayed------ class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') ethAddress = models.CharField(max_length=42, default='') advertisement = models.ForeignKey(Advertisement, on_delete=models.CASCADE, null=True, blank=True) def __str__(self): return f'{self.user.username}' ----This is the element in my template to display the image------ <img class="rounded-circle account-img" src="{{ user.profile.image.url }}"> ----This is the view that renders the template------ @login_required @transaction.atomic def profile(request): if request.method == 'POST': u_form = UserUpdateForm(request.POST, instance=request.user) p_form = ProfileUpdateForm(request.POST, … -
How to make Django OneToOneField mutually exclusive across classes
I have: myARecord = models.OneToOneField(ClassA,...) that is used by two different classes, B and C. In the Django admin, it lets me create a B record and a C record that both reference the same A record. Two instances of either B or C cannot reference the same A record as expected. How do I enforce that mutual exclusivity for all records of both B and C classes? -
How To Make a Dropdown Automatically Populate Other Fields in Django
I have a huge Django project I am making tweaks to. I need to have one dropdown field which automatically populates two other read-only fields in an admin page. I wish to do this without saving or refreshing the page. I want to be able to see the read-only fields instantly change as I change the dropdown selection. Right now, I have the dropdown and the the two read-only fields working, but not instantly. The read-only fields only update to match the dropdown when I save, and then open that instance again. I did this by overwriting the save method: def save(self, *args, **kwargs): self.firstname = self.fullname.split()[0] self.lastname = self.fullname.split()[1] super().save(*args, **kwargs) I know there's a javascript onchange strategy that can do this, i'm just a little confused as to how to apply this to a django framework to make it behave as intended. Any help would be very much appreciated. -
How to disable django REST framework docs page
I am currently using Django REST framework and it works very well for me. The problem is that the API documentation page is public in production and I would like it to only be seen in development (localhost) or by administrators users. PS: I'm using the version 3.9.2 -
Create report table by combining two models
I have two models and I would like to combine those two models and create a table as shown in the output below. Please guide me with the view and template code. class Question(models.Model): question = models.CharField(max_length=200) alias = models.CharField(max_length=25) class Answer(models.Model) qst_id = models.ForeignKey(Question,on_delete=models.CASCADE) user_phone = models.CharField(max_length=200) user_response = models.CharField(max_length=200) created_at = models.DateTimeField(auto_now_add=True) Input Data: (Question table) qid | question | Alias ============================== 1 Your name.? Name 2 Your Age.? Age 3 Your Class? Class Data: Answer table id | qst_id | user_phone | user_response ================================================ 1 1 999999 jhony 2 2 999999 12 3 3 999999 Second class 4 1 999988 Ramesh 2 2 999988 15 3 3 999988 First class Output: (Expected ) S.No | user_phone | Name | Age | Class ============================================ 1 999999 jhony 12 second class 2 999988 ramesh 15 First class My Code: class ReportListlView(LoginRequiredMixin,ListView): model = Answers template_name = 'web/test.html' def get_context_data(self, **kwargs): pk=self.kwargs.get('pk') context = super(ReportListlView, self).get_context_data(**kwargs) context['answers'] = Answers.objects.all() context['question'] = Question.objects.all() return context temaplate/test.html <div > <table class='table table-condensed'> <tr> <th>S.No</th> <th>Phone Number</th> {% for item in question %} <th>{{ item.alias }}</th> {% endfor %} </tr> {% for item in answers %} <tr> {% ifchanged item.user_phone %} <td>{{ forloop.counter … -
Debugging an python django project
I am python developer and follow an single python django sample project. Now I face an error, still could not find the solution: "IntegrityError at /blog/1/comments/new/ NOT NULL constraint failed: blog_comment.author_id" I hope a helpful advice on this problem thanks... "models.py": class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.PROTECT) #20190613 added some code by jpanda 'on_delete' author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING, db_constraint= False) message = models.TextField() def get_absolute_url(self): return reverse('blog:post_detail', args=[self.post_id]) "views.py": class CommentCreateView(CreateView): model = Comment form_class = CommentForm def form_valid(self, form): comment = form.save(commit=False) comment.post = get_object_or_404(Post, pk = self.kwargs['post_pk']) comment.author = self.request.user comment.save() return super(CommentCreateView, self).form_valid(form) comment_new = CommentCreateView.as_view() After adding the commnents in comment form, I have to add the comments into the posting panel, but there is an error like above: I don't know the reason exactly: -
How to get request body in Django server log
I'm setting up a website using Django for its backend framework and nginx for the webserver, and I want to save all of the logs to my server, I know about nginx logs and about Django logging system, but I can't reach to request's body e.g. post request body that has been sent to my server. Nginx and Django are only logging request method, URL and date, and response status code and bytes written. How can I get access to that data? I definitely want to log the body for my POST requests. I tried some of the Django logging systems but that isn't what I want, here are some of the codes: LOG_DIR = "/var/log/django/" LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'file_django': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': os.path.join(LOG_DIR, 'django.log'), }, 'file_request': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': os.path.join(LOG_DIR, 'request_errors.log'), }, }, 'loggers': { 'django': { 'handlers': ['file_django'], 'level': 'DEBUG', 'propagate': True, }, 'django.request': { 'handlers': ['file_request'], 'level': 'DEBUG', 'propagate': True, }, }, } this is the current output of this code: Bad Request: /o/auth/token/ but I want a JSON format of the request with all of its data. -
How do I pass a variable declared in HTML to a 3rd party event listener?
I have a Django application where I declare a variable at the bottom of the <body> tag, and I'm trying to use this variable inside of a 3rd part event listener function in my javascript code, but it keeps saying the variable is undefined. I've tried passing the variable to the event listener using .bind() but that doesn't seem to work either. I've also tried getting the variable from window.allJobsiteNames but that was undefined also. <!-- index.html --> <body> <script type="text/javascript" src="{% static 'js/autoComplete.js' %}"></script> <script type="text/javascript" src="{% static 'js/siren_search.js' %}"></script> <script type="text/javascript"> var allJobsiteNames = "{{ all_jobsite_names|safe }}".replace(/'/g, '"'); </script> </body> // siren_search.js $(document).ready(function () { console.log(allJobsiteNames) // ==> prints correctly // Add an event listener to the searchbar document.querySelector("#searchbar").addEventListener("autoComplete", function (event) { console.log(event.detail); }.bind(allJobsiteNames)); // User presses enter on the search bar $('#searchbar').on('keypress', function (event) { addSearchSpinner(event); }); }); new autoComplete({ data: { src: allJobsiteNames, // allJobsiteNames is not defined }, // some code }); -
Where is pytest-django setUp method?
recently I migrated to pytest-django. I don't know how to populate test database with pytest-django In default TestCase I have this class VolanaTests(TestCase): def setUp(self): john = Olona.objects.create(anarana='Doe', fanampiny='John') alice = Olona.objects.create(anarana='Noa', fanampiny='Alice') Fampirantiana.objects.create( daty='2012-12-12', ora_1='15:00:00', ora_2='17:00:00', toerana='Eftrano', olona_1=john, olona_2=alice, ) self.url = reverse('volana', kwargs={'month': 12, 'year': 2012}) self.response = self.client.get(self.url) def test_status_code(self): self.assertEquals(self.response.status_code, 200) def test_resolve_view(self): view = resolve('/volana/12-2012') self.assertEquals(view.func, volana) def test_contain_event(self): self.assertContains(self.response, 'John - Alice') self.assertContains(self.response, '15H - 17H') self.assertContains(self.response, 'Alarobia 12') But how about def setUp(self): for pytest-django ? -
How can I solve a construction of "planning-" and "Execution"-Models in Django?
i am trying to develop a workout-tracking website with django. the idea is, to create one view to "plan" and "create" the workout, and another view to "execute" one of the saved workouts. Plan-Mode class Workout(models.Model): title = models.CharField(max_length=100) date_created = models.DateTimeField(default=timezone.now) date_updated = models.DateTimeField(auto_now_add=timezone.now) creator = models.ForeignKey(User, on_delete=models.CASCADE) class Excercise(models.Model): exercise = models.CharField(max_length=100) sets = models.PositiveIntegerField() reps = models.PositiveIntegerField() weight = models.DecimalField(max_digits=5,decimal_places=2) date_created = models.DateTimeField(default=timezone.now) date_updated = models.DateTimeField(auto_now_add=timezone.now) workout = models.ForeignKey(Workout, on_delete=models.CASCADE) Data could look like: "Leg Workout": (workout.title) { ("Squats", 5, 5, 35.5), ("Leg Press",3,8,55.15), } this is it for the Plan-Mode, works fine! and now im stuck! the Exe-Mode should look like this: title:Leg Workout exercise: Squats Set 1: n of 5 Reps with 35.5kg Set 2: n of 5 Reps with 35.5kg Set 3: n of 5 Reps with 35.5kg Set 4: n of 5 Reps with 35.5kg Set 5: n of 5 Reps with 35.5kg exercise: Leg Press Set 1: n of 8 Reps with 55.15kg Set 2: n of 8 Reps with 55.15kg Set 3: n of 8 Reps with 55.15kg i dont know how to handle the sets, reps and weight attributes. i guess i'd have to create a dynamic Model (for e.g. … -
How to get cells and return in html link
I have a table created by a sql query and have made each cell clickable. I want to redirect the cell to a link containing that is as follow : /proteintable/table[row][2nd col]/ table[row][3rdcol]/table[row][5th col]/ I have no idea how to do this, I can make the link have the current cell that was clicked on but I need the specifics specific columns from the row that was clicked. This is my code for the table so far: <table> <tr> <th>id</th> <th>peptide_id</th> <th>protein_id</th> <th>group_id</th> <th>search_id</th> <th>peptide_parsimony</th> </tr> {% for elem in elem_list %} <tr> {% for sub_elem in elem %} <td onclick="location.href='/proteintable/{{ sub_elem}}/'">{{ sub_elem }}</td> {% endfor %} </tr> {% endfor %} </table> It returns the table and redirects to the correct link but I want to return a link with specific the contatins specific cells data, specifically the url should be : /proteintable/peptide_id/protein_id/search_id/ for the row that is clicked. If possible, could you give me an example because I am new to html and have not used javascript or other languages very much. Thanks :)