Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Postback, filters and sorting data in an App using Django and AJAX
I keep having this problem where I can't order some tables by date. I'm reading this code, I didn't write it so it will be useful if anyone can give me some tips. If I miss some information, just ask me, please. The ListView code: cursor = connections['default'].cursor() start = request.GET['start'] length = int(request.GET['length']) page = int(request.GET['draw']) poll = Poll.objects.get(id=poll_id) if not can_access_poll(request, poll): return JsonResponse({"error": "An error occurred"}) date_from = None period = None date_condition_shown = '' if request.GET.get("period"): period = request.GET['period'] if period and period != 'Total': date_condition, date_condition_shown, date_previous_condition, days_difference, date_from, date_to, filtering_by_date, date_from_previous, date_to_previous, date_from_string, date_from_previous_string = build_dates( period, None) if 'venue_id' in request.GET and request.GET['venue_id'] != '0' and request.GET['venue_id'] != 'undefined': filter_venue_id = request.GET['venue_id'] elif venue_id: filter_venue_id = venue_id else: filter_venue_id = None try: total = PollUser.objects.filter(poll=poll, completed=True).count() query = 'Select v.shown_on, v.source, u.first_name, u.last_name, p.id, v.id, ve.name ' \ 'From app_polluser v ' \ 'Inner join app_customuser u on u.id = v.user_id ' \ 'Inner join app_userprofile p on p.user_id = u.id ' query += 'Left join app_session s on v.session_id = s.id ' query += 'Left join app_router r on s.router_id = r.id ' query += 'Left join app_venue ve on r.venue_id = … -
How to access get request data in django rest framework
How to access GET request data in django rest framework. In the docs, they have mentioned "For clarity inside your code, we recommend using request.query_params instead of the Django's standard request.GET" https://www.django-rest-framework.org/api-guide/requests/ But when I use request.query_params.get('some_vaue') it gives me none even though I pass the data in the request body. sample code example: class TestView(APIView): def get(self, request): test = request.query_params.get('test') print('data',test) ... ... ... When I pass some value in the body of the request in postman and print the value, it actually prints None. -
Django gives 404 Error from previous project
When I'm trying to start new Django project and to run server I have "SOURCE /lo-fi-radio HTTP/1.0" 404 1987 But it's fully new empty project with its own virtualenv. lo-fi-radio is the root directory of my previous project. There are another strange errors too. Full log: Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). You have 17 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions. Run 'python manage.py migrate' to apply them. October 02, 2019 - 17:32:41 Django version 2.2.6, using settings 'company_db_manager.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Not Found: /lo-fi-radio [02/Oct/2019 17:32:45] "SOURCE /lo-fi-radio HTTP/1.0" 404 1987 Traceback (most recent call last): File "/usr/lib/python3.6/wsgiref/handlers.py", line 138, in run self.finish_response() File "/usr/lib/python3.6/wsgiref/handlers.py", line 180, in finish_response self.write(data) File "/usr/lib/python3.6/wsgiref/handlers.py", line 274, in write self.send_headers() File "/usr/lib/python3.6/wsgiref/handlers.py", line 333, in send_headers self._write(bytes(self.headers)) File "/usr/lib/python3.6/wsgiref/handlers.py", line 453, in _write result = self.stdout.write(data) File "/usr/lib/python3.6/socketserver.py", line 803, in write self._sock.sendall(b) ConnectionResetError: [Errno 104] Connection reset by peer [02/Oct/2019 17:32:45] "SOURCE /lo-fi-radio HTTP/1.0" 500 59 ---------------------------------------- Exception happened during processing of request from ('127.0.0.1', 36856) Traceback (most recent call last): … -
How to add Q search filter in subquery
How to add a Q search filter on this view subquery. def inventary(request): credits = Credit.objects.filter(account=OuterRef('pk')).values('account_id').annotate(sum_credits=Sum('amount')) debits = Debit.objects.filter(account=OuterRef('pk')).values('account_id').annotate(sum_debits=Sum('amount')) dif =Account.objects.annotate(credit_sum=Subquery(credits.values('sum_credits')),debit_sum=Subquery(debits.values('sum_debits')),balance=F('credit_sum') F('debit_sum')).values_list('name', 'balance') context = { 'credits ': credits , 'debits ': debits , 'dif': dif, } return render(request, 'inventary/inventary.html', context) -
How can I filter out objects where todays date falls within a range of a calculated date?
Here is the code I currently have. models = Model.objects.annotate( start_range=ExpressionWrapper( F('the_date') + datetime.timedelta(days=-7), output_field=DateField(), ), end_range=ExpressionWrapper( F('the_date') + datetime.timedelta(days=-2), output_field=DateField(), ) ).filter( F('today')__range=[F('start_range'), F('end_range')] ) Obviously I can not do a range on F('now') because it's not a database column / keyword but I'm just showing that I have a variable called today that I'm trying to compare against. I feel like I'm close but could use some help wrapping this up. Note: -7 and -2 will be dynamic days but just hardcoded for example. -
In django mapping how to get complete count of choice filed
I want the Count of My (Booking Type) I have 3 Types of choices (choice field in Model) Individual, Group, and Certificate. d1 = Booking.objects.values('booking_type').annotate(booking_count=Count('booking_type')) {f.get('booking_type'): f.get('booking_count') for f in d1} Here below is the Output of Above: But why the code Will Cant give me the Count of Certificate {'GROUP': 2, 'INDIVIDUAL': 3} I Changed Values To filter also But Nothing Works -
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 %}