Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I am not able to load the staticfiles in my templates. What am I doing wrong?
I need to incorporate css in my templates to help them look better, but inspite of adding the static url and root, I am just not able to load it in my template. I am attaching the relevant code here. Please tell me what am I doing wrong. Thanks in advance. settings.py BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATE_DIR = os.path.join(BASE_DIR,'templates') STATIC_DIR = os.path.join(BASE_DIR,'static') STATIC_URL = '/static/' STATIC_ROOT = [STATIC_DIR,], index.html <!DOCTYPE html> {% load staticfiles %} <html lang="en"> <head> <link href="{% static 'css/index.css' %}"> </head> -
No operator matchesYou might need to add explicit type casts django postgres
i was trying to access artist_type based on id when i try domain.com/artist/3 i get this error: operator does not exist: character varying = integer LINE 1: ...main_site_artist" WHERE "main_site_artist"."artist_type" = 3 ^ HINT: No operator matches the given name and argument types. You might need to add explicit type casts. as i can see in table there are 2 artist_type with id 3. as i am filtering artist based on artist_type this is models.py: from django.db import models class artist(models.Model): CHOICES = ( (0, 'celebrities'), (1, 'singer'), (2, 'comedian'), (3, 'dancer'), (4, 'model'), (5, 'Photographer') ) artist_name = models.CharField(max_length = 50) artist_type = models.IntegerField(choices = CHOICES) description = models.TextField(max_length = 500) def __str__(self): return self.artist_name this is my database table: celeb=# select * from main_site_artist; id | artist_name | artist_type | description ----+-------------+-------------+---------------- 1 | test | 1 | test 2 | aka | 3 | aka 3 | test2 | 4 | aka 4 | sonu | 3 | aka moth 5 | norma | 0 | its norma here urls.py: from django.urls import path from . import views urlpatterns = [ path('',views.index, name='mainsite-index'), path('about/',views.about, name='mainsite-about'), path('contact/', views.contact, name='mainsite-contact'), path('artist/<int:artist_type>/',views.talent, name='mainsite-talent'), path('book_artist/', views.artist_booking, name="artist_book") ] views.py: def talent(request, … -
Please help me in building an ecommerce platform
I had to build an ecommerce platform in Django which is like myus.com, basically it should help you purchase inexpensive products of a country directly by having a store in that country. I also wanna work with API'S like taboo.com so people can interact in their own native language. I need help about how to start this project? Need a developer friend who can mentor me? I need help how to do it fast and where to find help? Some other help which you may think will be useful. -
Add Username and Client IP Address in the Django manage.py runserver default output
Could anybody please help me, how to add Username and Clinet IP Address in the Django manage.py runserver default output. currently I am seeing: [01/Jul/2019 11:34:27] "GET / HTTP/1.1" 200 237 expected result: [pid: 10|app: 0|req: 1/2] 10.176.123.254 (Logged in username/email) {86 vars in 4942 bytes} [Mon Jul 1 06:08:37 2019] GET / => generated 291 bytes in 1160 msecs (HTTP/1.1 200) 7 headers in 250 bytes (1 switches on core 0) -
How do I add points of skill tags getting for every correct main question and subquestions?
I would like to add the points of skill tags(1,2,3,4 consider as 4 skills) each of these skill tag (any number of skills)has 1 point and add each tag to main questions and sub questions. Once the student has give the correct answer for the question(main questions and sub questions), it should add the points to the main question and sub questions(if student gave correct answer to main question it redirects to next main question instead of sub question)using the Django Rest Framework with one API call. How do i can save it. Thanks! -
How can I implement individual django session for individual users visiting my page without user registration?
I am making a restaurant-ordering website where customers open the site from their own smartphone and order food. I don't want them to have their own user accounts but the website must recognize these users(from cookies or something). In short, different users must have their own sessions provided they open the website from their devices. Is this possible in Django? -
Getting filtered objects from url by passing correct attributes
I have a Django app with posts and comments with comments linked to the posts with foreign keys. I am unable to fetch the comments for a particular post. I checked my DB to make sure the foreign key is getting added correctly and it is. I tried changing the attribute name multiple times with no effect. My html code in the post detail template for get all comments button is as below: <a class="btn btn-outline-info mb-4" href="{url 'user-comments' object.id}">View Answers</a> My views.py looks like this: class PostCommentListView(ListView): model = Comment template_name = 'blog/comment.html' context_object_name = 'comments' ordering = ['-comment_date'] paginate_by = 7 def get_queryset(self): post = get_object_or_404(Comment, post_id=self.kwargs.get('post_id')) return Comment.objects.filter(post=post).order_by('-comment_date') and the url 'user-comments' is as follows: path('post/', PostCommentListView.as_view(), name='user-comments') I am getting a page not found message. Request URL: http://127.0.0.1:8000/post/15/%7Burl%20'user-comments'%20object.id%7D The current path, post/15/{url 'user-comments' object.id}, didn't match any of these. -
missing 1 required positional argument: 'pk'
I am new in Django and react. I already faced this error at last week and That times its was request URL error. yesterday I changed backend design and now its error happens again. Here is my url=> urlpatterns = [ url(r'^allowances_mas/', AllowanceAPIView.as_view()), url(r'^allowances_mas/(?P<pk>\d+)/$', AllowanceAPIView.as_view()),.... here is my put method that inside view, def put(self,request,pk): save_allowance = get_object_or_404(Allowance.objects.all(),pk=pk) data = request.data.get('allowance') serializer = AllowanceSerializer(instance=save_allowance,data=data,partial=True) if serializer.is_valid(): allowance_saved=serializer.save() return Response({"success":"Allowance '{}' updated successfully".format(allowance_saved.AllowID)}) else: return Response({"fail":"'{}'".format(serializer.errors)}) Here is url request from React axios => axios.put('http://127.0.0.1:8000/api/allowances_mas/1/', { allowance },{ headers: { 'Content-Type': 'application/json' } }) .then(res => { axios.get('http://127.0.0.1:8000/api/allowances_mas/') .then(res=>{ const resallowance=res.data.allowance; this.setState({ allowances:resallowance }); }) }) .catch(err=>{ console.log("error",err); }) .finally(fin=>{ console.log(fin); }) I can do get and post method but put and delete can't because of this error. I set the pk key and why it's still happening the error? Thanks. -
How To Populate Table With Filtered Data in Django
I am attempting to populate a table with a filtered set of data from my Manifests model using a url parameter. I believe that the problem I am having is in the Views.py line manifests = Manifests.objects.all().filter(reference=reference_id) Models.py class Manifests(models.Model): reference = models.ForeignKey(Orders) cases = models.IntegerField() description = models.CharField(max_length=1000) count = models.IntegerField() def __str__(self): return self.description Urls.py url(r'^add_manifest/(?P<reference_id>\d+)/$', add_manifest, name='add_manifest'), Views.py def add_manifest(request, reference_id): if request.method == "POST": form = CreateManifestForm(request.POST) if form.is_valid(): instance = form.save(commit=False) try: order = Orders.objects.get(id=reference_id) except Orders.DoesNotExist: pass instance.reference = order instance.save() return redirect('add_manifest', reference_id=reference_id) form = CreateManifestForm() #manifests = Manifests.objects.all() manifests = Manifests.objects.all().filter(reference=reference_id) context = { 'form': form, 'reference_id': reference_id, 'manifests' : manifests, } return render(request, 'add_manifest.html', context) template (add_manifest.html) <div class="table-responsive"> <!--<table id="manifest_table" class="table table-striped table-bordered table-sm " cellspacing="0"--> <table class="table table-striped table-bordered manifest_table" cellspacing="0" style="width="100%"> <thead> <tr> <th></th> <th style="width:10%;">Ref ID</th> <th style="width:10%;">Cases</th> <th style="width:60%;">Description</th> <th style="width:10%;">Count</th> </tr> </thead> <tbody> {% for manifests in manifests %} <tr> <td> <a href="{% url 'edit_manifest_browse' manifests.pk %}" class="btn btn-default btn-sm" role="button">Edit</a> </td> <td>{{ manifests.reference }}</td> <td>{{ manifests.cases }}</td> <td>{{ manifests.description}}</td> <td>{{ manifests.count}}</td> </tr> {% endfor %} </tbody> </table> </div> <div class="text-center"> <button type="submit" class="btn btn-primary" name="button" align="right">Subit Manifest</button> </div> </div> I want the table to … -
ValueError in a Q&A like app for linking answers to question
I am learning to build a Q&A app using Django. I have set up models for posts, comments and users. I am not able to successfully link the id for the posts to the comments. I have tried linking the comments to the posts by overriding the ModelForm on Django unsuccessfully. This is in my views.py file: class CommentCreateView(LoginRequiredMixin, CreateView): model = Comment fields = ['comment'] def form_valid(self, form): form.instance.author = self.request.user form.instance.post_id = self.kwargs['post_id'] return super(CommentCreateView, self).form_valid(form) My models.py has the model for comments are follows: class Comment(models.Model): cid = models.AutoField(primary_key=True) author = models.ForeignKey(User, on_delete=models.CASCADE) post_id = models.ForeignKey(Post, on_delete=models.CASCADE) comment = models.TextField() comment_date = models.DateTimeField(default=timezone.now) def save(self, *args, **kwargs): super(Comment, self).save(*args, **kwargs) def __str__(self): return self.comment def get_absolute_url(self): return reverse('blog-home') and my url path is as follows: path('comment/', PostCommentListView.as_view(), name='user-comments') I expect the comments to get linked with the posts via the ForeignKey. But when I tried doing the same, I get an error as described below: ValueError at /post/11/comment/ Cannot assign "11": "Comment.post_id" must be a "Post" instance. Exception Value: Cannot assign "11": "Comment.post_id" must be a "Post" instance. -
Django - "fulltext = request.GET['fulltext']" stops working after I add request return render html to function
def count(request): fulltext = request.GET['fulltext'] return render(request, 'count.html') fulltext = request.GET['fulltext'] would stop working after I added return render(request, 'count.html') to the function. If I don't add the return render, it would give me ValueError: Exception Value: The view wordcount.views.count didn't return an HttpResponse object. It returned None instead. -
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: …