Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do i upload a image from user side to media folder from views and models in django? [closed]
my views.py file from django.core.files.storage import FileSystemStorage from django.shortcuts import render, redirect from mcatagory.models import sub_catagory, product from PIL import Image # Create your views here. def addproduct(request): scat = sub_catagory.objects.all() # scat = sub_catagory.objects.raw( # 'SELECT id FROM mcatagory_sub_catagory WHERE catagory_id_id=%s',[sub_catagory]) added = False if request.method == 'POST': p_name = request.POST.get("p_name") p_price = request.POST.get("p_price") p_desc = request.POST.get("p_desc") img = request.POST.get("image") s_cat = request.POST.get("s_cat_id") status = 0 data = product(p_name=p_name,p_price=p_price, p_desc=p_desc, image=img, sub_catagory_id=s_cat, status=status) data.save() added = True print("Thai Gayu !!!") return render(request, 'customer/rentproduct.html', {'sub_catagory': scat, 'added': added}) else: return render(request, 'customer/rentproduct.html', {'sub_catagory': scat}) -
Django admin Form with dynamic field addition
I study in Django and I have a task. There is data with a list of periods. These periods can be either five or twenty. And I need to create a form in to add this data. Periods will be added using the two fields start_period and end_period. The task is that when adding data, the user in the admin panel could add periods as much as necessary, when changing data accordingly, too. I see this as a form with the ability to dynamically add the required number of fields start_period and end_period, then saving data with periods in either json or in a separate table, the problem is that I don’t know how to implement dynamic adding of a field. Unfortunately, I could not find an adequate solution to this problem. I found something close to this through Formsets, but this is not what we are looking for. Who can tell how to implement this? python 3.7, Django 3.0.4 -
Database connection Error while hosting site on heroku
So I was trying to host my first Django app on heroku. Took help form some Youtube channels. I used postgresql as my database. Now when I tried hosting my app on heroku the following error is showing up: could not connect to server: Connection refused Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432?``` **This is the error showing** -
How to pass a dictionary in DestroyAPI SUccess MEssage
class ExampleDestroyView(DestroyAPIView): serializer_class = PetSerializer def perform_destroy(self, instance): self.data = {} self.data['status'] = True /// Some Code /// self.data['msg'] = "It removed" return self.data def get_queryset(self, *args, **kwargs): self.data Here is my Sample Class ..... In this I need to Delete an objet.... It's deleting But I am unable to pass the following Dict As an OutPut How can I pass the status and a message in a dictionary -
Updating value of a model
I am newbie of Django. And I don't understand how Django model works. First, I am trying to create a model of user score in users/models.py, so each user has a score variable to store their own score, and score can be updated. Then, in my morse_logs/game1.html, i will ask a question as simple as 1+1 to user, then i retrieve the answer and compare it in morse_logs/views.py to see if it is correct, if it is correct, I will add 5 score to that user; if incorrect, no score is added. So now I am struggling to define a correct model for setting a field for user to have their own score, and I wonder how can I update and retrieve the score of the user in view.py. users/models.py from django.db import models from django import forms from django.contrib.auth.models import User from django.db.models.signals import post_save # Create your models here. class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) description = models.CharField(max_length=100, default='') #score = models.CharField(User, max_length=10, default=0) def create_profile(sender, **kwargs): if kwargs['created']: user_profile = UserProfile.objects.create(user=kwargs['instance']) post_save.connect(create_profile, sender=User) class UserScore(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) score = models.CharField(max_length=1000, default=0) date_added = models.DateTimeField(auto_now_add=True) def __str__(self): """Returns a string representation of the model""" return … -
Django Channels - self.channel_layer.group_send not calling function
I'm creating a game with chat/voting functionality. I have made it in oTree which is based on the Django Web Framework. The chat works and is made with Django Channels, in each game a person has a network with other players and needs to vote/answer a question. I have defined a "send_choice" function in my consumer but when I reference that as the type it never gets instansiated. routing.py from . import consumers from django.conf.urls import re_path websocket_routes = [ re_path(r'ws/chat/(?P<group_pk>[0-9]+)$', consumers.ChatConsumer), re_path(r'ws/network_voting/(?P<player_pk>[0-9]+)/(?P<group_pk>[0-9]+)$', consumers.NetworkVoting) ] consumers.py class NetworkVoting(AsyncJsonWebsocketConsumer): def clean_kwargs(self): self.player_pk = self.scope['url_route']['kwargs']['player_pk'] self.group_pk = self.scope['url_route']['kwargs']['group_pk'] async def connect(self): self.clean_kwargs() # Join await self.channel_layer.group_add( self.connection_groups(), self.channel_name ) await self.accept() print("Connected to Network Socket") async def disconnect(self, close_code): self.clean_kwargs() await self.channel_layer.group_discard( self.connection_groups(), self.channel_name ) print("Disconnected from Network Socket") def connection_groups(self, **kwargs): group_name = self.get_group().get_channel_group_name() personal_channel = self.get_player().get_personal_channel_name() return "{}-{}".format(group_name, personal_channel) def get_player(self): return Player.objects.get(pk=self.player_pk) def get_group(self): return Group.objects.get(pk=self.group_pk) async def receive(self, text_data): self.clean_kwargs() text_data_json = json.loads(text_data) msg = text_data_json['message'] await self.channel_layer.group_send( { "type": "send_choice", "message": "Hello" } ) async def send_choice(self, event): message = event['message'] # Send message to WebSocket await self.send(text_data=json.dumps({ 'message': message })) print("Sent message") -
Django Dynamic form for manytomany
I am trying to make a form which includes the functionality of Add/Delete Row. And I am following this tutorial. The problem that I am facing is that I am unable to show the Add or remove button as well as the input fields in the form. Screenshot: Here's the template: <html> <head> <title>gffdfdf</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> </head> <body> <div class="container"> <form action="" method="post" class=""> {% csrf_token %} <h2> Team</h2> {% for field in form %} {{ field.errors }} {{ field.label_tag }} : {{ field }} {% endfor %} {{ form.players.management_form }} <h3> Product Instance(s)</h3> <table id="table-product" class="table"> <thead> <tr> <th>player name</th> <th>highest score</th> <th>age</th> </tr> </thead> {% for player in form.players %} <tbody class="player-instances"> <tr> <td>{{ player.pname }}</td> <td>{{ player.hscore }}</td> <td>{{ player.age }}</td> <td><input id="input_add" type="button" name="add" value=" Add More " class="tr_clone_add btn data_input"></td> </tr> </tbody> {% endfor %} </table> <button type="submit" class="btn btn-primary">save</button> </form> </div> <script> var i = 1; $("#input_add").click(function () { $("tbody tr:first").clone().find(".data_input").each(function () { if ($(this).attr('class') == 'tr_clone_add btn data_input') { $(this).attr({ 'id': function (_, id) { return "remove_button" }, 'name': function (_, name) { return "name_remove" + i }, 'value': 'Remove' }).on("click", function () { … -
How to use ForeignKey, ManyToManyFields and other fields of Django Relational DB into MongoDB
I am new in Django with MongoDB. Please suggest how to create models using MongoDB with relationship like ForeignKey, ManyToManyFields etc... -
Connecting js to html in django not working
I am trying to connect js to html in django. When i include script inside html file it excetutes the command, however i created seperate js file and linked to django so it does not work whereas I linked css file and it works fine , I am learning and using tutorials some of them are old and i do not know whether i am using old style and this is why linking js to django does not work. Would be happy if you could help to understand where i am doing wrong: in index.html <!DOCTYPE html> {% load staticfiles %} <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <link rel="stylesheet" href="{% static 'school/css/main.css' %}"> </head> <body> <div>{% block content %}{% endblock %} </div> <script type="text/javascript" scr="{% static 'school/js/main.js' %}"> </script> </body> </html> in settings i have : STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR,'static')] and main.js file: alert ("Hello"); My django version is my django version is 2.2.6 -
mongoengine.connection.ConnectionError: Cannot connect to database default : False is not a read preference
Django==2.2 django-rest-framework-mongoengine==3.4.1 djangorestframework==3.11.0 dnspython==1.16.0 mongoengine==0.9.0 pymongo==3.10.1 pytz==2019.3 six==1.14.0 sqlparse==0.3.1 these are the versions I am using. problems I am facing : mongoengine.connection.ConnectionError: Cannot connect to database default : False is not a read preference. again and again I am gettings this error. I want to connect to mongo atlas from my django project and then develop REST APIs for the same. solution I get: swtich to pymongo==2.8 problem: then it raises host should start with mongod:// not mongo+srv what i found pymongo 2.8 to 3.5 giving same errorS. and I am not able to resolve this error. please guide me through. for eg connect('db1223', host='mongodb+srv://admin123:'+urllib.parse.quote('admin@123')+'@enter code heresymbol-rd1il.mongodb.net/test?retryWrites=true&w=majority') what I want to accomplish is integrate django with mongo db and then develop REST APIs I have also gone through BurkovBA / django-rest-framework-mongoengine-example github repository. please please guide me.. -
Removing whitenoise form django project
I am working on a web app using django 3.0.4. Initially I was serving static files using whitenoise 5.0.1. However, now I am getting ready to put the project in production and use django storages with AWS S3 intead. I removed whitenoise from the middleware in my settings.py and uninstalled from my virtual environment as well. However when I run python manage.py runserver, I get the following error: (venv) D:\Projects\Bandar\BandarManagementPlatform>manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). April 09, 2020 - 15:33:04 Django version 3.0.4, using settings 'BandarManagementPlatform.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. Exception in thread django-main-thread: Traceback (most recent call last): File "D:\Projects\Bandar\BandarManagementPlatform\venv\lib\site-packages\django\core\servers\basehttp.py", line 45, in get_internal_wsgi_application return import_string(app_path) File "D:\Projects\Bandar\BandarManagementPlatform\venv\lib\site-packages\django\utils\module_loading.py", line 17, in import_string module = import_module(module_path) File "C:\Users\Haamid\AppData\Local\Programs\Python\Python37\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "D:\Projects\Bandar\BandarManagementPlatform\BandarManagementPlatform\wsgi.py", line 16, in <module> application = get_wsgi_application() File "D:\Projects\Bandar\BandarManagementPlatform\venv\lib\site-packages\django\core\wsgi.py", line 13, in … -
Django / Getting a specific queryset in ListView
I want to get specific queryset inside my ListView class. The queryset that I want to get is: user = User.objects.get(username=username) However, since ListView is class-based view, I can't define what I want. I tried like this: **views.py** class PostListView(ListView): model = Post template_name = 'itu_forum/home.html' context_object_name = 'posts' ordering = ['-date_posted'] # for normal view [date_posted] paginate_by = 6 def get_context_data(self, **kwargs): ctx = super(PostListView, self).get_context_data(**kwargs) ctx['title'] = 'Ana Sayfa' return ctx def get_queryset(self): queryset = super(PostListView, self).get_queryset() return queryset.filter(author.username=self.kwargs['username']) This is the url I want to use. I want to get to specific user's profile: **urls.py** path('profile/<str:username>/', views.user_profile, name='user-profile') href in My Template: href="{%url 'user-profile' queryset.username %} I completely messed up. Need help. -
Reverse for 'password_reset_confirm' not found. 'password_reset_confirm' is not a valid view function or pattern name in django
I keep getting this error: Reverse for 'password_reset_confirm' not found. 'password_reset_confirm' is not a valid view function or pattern name. The following is my code so far: urls.py app_name='stock' urlpatterns = [ path('reset_password/', auth_views.PasswordResetView.as_view(template_name='stock/password_reset.html'), name='reset_password'), path('reset_password_sent/', auth_views.PasswordResetDoneView.as_view(template_name='stock/password_reset_sent.html'), name='password_reset_done'), path('reset/<uidb64>/<token>', auth_views.PasswordResetConfirmView.as_view(template_name='stock/password_reset_form.html'), name='password_reset_confirm'), path('reset_password_complete/', auth_views.PasswordResetCompleteView.as_view(template_name='stock/password_reset_done.html'), name='password_reset_complete'), ] -
Change drop-down labels for Django UserAdmin
I have a User model with a timezone field on it: class User(AbstractBaseUser, PermissionsMixin): timezone = models.CharField( max_length=64, choices=[(tz, tz) for tz in pytz.common_timezones], default="UTC", ) When viewed in Django admin, this creates a drop-down list of timezones, but only of the names. I would like to dynamically generate labels for this drop-down that add the offset as a prefix (e.g. +02:00) and sort the list by that. I know I can create these by doing something like: choices=[ (tz, display_with_offset(tz)) for tz in pytz.common_timezones ], where display_with_offset generates the required label, but I think this would only calculate it when the migrations are run and would ignore any daylight savings changes that happen throughout the year for some regions. My admin file looks like this: class MyUserAdmin(UserAdmin): fieldsets = [ ("Info", {"fields": ("timezone")}), ] admin.site.register(models.User, MyUserAdmin) Is there a way I can dynamically set the drop-down labels? -
Not able to display icons and texts in Bootstrap Navbar
I am trying to display the brand logo followed by a compact disk image along with some text. Problem is the code for displaying icon followed by text works everywhere other than in the tag This is my code. I am using Django in the backend. {% load static %} <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"> <link href="https://fonts.googleapis.com/css2?family=Fredoka+One&display=swap" rel="stylesheet"> <link rel="stylesheet" type="text/css" href="{% static 'music/style.css' %}"/> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.13.0/css/all.css" integrity="sha384-Bfad6CLCknfcloXFOyFnlgtENryhrpZCe29RTifKEixXQZ38WheV+i/6YWSzkz3V" crossorigin="anonymous"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script> <nav class="navbar navbar-default"> <div class="container-fluid"> <!--Header--> <a class="navbar-brand" href="{% url 'music:index' %}">JBox</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#collapsibleNavbar"> <span class="navbar-toggler-icon"></span> </button> <!-- Items --> <div class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li class="nav-item"> <a class="nav-link" href="{% url 'music:index' %}"> <i class="fa fa-compact-disk"></i> Albums </a> </li> </ul> </div> </div> </nav> {% if all_albums %} <h3>All Albums:</h3> <ul> {% for album in all_albums %} <li><a href="{% url 'music:detail' album.id %}">{{album.album_title}}</a></li> {% endfor %} </ul> {% else %} <h3>You don't have any albums</h3> {% endif %} -
how to customize django forms
I created a django form using built-in django forms and then assigned variables properly. In front-end, inside html, I customized the form giving my own design instead of built-in forms but did not work. Was trying this for 3 days in a row. Somebody help. How can I make my models, forms and html make insert user data into MySQL db? forms.py: class ProductForm(forms.ModelForm): CHOICES = ( (1,'white'), (2,'silver'), (3,'grey'), (4,'black'), (5,'navy'), (6,'blue'), (7,'sky blue'), (8, 'azure'), (9, 'teal'), (10,'cyan'), (11, 'green'), (12, 'lime'), (13, 'olive'), (14, 'yellow'), (15, 'gold'), (16, 'amber'), (17, 'orange'), (18, 'brown'), (19, 'red'), (20, 'maroon'), (21, 'rose'), (22, 'violet'), (23, 'pink'), (24, 'magenta'), (25, 'purple'), (26, 'indigo'), (27, 'beige'), (28, 'ivory'), (29, 'peach'), (30, 'apricot'), (31, 'ochre'), (32, 'plum') ) CATEGORY = { ('Electronics', ( (1, 'Laptops'), (2, 'Desktops'), (3, 'Smartphones'), (4, 'Smart watches'), (5, 'Circuits'), (6, 'Audio amplifiers'), (7, 'Signal connectors'), (8, 'Audio transducers') )), ('Clothes', ( (9,'Men\'s fashion'), (10, 'Women\'s fashion'), (11, 'Boy\'s fashion'), (12, 'Girl\'s fashion') )), ('Books', ( (13, 'Non-finctions'), (14, 'Fictions'), (15, 'Self-help'), (16, 'Financial'), (17, 'Subjects'), (18, 'Action & Adventure'), (19, 'Classics'), (20, 'Comics'), (21, "Detective & Mystery"), (22, 'Romance') )), ('Beauty & Personal Care', ( (23, 'Makeup'), (24, … -
Django ModelForm. Hide models name
I have a one ModelForm: class First_Form(forms.ModelForm): class Meta: model = Post fields = ('text',) widgets = { 'text': forms.Textarea(attrs={"class": "form-control", "id": "exampleFormControlInput1", "placeholder": "Enter your YouTube link", "rows": 1, }), } On my site it's looking like: Can I hide name of ModelForm field? - "Text"? I want to show only InputField without "Text:" Thank you! -
How to handle a form and formset in the same page?
I have both a form in and a formset for the same model. The first form that I have is written in HTML because I needed some kind of widgets which Django doesn't have out of the box. models.py class MyModel(models.Model): name = models.CharField(max_length=255, null=True, blank=True) phone_number = models.CharField(max_length=255, null=True, blank=True) some_other_field = models.CharField(max_length=255, null=True, blank=True) views.py class MyView(View): def get(self, request): formset = modelformset_factory(MyModel, fields=('name', 'some_other_field', extra=2) return render(request, 'index.html', context={'formset': formset}) def post(self, request): formset = modelformset_factory(MyModel, request.POST, fields=('name', 'some_other_field')) if formset.is_valid(): formset.save() MyModel.objects.create(name=request.POST.get('name')) return HttpResponse("done") index.html <form method="post" action=""> <input type="text" name="name"> {{ formset.management_form }} {% for form in formset %} {{form}} {% endfor %} </form> This does not work at all, cause the request.POST sends all the irrelevant data to the modelformset such as in this case, the name field and I end up with this error. AttributeError: 'QueryDict' object has no attribute '__name__' -
django model form Pointfield returns different value
I’m having trouble with saving PointField using ModelForm, the data returned by cleaned_data attribute is different than what I inserted. anyone has any idea why this is happening, is it because of SRID? data = { 'point_field': (55.980385731737755, 25.39107740672915), 'id': 123 } class MyForm(forms.ModelForm): def __init__(self, *args, **kwargs): kwargs['data']['point_field'] = Point(kwargs['data']['point_field']) # Now, kwargs['data']['point_field'].coords returns (55.980385731737755, 25.39107740672915) super(MyForm, self).__init__(*args, **kwargs) form = MyForm(data=data, instance=location_obj) form.is_valid() # returns True form.cleaned_data['point_field'] # returns <Point object at 0x7f363080dc48> form.cleaned_data['point_field'].coords # returns (0.0005028803611372639, 0.00022809192914774866) >>> form.cleaned_data['point_field'].__dict__ {'_constructor_args': (((55.980385731737755, 25.39107740672915),), {}), '_ptr': <django.contrib.gis.geos.libgeos.LP_GEOSGeom_t at 0x7f363080dbf8>, '_cs': <django.contrib.gis.geos.coordseq.GEOSCoordSeq at 0x7f3630817cc0>} >>> form.cleaned_data['point_field'].srid 4326 -
How to display the course topics and topic contents in the same page in python(django)
Let me make my question clear to you guys. I'm developing an educational website where I have to design a course page. In this course page, you'll have all the topics what each course contains. When you click on any topic, its contents should show on the same page. This is my module. [Morever, If I go with a normal procedure, the content page will be displayed on the next page which I don't want. I want this to be dynamic. I want to store all the data into the database as well ] I'm just kind of confused on how to design the database for it however, I've uploaded two pictures here. Please look at them and let me know how this can be achieved. If Ajax needs to be used then let me know how it gonna be. This what I thought table should look like let me know if this can be changed in a proper way- Here is another picture of how the UI should look like. What I want here is when you click on introduction, its content page should display on the same page and in the same manner if I click on the … -
Django - rest_framework_social_oauth2 Proxy server
I have a situation, I have created a project using Django-Rest API with social auth (rest_framework_social_oauth2). In my production architecture application server doesn't have an internet access, which is connected by proxy server and load balancer. The issue is to validate the rest_framework_social_oauth2 by renderer_classes needs internet, please help me how can I apply proxy server settings to verify the rest_framework_social_oauth2 token from facebook and google-oauth2. Thanks in advance -
How to add a linked field in a view from the DetailView class?
There are two models: Document - information about the document, DocVersion - text of the document in a certain edition. Linked via ForeignKey, as one document can have several texts with different revision dates. class Document(models.Model): id = models.AutoField(primary_key=True) doc_title = models.TextField(verbose_name="Name") class DocVersion(models.Model): date_version = models.DateField(verbose_name="Version date") document = models.ForeignKey(Document, on_delete=models.CASCADE) date_start = models.DateField(verbose_name="Start date") text = models.TextField(verbose_name="Text") View based on the DetailView class. class DocumentDetailView(generic.DetailView): model = Document def get_context_data(self, **kwargs): context = super(DocumentDetailView, self).get_context_data(**kwargs) context['text'] = '?????text??????' return context How to fill text with data from the text field of the DocVersion model with the latest date_start? -
Not able to insert data into ArrayField while using psqlextra.backend with django
I have a model with an ArrayField, having JSONField as base. When I try to insert data, it gives the following error: ProgrammingError: column "data" is of type jsonb[] but expression is of type text[] LINE 1: ...e_status_code", "is_success", "error") VALUES (1, ARRAY['"a"... ^ HINT: You will need to rewrite or cast the expression. I am using psqlextra.backend as my default database engine. My model and other relevant codes are: class TestModel(models.Model): data = ArrayField( JSONField(), blank=True, ) My corresponding migration file looks like this: import django.contrib.postgres.fields import django.contrib.postgres.fields.jsonb from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('emails', '0003_auto_20200408_1351'), ] operations = [ migrations.RemoveField( model_name='TestModel', name='data', ), migrations.AddField( model_name='TestModel', name='data', field=django.contrib.postgres.fields.ArrayField(base_field=django.contrib.postgres.fields.jsonb.JSONField(), blank=True, size=None), ), ] I tried adding data like this: TestModel.objects.create( data= [{"a":"b"}, {"c":"d"}] ) -
Django - how to download a file
I am trying to create a download button in my template for a csv file generated by my website (I am new to Django). I have created the view function and updated urls.py but I get 'DoesNotExist: Page matching query does not exist' when I input the url ('http://127.0.0.1:8000/download_table'). I'd also like to know how to create a link/button to the download in my html template. views.py: def download_csv(request): table_selected = request.POST.get('Table_select') index_of_table_selected = int(re.search(r'\d+$', table_selected).group()) result_json_selected = request.session.get('result', 'missing')[index_of_table_selected] dataframe_selected = pd.read_json(result_json_selected) response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename=%s' % 'Table.csv' dataframe_selected.to_csv(path_or_buf=response, sep=';', float_format='%.2f', index=False, decimal=",") return response urls.py: urlpatterns = [ path('', views.index, {'pagename': ''}, name='home'), path('<str:pagename>', views.index, name='index'), path('download_table/', views.download_csv, name='download_csv'),] Also, what do I put in my template? Something like this? <a href="download_table/" download> Download File</a> That link returns the error TypeError: download_csv() got an unexpected keyword argument 'filepath' -
Django ORM generated query is not expected
Question desc Execute a query by django orm test_result = table1.objects.filter(q_filter).values(*groupby_columns).annotate(**{d: Sum(d) for d in data_columns}) Got an error Unknown column 'table2.column1' in 'field list' It's strange, because I execute query on model table1 but got an error on model table2 Debug print the sql print(test_result.query) I got this: SELECT `table1`.`column1`, `table1`.`column2`, SUM(`table1`.`data`) AS `data` FROM `table2` WHERE (`table1`.`column3` = 4 AND `table1`.`column4` = 0 AND `table1`.`column1` >= 2020-04-01 AND `table1`.`column1` <= 2020-04-08) GROUP BY `table1`.`column1`, `table1`.`column2` ORDER BY NULL; I'm not sure if there is a cache in django orm, and it record the query clause that I execute last time, so cause this error. It often happen, but recover after I restart my service. Env Python3.6.9 Django2.0.2 Mysql5.6 Does anyone meet this problem. Kindly to talk