Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Cannot move URL to import URL in Django
django 2.2.5 I haven't been having problems moving urls until now. reporting/reporting.html (index): ... {% url "line_chart_json" %} ... reporting/views.py class LineChartJSONView(BaseLineChartView): def get_labels(self): """Return 7 labels for the x-axis.""" return ["January", "February", "March", "April", "May", "June", "July"] .... When it's in the main app url.py, it's fine from django.urls import path, include from reporting.views import LineChartJSONView urlpatterns = [ ... path('reporting/', include('reporting.urls')), path('line_chart/json/', LineChartJSONView.as_view(), name='line_chart_json'), ] When I move it to reporting from django.urls import path from . import views from .views import LineChartJSONView app_name = 'reporting' urlpatterns = [ path('', views.summary_properties_user, name='index'), path('line_chart/json/', LineChartJSONView.as_view(), name='line_chart_json'), ] I get an error coming back from it's use on reporting.html: NoReverseMatch at /reporting/ Reverse for 'line_chart_json' not found. 'line_chart_json' is not a valid view function or pattern name. I assume a simple oversight. Only a few weeks in, and Django URLs are still something to get my head around. -
How to show a message dynamically in a django app?
I've created a webapp using django where in one of the section I asks for user's feedback and on clicking the submit button I send user an email thanking him for feedback. But every time I click on submit, the page refreshes itself, the email get delivered successfully But What I want is when user click on submit I want to show a "Thank you" message right there in place of feedback form. and feedback form to get removed Here's a section of my index.html <form action="" method="POST"> {% csrf_token %} <div>{{ form.message }}</div> <div>{{ form.email }}</div> <p class="formerrors" >{{ form.email.errors.as_text }}</p> <hr> <input id="submitbutton" type="submit" name="submit" value="Submit"> </form> here's my view def index(request): if request.method == 'POST': form = FeedbackForm(request.POST) if form.is_valid(): subject = "You got a message" message = form.cleaned_data['message'] email = form.cleaned_data['email'] actual_message = "You got a message from {} \n\n {} \n\nGo to work\nWith regards".format(email,message) recipients = ['example@mail.com'] sender = 'example@mail.com' send_mail(subject, actual_message, sender ,recipients,fail_silently=False) return HttpResponseRedirect('') else: form = FeedbackForm() return render(request,'my_webapp/index.html',{'form':form}) I can do this by writing a JS onClick function but is there any better way to do this? Also the built-in django messages refreshes the page I guess and are always on … -
Django - Filter related objects
Let's say I have a list of locations where each location has a list of some objects. I want to make sure that I get these locations, but with a filtered list of objects. Here's the structure of models.py: class Location(models.Models): # fields class LocationObject(models.Models): location = models.ForeignKey(Location, related_name="objects_list") # other fields that are used in filtering Here's how I do filtering: locations = Location.objects.all() if request_square_from: locations = locations.filter(objects_list__size__gte=request_square_from) if request_square_to: locations = locations.filter(objects_list__size__lte=request_square_to) # Other filters ... The problem is that by using this method of filtering, I get in each location a list of objects in which there is at least one object that satisfies the condition in locations.filter(). This is not what I actually need. I need to exclude every object (I mean LocationObject) that doesn't satisfy the condition in the filter() method. Is there any idea to do that? -
Django Api - 'str' object has no attribute '_meta'
I get this Attribute Error 'str' object has no attribute '_meta' views.py def display_mobiles(request,*args,**kwargs): items = Mobiles.objects.all() context = { 'items': items, } data_serialized = serializers.serialize('json', context) return JsonResponse(data_serialized,safe=False) Thank you for any help -
Database design approach: suggestions needed
I am designing training video marketplace application. There is going to be Paid and Unpaid customers. For Unpaid customers, I want to provide few videos as free access for selected training package. For example, if there is total 10 training videos in a given training package, 4 videos are going to be free. But, to view remaining 6 videos, customer needs to purchase whole training package. I am not able to decide proper approach to design database tables for this scenario. Here is what I can think of. I am not sure this is going to be correct approach. First Approach: I am assuming, I need three tables like below: Customer Table (Columns: customer_id, customer info) Training Video Table (Columns: video_id, video url, free_access as boolean) Purchase Table (columns: Customer_id as foreign key, video_id as Foreign Key) When user accessing any training video, I will check if the user is paid or unpaid. For this I will take help of Purchase_table. Then on the basis of boolean free_access column, video will be served/denied. But, this seems too costly performance wise (I might be wrong on this!). Second Approach: I should create view on top of Training Video Table for Paid … -
django custom relationship #2
helo; supose i've tow models: class Product(models.Model): ref= models.CharField(max_length=12, unique=True) code_prod= models.CharField(max_length=50) description= models.CharField(max_length=150) class Detail(models.Model): ref = models.CharField(max_length=10) year= models.IntegerField() code = models.CharField(max_length=10) month = models.IntegerField() created_at = models.DateField() class Meta: db_table = 'details' to make oneToMany relationship on Detail model, we can use ForeignKey. this supose in Detail table there is column named product_id, i want know if i can use another field for example "ref" to make this relationship ? also how can i perform this SQL query : query = "select product.ref, product.description, details.year, details.code from product left join details on details.ref = product.ref where product.code = 'abcd' ; " thank you very much. -
What's wrong with this Nginx configuration that can't locate media directory?
I'm learning Django for some months. Right now I am working with a demo project of video blog which I am trying to host on a local Ubuntu Server 18.04 LTS with Gunicorn, Nginx, Redis and Postgresql. I have installed this server on Virtualbox and assigned a fixed IP. Site has been hosted and static files (html, css, js) are working well but video and a default image file of media folder are not connected. Both static and media folders are in the project root directory. I think have not configured properly the Nginx configuration file. But everything works fine with the development server. I am very new my dear and have a lack of advance programming knowledge. In this case, I am asking for your help for solving this problem. Please have a look the code bellow. Thanks in advance! Project structure part of settings.py file # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.2/howto/static-files/ STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'kiji/static') ] MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' # For sending email EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' # Redis Configuration REDIS_HOST = 'localhost' REDIS_PORT = 6379 REDIS_DB = 0 Nginx congiration server { listen 80; … -
How to access foreign key table's data in Django templates?
I want to access foreign key table's data into django templates. my code is as below. class TutorialCategory(models.Model): tutorial_category = models.CharField(max_length=200) category_summary = models.CharField(max_length=200) category_slug = models.CharField(max_length=200, default=1) class TutorialSeries(models.Model): tutorial_series = models.CharField(max_length=200) tutorial_category = models.ForeignKey(TutorialCategory, verbose_name="Category", on_delete=models.SET_DEFAULT) series_summary = models.CharField(max_length=200) Tutorial_obj = TutorialSeries.objects.get(pk=1) {{ Tutorial_obj.tutorial_series}} {{Tutorial_obj.category_summary}} // Not able to access TutorialCategory I have searched on SO also & found to use _set which I have used but still not able to access table. Pls if anyone have suggestion pls guide me . -
Django Variable Wrapped in Paragraph Tag
I am using django-ckeditor as a WYSIWYG text editor when creating posts. It captures and saves the content and the correct HTML tags without any problem. However, my template renders the variable surrounded by <p> tags, which ruins the RichTextField because <p> tags cannot be nested. As a result, it was showing all of the text (with tags) as a paragraph with no formatting. I realized that this was happening, so I changed the surrounding tags in my template to <div> tags, but when the template is loaded on the browser, it replaces the div tags with paragraph tags again. How can I get rid of the <p> tags so that my text is rendered with the correct formatting? Here is my template: {% extends 'bandwagon/base.html' %} {% block content %} <article class="media content-section"> <img src="{{ post.author.profile.image.url }}" alt="profile photo" class="rounded-circle article-img"> <div class="media-body"> <img src="{{ post.image.url }}" class="post-img"> <div class="article-metadata"> <a class="mr-2" href="{% url 'user-posts' object.author.username %}">{{ object.author }}</a> <small class="text-muted">{{ object.date_posted | date:'F d, Y'}}</small> {% if object.author == user %} <div> <a href="{% url 'post-update' object.id %}" class="btn btn-outline-secondary btn-sm mt-1 mb-1">Edit</a> <a href="{% url 'post-delete' object.id %}" class="btn btn-outline-danger btn-sm mt-1 mb-1">Delete</a> </div> {% endif %} … -
Visual Studio Code: "ImportError: No module named 'environ'" but django-environ installed
I have this problem repently. When execute the debugger I get this error: ImportError: No module named 'environ' But actually I have installed this module with pip. The version of VSC is 1.38.1 Django 2.2 django-environ installed is 0.4.5 debug config: { // Use IntelliSense to learn about possible attributes. // Hover to view descriptions of existing attributes. // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ { "name": "Python: Django", "type": "python", "request": "launch", "program": "${workspaceFolder}/manage.py", "args": [ "runserver", "--noreload" ], "django": true, "pythonPath": "${workspaceFolder}/env3/bin/python3" } ] } Any help? Ideas? Thank you! -
How to send multipart form with a file from node to django
I currently have a setup with a service running on node. This service needs to have some processing done on an audio file, so it creates a read stream of this file and sends it, with some other data, to a python Django API for this processing. My Node service essentially does this: const fs = require('fs'); const FormData = require('form-data'); const fetch = require('node-fetch'); function processFile(filepath){ const form = new FormData(); form.append('some-data', someVar); form.append('audio', fs.createReadStream(filepath)); const response = await fetch('some/url', { method: 'POST', body: form, }) .then(r => { return r.json(); }); } I then have a Django API which receives this request and will run some processing on the given file. However Django can't see the file. On the other hand if I send a file using requests (python) it works fine. What I have found so far is that requests adds a Content-Length header which node-fetch does not. Adding this manually does not solve the problem. node-fetch does add Transfer-Encoding: chunked but I don't think this should be a problem. In all cases there is the Content-Type:multipart/form-data header with a boundary defined. I have previously had this working with Flask, but there is some motivation to move … -
Show icon when boolean field in change_list view of admin with Django-jet
When showing boolean fields, there's no check/uncheck icon as in the default template of Django Admin. my Admin model class UserAdmin(UserAdmin): list_display = ['username', 'last_name', 'first_name', 'active'] search_fields = ['username', 'last_name', 'first_name', 'is_active', 'groups'] -
Is there a Reverse-ForeignKey in django?
Suppose we have the following model, class Child(models.Model): parent = models.ForeignKey(User, related_name='children') birth_date = models.DateField(null=True, blank=True) class User(models.Model): pass given a user, we can find his/her children via user.children.all() Question: How to model the following? Suppose we have a kids birthday party, and each party has one or more children Conceptually birthday-party would have a list of children class BirthdayParty(models.Model): children = models.ListForeignKey(Child, many=True) But, the best we can do with django is using mtm where a table for relation is created? class BirthdayParty(models.Model): children = models.ManyToManyField(parent) -
How to merge multiple models into one dataframe in Django
I am working in Django and my models.py look like this: class Catch(models.Model): specimen_count = models.IntegerField(blank=True, null=True) unweighed_baskets = models.FloatField(blank=True, null=True) catch_weight = models.FloatField(blank=True, null=True) class Specimen(models.Model): catch = models.ForeignKey(Catch, on_delete=models.CASCADE) fish_number = models.IntegerField(blank=True, null=True) class Observation(models.Model): specimen = models.ForeignKey(Specimen, on_delete=models.CASCADE) observation_type = models.ForeignKey(ObservationType) observation_value = models.FloatField(max_length=100) class ObservationType(models.Model): name = models.CharField(max_length=100, unique=True) data_type = models.IntegerField() What is the best way to merge all those models into one big dataframe in my views.py ? I suppose I could transform each of them into dataframes by using Panda and then merge them manually one by one until I get a complete dataframe but this sounds very inefficient. Is there a better way ? -
Anomally increase in records of table: From Order ID 54 to 86?
I've a DjangoApp hosted in Heroku. For a while it worked perfectly. In recent days I saw a strange "user" signup with this email: "accessto@hidebusiness.xyz", name: "Access", lastname: "To". He/She signed up 2 times: first as "accessto2" after with "accessto3". After that my normal record of Order was altered. Before this incident Order.id increased by 1, but around this incident it went from 54 to 86. Why? in Heroku, I'm trying to run a DataClip, but I'm getting: SELECT * FROM Order Error: Dataclip Error ERROR: syntax error at or near "Order" LINE 2: FROM Order ^ What could have happened? How can I debug this? -
import data into sqlite database with foreign key django
I want to import student's name list to database with one foreign key which is the class infomation. Namelist Model.py: name = models.CharField(max_length=100) program = models.CharField(max_length=10) classGrp = models.ForeignKey('GroupInfo', on_delete=models.SET_NULL, null=True) the data in the namelist is like this: id name program classGrp 1 ABHISHEK SINGH CE1 1 GroupInfo Model.py: class GroupInfo(models.Model): classGrp = models.CharField(max_length=10) day = models.CharField(max_length=15) The data in the groupInfo is like this: id classGrp day 1 FEP1 Tues 2 FSP1 Wed When i import the namelist data, eg as below: id name program classGrp 137 Dummy FP 2 It does not store 2, which is the classGrp. When i check the detail of the classGrp at http://127.0.0.1:8000/admin: The classGrp is in dropdownlist displaying the classgr ( FEP1,FSP1) instead of the ID (1,2). VIEW.PY: def import_studName(request): template = "import_stud.html" prompt = { 'order' : 'Kindly ensure that the order of CSV should be id, name, program, year, studType,courseType,nationality,VMSAcc,classGrp' } if request.method == "GET": return render(request, template, prompt) csv_file = request.FILES['file'] if not csv_file.name.endswith('.csv'): messages.error(request, 'This is not a csv file') data_set = csv_file.read().decode('UTF-8') io_string = io.StringIO(data_set) next(io_string) for column in csv.reader(io_string, delimiter=',', quotechar="|"): #x = GroupInfo.objects.get(pk=(column[4])) #y = Namelist.objects.get(x=) if column[8] != '': classGrp = GroupInfo.objects.get(pk = … -
How to translate a string from Cyrillic to Latin
I have a Story model. User can enter a title in Russian and I need to save alias, which will take transform from Cyrillic to Latin(not translation). For example, 'привет' will be 'privet', not 'hi'. class Story(models.Model): title = models.CharField(max_length=255) alias = models.CharField(max_length=255, null=True, blank=True) -
Django 2.2 default login url
I want to load the Django builtin login page, but not with the URL http://127.0.0.1:8000/login/, instead of this i am trying to load the login page like this URL http://127.0.0.1:8000/ I have tried : LOGIN_URL ='/login/' - (in settings.py) @login_required()- (in the app view.py) @login_required(login_url='/login/') - (in the app view.py) these both method not helped me, kindly someone help me to sort this out. project url.py urlpatterns = [ path('admin/', admin.site.urls), path('',include('home.urls')), ] project settings.py in the bottom i have included like below LOGIN_URL='/login/' LOGIN_REDIRECT_URL= 'home' LOGOUT_REDIRECT_URL ='home' in my app url # from django.urls import path, include from home.views import HomeView urlpatterns = [ path('',include('django.contrib.auth.urls')), path('home',HomeView, name='home'), ] in app view.py from django.http import HttpResponse from django.shortcuts import render @login_required(login_url='/login/') def HomeView(request): return render(request, "home.html") overall my expectation to load the Django default Login page without passing /login/ or account/login in the url. -
Submit button doesn't work in my django project
The submit button doesn't work Can't save in database {% block content %} <form class="" action="{% url 'post_create_url' %}" method="post"> {% csrf_token %} {% for field in form %} <div class="form-group"> {% if field.errors %} <div class="alert alert-danger"> {{ field.errors }} </div> {% endif %} {{ field.label }} {{ field }} </div> {% endfor %} <button type="submit" class="btn btn-primary">Create Post</button> </form> {% endblock %} -
Django List objects that will be deleted by deleting the current object
In my DeleteView template, I'd like to warn the user that deleting the current object will delete the following objects (since the db schema requires on_delete = models.CASCADE). Here is an example model: class Book(models.Model): course = models.ForeignKey(Course, related_name = 'course_books', on_delete = models.CASCADE, null = True, blank = True) class Exercise(models.Model): book = models.ForeignKey(Book, related_name = 'exercises', on_delete = models.CASCADE, null = True, blank = True) ... class Solution(models.Model): exercise = models.ForeignKey(Exercise, related_name = 'solutions', on_delete = models.CASCADE, null = True, blank = True) So, say the user wants to delete a course, I'd like to warn the user which books, exercises, and solutions will be deleted upon deleting the current book. Something to this effect: WARNING: Deleting course Programming 101 will delete Python Programming for Beginners and Python By Example. It will also delete Excersises 1-5 and solutions 1-10 This will require that I can look at the related field to see if the on_delete is set to CASCADE or not. If it is, I should add it to the list of to_be_deleted objects. I have looked to see if I can check the on_delete attribute of the field: for related_object in the_course._meta.related_objects: dir(related_object.field) But nothing shows up … -
Django authenticate method returns None
I am trying to create a user login. I am registering the user through django's admin page. Username and passwords are entered correctly. Also I have tried adding authentication backends to settings.py I have tried multiple ways but couldn't get it to work. AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', ) My code looks like below : models.py : class Account(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) views.py: def login(request): if request.method == 'POST': username = request.POST.get('user') password = request.POST.get('pass') user = authenticate(username=username, password=password) ----------> None if user: if user.is_active(): login(request, user) return HttpResponseRedirect(reverse('index')) else: return HttpResponse('Account not active') else: print('Someone tried to login and failed ') print('Username {} and passowrd {}'.format(username, password)) return HttpResponse('Invalid login details supplied!!') else: return render(request,'account/login.html', {}) -
Django & Django ORM: performance improvements to bulk updating records
I'm hoping this will be a really simple question. I just wanted some advise on the bulk updating of records. An example bulk update may go something like this: for user in User.objects.all().iterator(): user.is_active = False user.save() Is there a more efficient way to do this on the database level using the Django ORM? Would the following be more efficient: User.objects.all().update(is_active=False)? -
Why is makedirs() creating an empty file instwad of a folder?
I am creating a Django app and using Python to create an upload folder. For now, I am using static names to test. My function creates an empty file only, not a folder. I have tried both mkdir() and makedirs() with the same result. I am testing on Windows 10. This is in my model: def uploadloc(self, irun): if not os.path.exists('device1'): os.makedirs('device1') return 'device1' iimage = models.ImageField(null=True, default=None, upload_to=uploadloc) I think this should be creating a folder but it is only creating an empty file. irun is currently no used. -
Chart js does not load on page
I have the following Django code, it has a list of cards that are automatically generated and each card should be generated a Chart. However, this chart is being generated only on the first card, not the others. What can I be doing wrong? Check out my code {% extends 'base.html' %} {% load static %} {% block title %} Listagem de Linhas {% endblock title %} {% block content %} <div class="row"> {% for row in list %} <div class="col-xs-6 col-md-4"> <div class="card"> <h5 class="card-header">{{row.description}}</h5> <!--<img class="card-img-top" src="{% static 'img/gauge.png' %}" width="100" height="200" alt="Card image cap">!--> <canvas id="myChart"></canvas> <a href="{% url 'row_details' pk=row.pk %}" class="btn botao-detalhar">Detalhar</a> </div> </div> {% endfor %} </div> {% endblock content %} {% block scripts %} <script> var ctx = document.getElementById('myChart').getContext('2d'); var chart = new Chart(ctx, { // The type of chart we want to create type: 'doughnut', // The data for our dataset data: { labels: ["January", "February", "March", "April", "May"], datasets: [{ label: "My First dataset", backgroundColor: ['rgb(0, 99, 132)', 'green', 'red', 'yellow', 'orange'], borderColor: '#fff', data: [5, 10, 5, 2, 20], }] }, // Configuration options go here options: { circumference: 1 * Math.PI, rotation: 1 * Math.PI, cutoutPercentage: 90 } }); … -
Dynamic year wise data in chart.js
I am using chart.js. And i want to know how can i display dynamic date and data using the following queryset. I am using django 2.2 its i could not find any complete tutorials online. views.py def get(self, request, format=None): qs = Add.objects.annotate( month=TruncYear('date')).values('month').annotate(total_income=Sum('budget'), total_expense=Sum('expense')).order_by('month') labels = ["2019",'2020',] default_items = [100, 200 ], data = { "newlabels": labels, "newdata": default_items, } return Response(data) Template var endpoint = '/api/chart/data/' var labels = [] var defaultData = []; $.ajax({ method: "GET", url: endpoint, success: function(i){ labels = i.newlabels defaultData = i.newdata var ctx = document.getElementById('myChart'); var myChart = new Chart(ctx, { type: 'bar', data: { labels: labels, // CHANGED datasets: [{ label: 'sum', data: defaultData, // CHANGED }] } }) },