Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
Django reds won't work on windows or in Ubuntu production
I have React-Django application (I am using Django Rest Framework) and I am trying to integrate websockets with the channels & channels-redis package from django. I follow this tutorial along with this video tutorial but I make adjustments based on the former when necesary. I've installed pip install channels pip install channels-redis but redis doesn't seem to work at all for me on my Windows OS On the local server I've got the following configurations: settings.py ASGI_APPLICATION = "mysite.asgi.application" . . . if config('CHANNEL_LAYERS') == 'redis': CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": [os.environ.get('REDIS_URL', 'redis://localhost:6379')], }, }, } else: CHANNEL_LAYERS = { "default": { "BACKEND": "channels.layers.InMemoryChannelLayer", }, } asgi.py import os import django from django.conf.urls import url from django.core.asgi import get_asgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "trike.settings") from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter # Models from logistics.consumers import OrderConsumer django.setup() application = ProtocolTypeRouter({ # Django's ASGI application to handle traditional HTTP requests "http": get_asgi_application(), "websocket": AuthMiddlewareStack( URLRouter([ url(r"^order_update/$", OrderConsumer.as_asgi()), ]) ), }) Orders.js useEffect(() => { let wsStart = 'ws://' if (window.location.protocol === 'https:') { wsStart = 'wss://' } let endpoint = wsStart + window.location.host setSocket(new WebSocket(endpoint+'/order_update/')) }, []); useEffect(() => { console.log(socket) if (socket) { socket.onmessage = … -
React Native App not connecting via WebSocket after publishing it on the Play Store
In my application I have implemented real time application with socket and django channels that I deployed with daphne (ws://api.xxxxx.com). It works perfectly with my react native app in the development mode, where I just connect with javascript code: let socket = new WebSocket(ws://api.xxxxx.com). But the problem was when I published the app on the play store, which I just can't know why it's not connecting since I don't have any log showing the refusal of connection. These are the logs from daphne in the development mode: 1xx.x.x.x.x:45xxx - - [09/Dec/2020:23:27:34] "WSCONNECTING /ws/xxxxx/90/" - - 1xx.x.x.x.x:45xxx - - [09/Dec/2020:23:27:34] "WSCONNECT /ws/xxxxx/90/" - - With the play store version app, the daphne logs are just empty. Can anyone help me on how to solve this? -
Django - Implementing a Simple Search Bar
I'm new to Django and implementing a simple search bar on a site to search for article titles (This is for a class). No matter what I try, when I search for an article name that exists, the homepage just stays exactly the same, and only the URL changes to http://127.0.0.1:8000/?q=Apple. So everything after the ?q= is the title of the article (this one is called Apple). But the page I'm on stays the same and doesn't go to the actual page I'm looking for. I'm at the point where I've now copy and pasted code from other people, from this same assignment, just to see if it would work, and none of it works. I get the same result every time. Therefore I'm wondering if I'm just totally missing something? Maybe the issue is not in views.py or urls.py etc? I'm not really sure. Any help is super appreciated. If the query matches the name of an article entry, the user should be redirected to that entry’s page. Here is one of the examples I tried and all code associated in views.py: class SearchForm(forms.Form): """ Form Class for Search Bar """ title = forms.CharField(label='', widget=forms.TextInput(attrs={ "class": "search", "placeholder": "Search"})) … -
How Can I Associate A Foreign Key Of A Django Class Model Field To A Parent's Class Field
I am creating a question and answer django model where i want to set the correct answer to an option on the same class Essentially I Want To Do Something Like This class Question(models.Model): question = models.CharField(max_length=40) options = models.ManyToManyField('Answer') correct_answer = models.ForeignKey('self.options',on_delete=models.CASCADE) Unfortunately I'm Getting Errors From Django. -
Rtl direction in TinyMce scrambles codesample
my Django-TinyMce direction has turned rtl due to my language and everything looks fine except the code sample plugin which has gotten rtl and scrambles the code. I would appreciate anyone help me figure this out. I want code sample to be ltr while everything else is rtl. Thanks in advance -
Please review my code of my first web app
I wrote my first web app. Please let me know, what should i improve. I want to write as clean code as possible. I will be greatful for any advices. App is about adding and removing tasks from list. Backend written in Django, Frontend in Sass and Javascript. Link to my code on GitHub Link to app on heroku Cheers.