Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Cannot open folder path directly from html <a> tag in Django template
I have created django template as: {% extends '_base.html' %} {% block title %}Checker{% endblock title %} {% block content %} <div class="container"> <a href="D:/Plagiarism Checker/plagiarismchecker/assignments/datasets/file161.pdf">Click to open a pdf</a> </div> {% endblock content %} Whenever I try open that link Click to open a pdf it doesnot open that link. I try this same process in plain html template it works as: <!DOCTYPE html> <html> <head> <title>Sample Code</title> </head> <body> <h1>Opening a folder from HTML code</h1> <a href="D:/Plagiarism Checker/plagiarismchecker/assignments/datasets/file161.pdf">Click to open a folder</a> </body> </html> I want to open that link from django template. But I cannot open that path. I will be very thankful if you can resolve this problem. Thank you!!! -
Django on click get main window's url
I want to get the main window's url(ie. 127.0.01:8000/add_person/N/...) on clicking the delete button in views.py request.path gives the delete button's url (i.e delete_person/id) -
Django queryset to get Top 3 users
I have a model: class RnR(models.Model): emp_sent = models.CharField(null=True, blank=True, max_length=122) badgename = models.CharField(null=True, blank=True, max_length=122) message = models.CharField(null=True, blank=True, max_length=122) emp_recvd = models.CharField(null=True, blank=True, max_length=122) date = models.DateField(null=True, blank=True) Now the data in this table will be in the following way(example): emp_sent badgename message emp_recvd date Tony great job good Steve 01/01/2020 Tony thank you thanks Nat 04/02/2020 Steve great job nice Tony 05/02/2020 Steve congo nice Nat 05/04/2020 Bruce great job nice work Clint 05/06/2020 Nat congo nice Bruce 25/06/2020 Steve great job nice Nat 05/07/2020 Nat thank you nice work Tony 15/07/2020 Steve great job nice Bruce 03/09/2020 Now I want to write a query-set that gives me the name of the Top 3 Senders (which in above example will be Steve, Nat and Tony, in that order) along with some other details like the badgename and the number of times sent and received. Here's how it will look: (Note : The following table is just to make my question more clear, in my actual code I am going to display this information in a Bootstrap Carousel using Django context) Rank Employee Name Badgename Sent Received 1 Steve great job 3 1 congo 1 0 thank you … -
Upload Pdf file through outside Api in django
Im trying to upload a pdf file using third party api from my django view. Heres My form field for file. It doesn't have any constructor. Also I added multipart/form-data on html template. My forms.py file upload field uploadFile = forms.FileField() and heres my view: if request.method == 'POST': form = FileForm(request.POST, request.FILES) if form.is_valid(): f = request.FILES['uploadFile '] URL= "Some Url" headers = {'content-type': 'application/pdf','Authorization': 'Token ' + token} r = requests.patch(URL, data=f, headers=headers) I'm not able to upload the file from the view. But files is being uploaded via postman. I'm not sure what I'm doing wrong here. -
I had 'NoneType' object has no attribute 'groups' in django
I'm new in django,I just have the error, AttributeError at /registro/ 'NoneType' object has no attribute 'groups', but my form is saving all the data views.py def register(request): if request.method == 'POST': form = CreateUserForm(request.POST) if form.is_valid(): ui = User() ui.username = request.POST.get('username') ui.password = request.POST.get('password') ui.first_name = request.POST.get('first_name') ui.last_name = request.POST.get('last_name') ui.email = request.POST.get('email') # user = User.objects.create_user(username=username,first_name=first_name,last_name=last_name,email=email,password=password) user = ui.save() obj = User.objects.latest('id') cli = Client_profile_master() cli.first_name = request.POST.get('first_name') cli.last_name = request.POST.get('last_name') cli.email = request.POST.get('email') cli.mobile_no = request.POST.get('mobile') cli.address_1 = request.POST.get('address1') cli.address_2 = request.POST.get('address2') cli.image=request.FILES.get('image') cli.user=obj # emp.save() # client = Client_profile_master.objects.create(first_name=first_name,last_name=last_name,email=email,mobile=mobile,address1=address1,address2=address2,image=image,user=obj) cli.save() username = form.cleaned_data.get('username') group = Group.objects.get(name='Client') user.groups.add(group) messages.success( request, f'Account created successfully for {username} !!!') return redirect('login') else: return redirect('/') else: form = CreateUserForm() return render(request, 'sites/register.html', {'form': form}) -
My VScode terminal is not working for me to make migrations and also runserver
I am trying to make a website through django and it seems that it keeps saying that I have an error that keep trying to correct and it seems to be correct. I have been trying to figure it out to no avail. [Here is the only error the debug is saying exist in the file][1] [here is what comes up when I try to make migrations][2] the same thing comes up when I try to run the server. any help is appreciated. clarity can be made available upon request. [1]: https://i.stack.imgur.com/HDxNl.png [2]: https://i.stack.imgur.com/ElV6A.png -
How do I loop on a queryset and get each row
ValueError : The QuerySet value for an exact lookup must be limited to one result using slicing. views.py 1. def test(request): 2. auth_user = User.objects.filter(groups=2) 3. student = MySchoolUser.objects.filter(auth_user_id=auth_user) 4. for st in student: # error on this line 5. standard1 = random.randint(1, 12) 6. section = random.choice(StandardSection.objects.filter(standard=standard1)) 7. stss = MapMySchoolUserStandardSection(myschool_user=st, standard_section=section) 8. stss.save() 9. 10. return HttpResponse('<h1>Done</h1>') models.py class AagamBaseModel(models.Model): objects = models.Manager() class Meta: managed = True abstract = True class MySchoolUser(AagamBaseModel): myschool_user_id = models.AutoField(primary_key=True) auth_user = models.OneToOneField(User, on_delete=models.CASCADE) class Meta: managed = True db_table = 'myschool_user' constraints = [ models.UniqueConstraint(fields=['auth_user'], name='unique_auth_user_for_myschool_user') ] def __str__(self): return f'{self.auth_user}' class Standard(AagamBaseModel): standard = models.IntegerField(primary_key=True) class Meta: db_table = 'standard' def __str__(self): return str(self.standard) class StandardSection(AagamBaseModel): standard_section_id = models.AutoField(primary_key=True) standard = models.ForeignKey(Standard, models.DO_NOTHING) section = models.CharField(max_length=1) class Meta: db_table = 'standard_section' def __str__(self): return f'{self.standard} {self.section}' class MapMySchoolUserStandardSection(AagamBaseModel): map_my_school_user_standard_section = models.AutoField(primary_key=True) myschool_user = models.ForeignKey(MySchoolUser, models.DO_NOTHING) standard_section = models.ForeignKey(StandardSection, models.DO_NOTHING) I am trying to add students from MySchoolUser (line 3), who belong to group 1 in django.contrib.auth.models.User (line 2), to MapMySchoolUserStandardSection randomly (line 7) that comes from a random standard (line 5) and a choice form the sections (line 6) in the standard. -
Displaying foreign key values in the form
My models look like this: class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() class PostImage(models.Model): post = models.ForeignKey(Post, default=None, on_delete=models.CASCADE) images = models.FileField(upload_to = 'post') I have created a CreateView in my views.py: class PostCreateView(CreateView): model = Post fields = ['title','content'] What do I need to do, to have the ability to add an image to my post? Will I be able to add as many images as I can (admin page allow me to do that) or will I have to add something else? -
Best way to write an If statement in Python with a queryset that is out of index?
Hey guys I'm trying to do a simple if statement in Python and I get an error any time I try to do a comparison between a queryset that is empty. What's the best way to write this code so that it doesn't give me an error if there's no fields in the check variable? If check comes up empty, then I get an error when I run the if(check[0].username == None) statement. Thanks! Here's my code: def upvote(request): postID = request.POST.get("postID") currentUser = request.POST.get("currentUser") username = request.POST.get("username") query = NewPost.objects.get(id = postID) check = Vote.objects.filter(postID = postID) & Vote.objects.filter(username = currentUser) if(check[0].username == None): query.rating = query.rating +1 query.save() query2 = User.objects.get(username = username) query2.userRanking = query2.userRanking +1 query2.save() new = Vote.objects.create(postID = postID, username = currentUser) new.save() pyautogui.hotkey('f5') return render(request) else: pyautogui.hotkey('f5') return render(request) -
How do i set the carousel (CSS materialize) positioning to be just below the nav bar instead of after 5 line breaks?
i am trying to explore carousel via materialize in CSS (for django app) Somehow i am not able to find a way to fix the size of the carousel item along with the text wrapping inside it. messed up spacing which can't be removed when i remove some of the br tags, there is a massive gap between nav bar and carousel row edge. How do i preserve the shape of the carousel item while also fixing the font at the top? {% load staticfiles %} {% load static %} {% load index %} <html lang="en"> <head> <div class="" <meta charset="UTF-8"> <title>Top AskReDDit </title> <meta charset="UTF-8"/> <meta name="viewport" content="width=device-width, initial-scale=1"/> <link rel="stylesheet" href="{% static 'style.css' %}"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css"> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> </head> <body> <nav> <div class="container nav-wrapper"> <div class="flex-container"> <h class="brand-logo center"><b>Today's Q/A</b></h> <ul id="nav-mobile" class="Center"> <li><a href="/"></a></li> </ul> </div> </nav> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css"> <script> $(document).ready(function(){ $('.carousel').carousel(); }); autoplay() function autoplay() { $('.carousel').carousel('next'); setTimeout(autoplay, 4500); } </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script> {#<section class="black">#} <style> html, body{ background-color: #FEDCC8; } .flex-container { display: flex; flex-direction: row; flex-wrap: wrap; justify-content: space-evenly; } </style> <div class="flex-container"> <div class="container-fluid"> <a class="btn waves-effect waves-light" href="/random_naturemetal_link">Cute Cat Pic <3 <i class="large material-icons left">sentiment_neutral</i> <i class="large … -
Rounding numbers up and down based on number in django
Let us considers the examples a = 14.17 b = 39.48 c = a * b = 559.4316 here when rounding to two decimals we need to get the result as 559.43 a = 21.26 b = 8.85 c = a * b = 188.151 here when rounding to two decimals we need to get the result as 188.16 (because after round to 2 decimals last digit is 5) , but i am getting 188.15 a = 14.17 b = 39.33 c = a * b = 557.3061 here when rounding to two decimals we need to get the result as 557.30 but i am getting 557.31 a = 15.9 b = 39.5 c = a * b = 628.05 here when rounding to two decimals we need to get the result as 628.06 as last digit is 5, but i am getting 628.05 Please help me so that it works fine in all the four examples -
Can I get a value from inside a field within a Django model at instantiation?
I am trying to do the following: class Entity(models.Model): entity_name = models.CharField( max_length=200, default="Entity Name") ... json_file_name = Path(f"{cwd}/entities_json/{entity_name}") import json with open(json_file_name) as f: ddd = json.load(f) As I am sure you've already guessed, I get an error because it passes "<django.db.models.fields.CharField>" as the filename. Can I get the value? Name gets a default value that matches with a default json file. When I try to do a querryset it says the Object Entity doesn't exist. Which makes sense, as it has not been instantiated yet. If I move the function to an external method after Entity Class is created, then Entity class can't create because the function doesn't exist yet. I'm sure I'm missing some basic concept, but I think would really rather have the functionality in the Entity class rather than in a View or elsewhere if possible, but I am definitely open to suggestions regarding this. -
How to ensure loop is not sutting down until it's all task are done
I'm newbie to python. I'm trying to make asyncio module for http connection using aiohttp. When I launch that connection, loop is always closing before it's all task completed. The average amount of connection is around 30,000 at once. When the user click a button to send a large amount of data from the web, the user can use other functions of my app without waiting for the result, and I want to handle the task through asyncio until its done. I want to make it stable that possibly know which connection is completed or failed. I tried to use asyncio.gather, but there was a load that could not use other functions while sending data. please let me know, if there is any onther solution and if there is any proble on my codes. Thanks. class main(): def __init__(self, params, data, attr ): self.succnt = 0 self.failcnt = 0 threading.Thread(target=self.spin_loop(params, data, attr), daemon=True).start() def spin_loop(self, params, data, attr): try: loop = asyncio.get_event_loop() except Exception as e: loop = asyncio.new_event_loop() loop.run_until_complete(self.runTask(params, data, attr)) loop.close() async def sendData(self, params, data, attr): try: # load target url and extra info from json format connInfo = apiUrlInfo(params, attr) headers = apiHeaderInfo(connInfo['HEADER'], connInfo['FORMAT']) async with … -
Export django model to database adding extra fields
For exportation into a dbdump, I need to create a table that is a exact clone of my model but with a "summary" column. Given that the model is concrete, not abstract, to subclass it is a failure, as class AnnotatedModel(MyModel): summary = m.TextField(null=True, blank=True) creates a new table with only the new field. I have attempted to use metaclass inheritance instead, but I am stuck because of the model.Meta subclass of Django BaseModel. I have got some success using add_to_class but I am not sure if it is a documented user level function. The final goal is be to be able to run a loop for x in MyTmpModel.objects.using('input').defer("summary").all(): x.pk = None x.summary = Foo(x) x.save(using='output') without modifying the original model which is in a separate package. -
Get posted value from IoT in Django
I'm getting a POST-ed data with my php like this $data = file_get_contents('php://input'); $json = json_decode($data, true); // etc... I tried the same thing with Django like this @csrf_exempt # because not csrf def some_view(request): data = request.POST.get() print(data) return HttpResponse('Hello world') but I was receiving TypeError: get() missing 1 required positional argument: 'key' so I added "" to the get() like this request.POST.get(""). But I'm getting None now. How could I receive posted data without form??? -
How to get the full name of a choice in django-model-utils
I am using django-model-utils for selecting a choice when adding new entry to the database. My models look like this: class Book(models.Model): STATUS = Choices( ('available', _('Available to borrow')), ('borrowed', _('Borrowed by someone')), ) status = models.CharField( max_length=32, choices=STATUS, default=STATUS.available, ) In my admin page its showing the full name of a choice (Available to borrow), but when I am trying to get this name to the HTML template using {{ book.status }}, I get the available instead of Available to borrow. I have tried {{ book.status.display_text }}, but it didn't work. Any idea, hot to pull up the display_text to the HTML template? -
Django receive POST data from NodeMCU ESP8266HTTPClient
Hi I'm new to Django framework and I am on a project on which to send http.POST data from NodeMCU to the web application using the Django Framework and the sent data is a string ID of the RFID card. I want to render the POST data sent by the NodeMCU to the textarea in the template below. I dont know how to handle http.POST sent by the NodeMCU using the Django Framework. I tested the views functions and it rendered data to the templates. I don't if the data is successfully sent or received. Arduino version 1.8.13 Django version 3.1.4 Any help would be appreciated views.py from django.shortcuts import render # Create your views here. def card_reg(request): id = request.POST.get('UIDresult', 'whatever') context = { 'id': id } return render(request, 'nodemcuapp/card_reg.html', context) templates/card_reg.html ''' {% extends 'nodemcuapp/main.html' %} {%block content%} <div class="container"> <br> <div class="center" style="margin: 0 auto; width:495px; border-style: solid; border-color: #f2f2f2;"> <h3 align="center" class="text-primary">Registration Form</h3> <br> <form action=" " method="POST" > {%csrf_token%} <div class="form-group"> <label class="text-primary">ID</label> <div> <textarea class="form-control" name="id" id="getUID" placeholder="Please Tag your Card to display ID" rows="1" cols="1" required>{{id}}</textarea> </div> </div> <div> <label class="text-primary">Name</label> <div> <input class="form-control" id="div_refresh" name="name" type="text" placeholder="" required> </div> </div> <div class="form-group"> … -
Override utils methods in Django allauth
in purpose to redirect user to previous page aver clicking on login I added this next request path in login URL: href="{% url 'login' %}?next={{request.path}}" this login is working as sign up and login link indeed, the problem that I am facing with this hint, that it overrides the signup redirect as well as I am using SocialAccountProvider trying to fix the code to cancel returning the previous page and redirect to the default signup link, I need to override this method in allauth/account/utils.py def get_login_redirect_url(request, url=None, redirect_field_name="next", signup=False): ret = url if url and callable(url): # In order to be able to pass url getters around that depend # on e.g. the authenticated state. ret = url() if not ret: ret = get_next_redirect_url(request, redirect_field_name=redirect_field_name) if not ret: if signup: ret = get_adapter(request).get_signup_redirect_url(request) else: ret = get_adapter(request).get_login_redirect_url(request) return ret checking the documentation there is only a way to override the AccountAdapter methods but not the utils method one Any suggestion or help will be too much appreciated -
I'm not able to run my server or make migrations?
I'm making a website on django and I seem to be having some syntax issues and its prohibiting me from being able to do anything outside of typing out the project but when I try to check it, it'll tell me that there is no error but won't send me to link to see the website and won't allow me to make migrations. Has anyone encountered this problem? I don't really know where to go from here and I don't understand the issue. Further clarification can be made upon request and pictures can be made available. ANY help is appreciated! -
Get range in string pattern using regular expression in django query
So I have a column where it stores a location with this pattern \AR(\d{1,2}L(\d{1,2}C(\d{1,2}) where R = ROCK , L = LOCATION, C = COLUMN, so lets say we have this string collection already stored in database R3L2C1 - R3L2C50 how can I query if I want to select only the range of R3L2C1 - R3L2C13 in django. -
Failed django plotly dash migration on MongoDB djongo engine
I wanted to practice django plotly dash library and MongoDB altogether. I have tried running different queries and scenarios using djongo engine alone (without using plotly dash) - worked fine. So the problems start when I am trying to configure the project to be able to render graphs using plotly dash. One of the steps from Plotly dash documentation requires making migrations. This is what I get when trying to do so: Not implemented alter command for SQL ALTER TABLE "django_plotly_dash_dashapp" ADD COLUMN "stateless_app_id" int NOT NULL Applying django_plotly_dash.0001_initial...Traceback (most recent call last): File "E:\Users\leshc\anaconda3\envs\MigLog\lib\site-packages\djongo\cursor.py", line 56, in execute params) File "E:\Users\leshc\anaconda3\envs\MigLog\lib\site-packages\djongo\sql2mongo\query.py", line 783, in init self._query = self.parse() File "E:\Users\leshc\anaconda3\envs\MigLog\lib\site-packages\djongo\sql2mongo\query.py", line 875, in parse raise e File "E:\Users\leshc\anaconda3\envs\MigLog\lib\site-packages\djongo\sql2mongo\query.py", line 856, in parse return handler(self, statement) File "E:\Users\leshc\anaconda3\envs\MigLog\lib\site-packages\djongo\sql2mongo\query.py", line 888, in _alter query = AlterQuery(self.db, self.connection_properties, sm, self._params) File "E:\Users\leshc\anaconda3\envs\MigLog\lib\site-packages\djongo\sql2mongo\query.py", line 425, in init super().init(*args) File "E:\Users\leshc\anaconda3\envs\MigLog\lib\site-packages\djongo\sql2mongo\query.py", line 84, in init super().init(*args) File "E:\Users\leshc\anaconda3\envs\MigLog\lib\site-packages\djongo\sql2mongo\query.py", line 62, in init self.parse() File "E:\Users\leshc\anaconda3\envs\MigLog\lib\site-packages\djongo\sql2mongo\query.py", line 435, in parse self._add(statement) File "E:\Users\leshc\anaconda3\envs\MigLog\lib\site-packages\djongo\sql2mongo\query.py", line 599, in _add err_sub_sql=statement) djongo.exceptions.SQLDecodeError: Keyword: int Sub SQL: ALTER TABLE "django_plotly_dash_dashapp" ADD COLUMN "stateless_app_id" int NOT NULL FAILED SQL: ('ALTER TABLE "django_plotly_dash_dashapp" ADD COLUMN "stateless_app_id" int NOT NULL',) Params: ([],) … -
How to add Cryptocurrency Payment Gateway on Django
Does anyone know what I need to know to accept cryptocurrency payments in my e-commerce created with Django framework, thanks -
How to go from one ListView to another ListView in django?
I am trying to go from one listview to another listview. In this case going from a list of authors, to a list of an authors books, and in their books to a list of all the chapters. I haven't been able to find the way of doing this. I feel like it should be something fairly simple, but I can't seem to find anything other than ListView --> DetailView. Any advice or insight would be greatly appreciated! So something like /authorlist/ <--listview /authorlist/booklist/ <--listview /authorlist/booklist/chapterlist/ <--listview /authorlist/booklist/chapterlist/chapterdetail <--detailview -
Fixing date format after data update
I am using django / ajax / jquery to update date using a modal. Currently my data is being displayed in "M d, Y" format. I am having two issues regarding this: After I update the data in the modal, the date value returns in YYYY-MM-DD format, despite the "M d, Y" format. The modal autofills with the current model info. When the date is displayed as "M d, Y", the date does not autofill in the modal, but when the date is updated and then the modal is opened again (i.e. date is currently being displayed in YYYY-MM-DD) the date autifills correctly. How can I ensure that the date displays in the correct format after updating and how can I ensure that the date is autofilled correctly in the modal? Table: <div class="col-md-8"> <h3>Expenses</h3> <table id="expenseTable" class="table table-striped"> <tr> <th>Vendor</th> <th>Date</th> <th>Amount</th> <th>Category</th> <th>Description</th> <th colspan="2">Actions</th> </tr> {% for expense in expenses %} <tr id="expense-{{expense.id}}"> <td class="expenseVendor expenseData" name="vendor">{{expense.vendor}}</td> <td class="expenseDate expenseData" name="date">{{expense.date|date:"M d, Y"}}</td> <td class="expenseAmount expenseData" name="amount">{{expense.amount}}</td> [...] <td> <button class="btn btn-success form-control" onClick="editExpense({{expense.id}})" data-toggle="modal" data-target="#myModal")>EDIT</button> </td> <td> <button class="btn btn-danger form-control" onClick="deleteExpense({{expense.id}})">DELETE</button> </td> </tr> {% endfor %} </table> </div> Modal: <!--MODAL--> <div class="modal fade" id="myModal" tabindex="-1" … -
How to update my Django database with a submit button?
I am creating a web application that will serve as a grocery store. The way I set it up is so the customer can come onto the website, click on the items that they would like to purchase, and then click a submit button to purchase those items. The problem I am running into is having a views.py function to take the information of which products were selected and subtracting 1 from the quantity of the database. """models.py""" class Post(models.Model): title = models.CharField(max_length=100) Price = models.DecimalField(max_digits=4, decimal_places=2,default=1) Sale = models.DecimalField(max_digits=4, decimal_places=2,default=1) quantity = models.IntegerField(default=1) author = models.ForeignKey(User, on_delete=models.CASCADE) category = TreeForeignKey('Category',null=True,blank=True, on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) views.py class PostListView(ListView): model = Post template_name = 'blog/home.html' # <app>/<model>_<viewtype>.html context_object_name = 'posts' def inventory(request): request.POST.getlist('products') for x in range (len('products')): a = Post.objects.get('products[x]') count = a.quantity() count -=1 a.quantity = count a.save() return HttpResponseRedirect("{% url 'profile'%}") urls.py path('user/<str:username>', UserPostListView.as_view(), name='user-posts'), path('inventory', views.inventory, name='inventory'), home.html {% extends "blog/base.html" %} {% block content %} {% for post in posts %} {% if post.quantity > 0 %} <input type="checkbox" name="products" id="product_{{ post.id }}" value="{{ post.id }}"> <article class="media content-section"> <div class="media-body"> <div class="article-metadata"> <a class="mr-2" href="{% url 'user-posts' post.author.username …