Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to change Django views into Django rest framework views?
hi I'm coding a shopping cart and I write the cars session but I couldn't write the view .I searched and found a code that had the view but it was for django and had forms could you please help me to change the views into django rest framework??? actually my problem is the cart_add function in views this is the code??? #cart CART_SESSION_ID = 'cart' class Cart: def __init__(self, request): self.session = request.session cart = self.session.get(CART_SESSION_ID) if not cart: cart = self.session[CART_SESSION_ID] = {} self.cart = cart def __iter__(self): product_ids = self.cart.keys() products = Product.objects.filter(id__in=product_ids) cart = self.cart.copy() for product in products: cart[str(product.id)]['product'] = product for item in cart.values(): item['total_price'] = int(item['price']) * item['quantity'] yield item def remove(self, product): product_id = str(product.id) if product_id in self.cart: del self.cart[product_id] self.save() def add(self, product, quantity): product_id = str(product.id) if product_id not in self.cart: self.cart[product_id] = {'quantity': 0, 'price': str(product.price)} self.cart[product_id]['quantity'] += quantity self.save() def save(self): self.session.modified = True def get_total_price(self): return sum(int(item['price']) * item['quantity'] for item in self.cart.values()) def clear(self): del self.session[CART_SESSION_ID] self.save() #views.py def detail(request): cart = Cart(request) return render(request, 'cart/detail.html', {'cart':cart}) @require_POST def cart_add(request, product_id): cart = Cart(request) product = get_object_or_404(Product, id=product_id) form = CartAddForm(request.POST) if form.is_valid(): cd = … -
Send back data changed on backend
I made a POST method to send data from user input , recive it with Django views.py . Now i want to do some changes(ex. calculate return on invest) on that data and then send it again to display it on my page. Im stuck in it right now. I would really appreciate some help. views.py def valid(request): if request.is_ajax(): request_data = request.POST.getlist("invest")[0] investment = calculate_return_on_invest(request_data) return JsonResponse(investment, safe=False) script.js function ajaxdata(){ let invest = document.getElementById('investment').value; $.ajax({ method:'POST', url:'/valid/', data: { 'invest': invest, csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val() }, success: function (data){ alert("works"); }, error: function(data){ alert("doesn't work") } }); }; -
how to order by 1 in Django template
I have this Django template, which works template = '%(function)s(%(expressions)s ORDER BY "col_name")' However, I want to replace "col_name" with 1, e.g. template = '%(function)s(%(expressions)s ORDER BY 1)' This does not do the ordering properly what can I do? -
Django backend authentication with NextJS frontend form - best practices
I have an API hub that I've built in Django and a frontend end application I've built in NextJS. I'm currently working on authenticating to the Django API in Nextjs and I'm curious about best practices. Currently, the NextJS app posts the users username/password to an endpoint. This endpoint either returns the users token or the error illustrating the issue. React const login = async () => { let token = await axios.post('/api/accounts/', { email: email, password: password }).then(r => r.data.token).catch(function (error) { console.log(error) }) if (token) { router.push({ pathname: '/home/', query: { token: token }, }) } } nexjs server api/accounts export default async (req, res) => { if (req.method === 'POST') { try { // retrieve payment intent data const {data} = await axios.post('https://website/api/api-token-auth/', req.body) res.status(200).send(data) } catch (err) { res.status(500).json({ statusCode: 500, message: err.message }) } } else { res.setHeader('Allow', 'POST') res.status(405).end('Method Not Allowed') } } Django API @csrf_exempt @api_view(["POST"]) @permission_classes((AllowAny,)) def obtain_auth_token(request): email = request.data.get("email") password = request.data.get("password") if email is None or password is None: return Response({'error': 'Please provide both email and password'}, status=HTTP_400_BAD_REQUEST) user = authenticate(email=email, password=password) if not user: return Response({'error': 'Invalid Credentials'}, status=HTTP_404_NOT_FOUND) token, _ = Token.objects.get_or_create(user=user) return Response({'token': token.key}, status=HTTP_200_OK) Once … -
How to implament teacher student functionality into django?
Hi im working on a school project. I am supposed to make a teacher control panel that lets the teacher group students and stuff. How do i do such thing? Is there anything implamented in django. Also i cant just use the admin panel build into django because it should be a admin more of a like moderator. Hopefully you have some answers. -
Unable to import installed package in Python
I'm attempting to use the following Python package: https://github.com/amadeus4dev/amadeus-python I have installed it as a global package via the pip3 install amadeus command and can see that it has been installed correctly, as reported by pip3 list Despite it being installed, I am receiving the following error when trying to import it into a Django view: Unable to import 'amadeus'pylint(import-error) Troubleshooting Uninstalled the package and reinstalled using sudo pip3 install amadeus Uninstalled the package and reinstalled using python3 -m pip install amadeus Checked that the package has been installed within a directory in my system path. I'm currently all out of ideas for why it won't work for me and would be grateful if somebody had any ideas? Thank you! -
Django - running both Functional and Unit test in a single test file
I am using Django 3.1 and Python 3.6 I have an app that I want to run both functional and unit tests for, by running ./manage.py test myapp /path/to/project/myapp/test.py import os from django.test import TestCase from selenium import webdriver from django.contrib.staticfiles.testing import StaticLiveServerTestCase import time # Create your tests here. class FunctionalTestCase(StaticLiveServerTestCase): fixtures = ['user_test_data.json','foo_test_data'] @classmethod def setUpClass(cls): super().setUpClass() loc='/path/to/some/loc/' chrome_options = webdriver.ChromeOptions() chrome_options.add_argument("--disable-notifications") chrome_options.add_argument("user-data-dir=/home/morpheous/") # cls.browser = webdriver.Chrome(os.path.join(loc, 'chromedriver'), chrome_options=chrome_options) @classmethod def tearDownClass(cls): cls.browser.quit() super().tearDownClass() def test_functest_one(self): pass def test_functest_two(self): pass # Create your tests here. class UnitTestCase(TestCase): def test_some_unit_test(self): pass When I run ./manage.py test myapp It only run the functional tests and says two tests failed (as expected). How do I run BOTH the functional and unit tests? -
customizing django admin tabular inline using smart_selects chained select field
I am trying to implement dependent select field called ChainedForeignKey (dependent on another select field) using smart_selects . I have followed the documentation (https://django-smart-selects.readthedocs.io/en/latest/index.html)but they do not consider (Django admin) templates where you have no {{ form.as_p }} tag. I'm pointing this out because one of the implementation steps is to include {{ form.media.js }} tag before your {{ form.as_p }}. However django tabular inline template (located in pathtodjango\contrib\admin\templates\admin\edit_inline\tabular.html) looks as following; {% load i18n admin_urls static admin_modify %} <div class="js-inline-admin-formset inline-group" id="{{ inline_admin_formset.formset.prefix }}-group" data-inline-type="tabular" data-inline-formset="{{ inline_admin_formset.inline_formset_data }}"> <div class="tabular inline-related {% if forloop.last %}last-related{% endif %}"> {{ inline_admin_formset.formset.management_form }} <fieldset class="module {{ inline_admin_formset.classes }}"> <h2>{{ inline_admin_formset.opts.verbose_name_plural|capfirst }}</h2> {{ inline_admin_formset.formset.non_form_errors }} <table> <thead><tr> <th class="original"></th> {% for field in inline_admin_formset.fields %} {% if not field.widget.is_hidden %} <th{% if field.required %} class="required"{% endif %}>{{ field.label|capfirst }} {% if field.help_text %}&nbsp;<img src="{% static "admin/img/icon-unknown.svg" %}" class="help help-tooltip" width="10" height="10" alt="({{ field.help_text|striptags }})" title="{{ field.help_text|striptags }}">{% endif %} </th> {% endif %} {% endfor %} {% if inline_admin_formset.formset.can_delete %}<th>{% trans "Delete?" %}</th>{% endif %} </tr></thead> <tbody> {% for inline_admin_form in inline_admin_formset %} {% if inline_admin_form.form.non_field_errors %} <tr><td colspan="{{ inline_admin_form|cell_count }}">{{ inline_admin_form.form.non_field_errors }}</td></tr> {% endif %} <tr class="form-row {% cycle "row1" "row2" %} … -
Django: javascript variable intermittently not being passed (variable undefined after assignment)
I'm hoping someone can spot what I'm doing wrong here. I have a dropdown list which triggers a javascript function to change the language. It works exactly as expected maybe 19/20 times, but every so often, one variable (always the same one) is undefined after assignment. I've trapped the code with an alert statement to make sure the HTML is rendered ok on the page - it is. I flip between two languages over and over, fine then suddenly, with no changes, I get the variable undefined error. In the Django-rendered HTML: <div class="collapse navbar-collapse flex-grow-0 float-right" id="navbarNavDropdown"> <ul class="navbar-nav"> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="" id="navbarDropdownMenuLink" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> <img src="/static/ca.png" class="d-inline-block align-middle pb-1" alt="" loading="lazy"> &nbsp;Català </a> <div class="dropdown-menu" role="menu" id="language-list" aria-labelledby="navbarDropdownMenuLink"> <input type="hidden" name="csrfmiddlewaretoken" value="..."> <link rel="alternate" hreflang="es" href="http://localhost:8000/es/noticias/el_segundo_elemento" /> <a class="dropdown-item" href="/i18n/setlang/" data-language-code="es" data-next="/es/noticias/el_segundo_elemento"> <img src="/static/es.png" class="d-inline-block align-middle pb-1" alt="" loading="lazy"> &nbsp;Español </a> <link rel="alternate" hreflang="en" href="http://localhost:8000/en/news/the_second_item" /> <a class="dropdown-item" href="/i18n/setlang/" data-language-code="en" data-next="/en/news/the_second_item"> <img src="/static/en.png" class="d-inline-block align-middle pb-1" alt="" loading="lazy"> &nbsp;English </a> <link rel="alternate" hreflang="fr" href="http://localhost:8000/fr/nouvelles/le_deuxieme_element" /> <a class="dropdown-item" href="/i18n/setlang/" data-language-code="fr" data-next="/fr/nouvelles/le_deuxieme_element"> <img src="/static/fr.png" class="d-inline-block align-middle pb-1" alt="" loading="lazy"> &nbsp;Français </a> </div> </li> </ul> </div> The data-next tag is the one giving me the … -
Django REST Framework: Type Error When Trying To Update Using Nested Serializer
I am trying to use a nested serializer in Django Rest Framework. I basically want to update my instance in a single shot. When I send my response, it throws an error saying- save() got an unexpected keyword argument 'id'. I tried popping "id" but then it just repeats the same error with a different attribute. Here is my model: models.py class Language(models.Model): name = models.CharField(max_length=255) def __str__(self): return self.name def save(self, *args, **kwargs): super().save(*args, **kwargs) serializers.py from ..models import Language, Lead, Genre, Business from rest_framework import serializers class LanguageSerializer(serializers.ModelSerializer): id = serializers.IntegerField() class Meta: model = Language fields = "__all__" class LeadSerializer(serializers.ModelSerializer): id = serializers.IntegerField() language_id = LanguageSerializer(many=True) class Meta: model = Lead fields = "__all__" def update(self, instance, validated_data): language_ids = [item['id'] for item in validated_data['language_id']] for language in instance.language_id.all(): if language.id not in language_ids: language.delete() for item in validated_data['language_id']: if item.get("id", None) is not None: lang = Language.objects.get(id=item["id"]) lang.save(**item) #This throws an error else: lang = Language.objects.create(**item) instance.language_id.add(lang) validated_data.pop("language_id") validated_data.pop("id") instance.save() return instance -
Django template simple {% block %} and {% extends '' %}
So guys, i'm trying basics from django and {% block %} statement seems not to work for some reason... this is my forms.html: <body> {% include "homepage/navbar.html" %} <div class="container-fluid"> {% block content %} {% endblock content %} </div> {% include "homepage/footer.html" %} </body> and this is my form_model.html: {% extends 'forms/forms.html' %} {% block content %} <h1>Hello world</h1> {% endblock content %} Settings.py in templates: 'DIRS': [BASE_DIR, '/homepage/' '/boards/' '/forms/' ], -
Integrity & NotNull errors for null value in DateField column, but null=True, and blank=True
I'm currently using a Django backend, with a React/Redux frontend. When I try to add a new "Day" to my database, I get: psycopg2.errors.NotNullViolation: null value in column "day_date" ... violates not-null constraint DETAIL: Failing row contains (2, null, Tu). django.db.utils.IntegrityError: null value in column "day_date" ... violates not-null constraint DETAIL: Failing row contains (2, null, Tu). This shouldn't be an issue because in my model, day_date is a DateField: class Day(models.Model): day_id = models.AutoField(primary_key=True) day_date = models.DateField(blank=True, null=True) day_str = models.CharField(max_length=30, blank=True) class Meta: db_constraints = { 'CHK_DayNotNull': 'CHECK (day_date IS NOT NULL OR day_str <> "")' } I thought maybe it was an error with my constraint, but when I deleted the constraint I get the same error. I tried playing with the inputs of the day_date field in the model; I tried all the combinations and get the same error which makes me think something is wrong with how my database is being updated. I'm using PostgreSQL for my database. I tried clearing cache. deleting all my migrations, and then running, python3 manage.py flush python3 manage.py makemigrations python3 manage.py migrate but I'm still getting the exact same error. -
How to add name attribute in dynamically generated HTML form?
I am generating a dynamic input field in my form using javascript in Django template. But on submitting the form in Django, I need the name attribute in every input field. Like this: For input field with From Area label I need a name to be something like this: fromArea-1 Similarly, For input field with To Area label I need a name to be something like this: toArea-1 Any help would be beneficial. Here is my code: function addRow() { const div = document.createElement('div'); div.className = 'card'; div.innerHTML = ` <div class="card-body"> <div class="form-group"> <label>From Area</label> <select class="form-control" id="exampleFormControlSelect1"> <option>1</option> <option>2</option> <option>3</option> <option>4</option> <option>5</option> </select> <br/> <label>To Area</label> <select class="form-control" id="exampleFormControlSelect1"> <option>1</option> <option>2</option> <option>3</option> <option>4</option> <option>5</option> </select> <br> <label>Distance</label> <input class="form-control" type="text"></input> </div> </div> `; document.getElementById('permission-wrapper').appendChild(div); } <div class="mt-4 ml-4 mr-4"> <form class="mt-4" method="post"> <div id="permission-wrapper"> <div class="card mb-2"> <div class="card-body"> <div class="form-group"> <label>From Area</label> <select class="form-control" id="exampleFormControlSelect1"> <option>1</option> <option>2</option> <option>3</option> <option>4</option> <option>5</option> </select> <br/> <label>To Area</label> <select class="form-control" id="exampleFormControlSelect1"> <option>1</option> <option>2</option> <option>3</option> <option>4</option> <option>5</option> </select> <br> <label>Distance</label> <input class="form-control" type="text"></input> </div> </div> </div> </div> <br/> <button class="btn btn-primary float-right" onClick="addRow()">Add</button> <button class="btn btn-success" type="submit">Submit</button> </form> </div> -
Herko collect static question. How do I make it run python3 manage.py collect static instead of python manage.py collect static
I have python3 installed on my virtual env, but the default python version on my laptop is 2. I run python3 ... for everything I do. Heroku runs python manage.py collectstatic, so it does not work, as my default version is python2. I want it to run python3 manage.py collectstatic. Is there a way I can do this? Also is there a way I can collecstatic files and disable heroku from doing it, so that I can manually get the static files ready for production? Please help me out here, I am very confused. -
I can access fatimatestpro.pythonanywhere.com but not fatimatestpro.pythonanywhere.com/help/
I am working on PythonAnywhere and made my first project. I am trying to access many views (HTML pages) from my views.py. Here is my project tree: emailpro --emailpro ----url.py --emailapp ----urls.py ----views.py --templates ----emailapp ------index.html ------help.html Code inside my emailpro>emailpro>urls.py is from django.conf.urls import url, include from django.contrib import admin #from emailapp import views urlpatterns = [ url(r'^admin/', admin.site.urls), #url(r'^$', views.index, name='index'), url('', include('emailapp.urls')), ] Code inside my emailpro>emailapp>urls.py is: from django.conf.urls import url from emailapp import views urlpatterns=[ url('', views.index, name='index'), url(r'^help/$', views.help, name='help'), ] Code inside my emailpro>emailapp>views.py is from django.shortcuts import render #from django.http import HttpResponse # Create your views here. def index(request): my_dict={'insert_me': "Hi I am index coming from views.py"} return render(request, 'emailapp/index.html', context=my_dict) def help(request): help_dict={'help_insert': "HELP PAGE"} return render(request, 'emailapp/help.html', context=help_dict) My emailpro>templates>emailapp>index.html is <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>Index</title> </head> <body> <h1>Index page</h1> {{ insert_me }} </body> </html> Code inside my emailpro>templates>emailapp>help.html is <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title> Help </title> </head> <body> <h1>This is my Help HTML</h1> {{ help_insert }} </body> </html> Now when I run my site and access http://fatimatestpro.pythonanywhere.com/, it shows me my index.html page which means it is going inside my emailpro>emailapp>urls.py … -
Update Django Model
How to i update a certain value in the database? class Userdata(models.Model): user = models.OneToOneField(User, on_delete= models.CASCADE) faculty = models.ForeignKey(Fakultas,on_delete=models.CASCADE,default= 1) is_voted = models.BooleanField(default=False) def __str__(self):return self.user.username class Voting(models.Model): name = models.CharField(max_length=50) faculty = models.ForeignKey(Fakultas, on_delete=models.CASCADE, default=1) pic = models.CharField(max_length=50) text = models.TextField() voters = models.IntegerField() def __str__(self): return self.name My Views : def voted(response): if response.method == 'POST': id = response.POST.get['idcalon'] user = Userdata.objects.get() #get the username calon2 = Voting.objects.get() #get user selection in html user.is_voted = True calon2.voters +=1 user.save(['is_voted']) calon2.save(['voters']) I'm trying to grab the user's name and then when update the user's is_voted value to True when triggered. Then, I wanted to grab my Voting model by id, for example, I wanted to edit id = 1 So how do I do it? I've been trying to understand the documentation, but still have 0 idea how to do it. Thank you -
Docker Django database connection error: UNICODE Using encoding ASCII 'UTF-8' and UNICODE 'UTF-16LE'
I'm running into an issue with docker and django when trying to connect to a remote database (on a different server). Using Python 3.4 and django 1.9.7. I can perform runserver just fine when running locally, and can connect using tsql or pyodbc.connect() in the docker container. However, when performing runserver on the docker container for the project, here is the error I receive: [ODBC][14][1604961520.418108][SQLDriverConnectW.c][290] Entry: Connection = 0x7f48618ecba0 Window Hdl = (nil) Str In = [UID={{UID}};PWD={{password}};DRIVER=FreeTDS;SERVER={{serverIP}};DATABASE={{databaseName}};unicode_results=True;][length = 110] Str Out = (nil) Str Out Max = 0 Str Out Ptr = (nil) Completion = 0 UNICODE Using encoding ASCII 'UTF-8' and UNICODE 'UTF-16LE' This error is mentioned on https://docs.microsoft.com/en-us/sql/connect/odbc/linux-mac/known-issues-in-this-version-of-the-driver?view=sql-server-ver15 with the comment: There is more than one Driver Manager installed and your application is using the wrong one, or the Driver Manager was not built correctly. I have tried everything I can think of and feel like I'm overlooking something really obvious here, but I've had no luck figuring out this error, or if I even have more than one driver being used (and if so how to fix that). Here are other related setup files, perhaps someone will spot something or have an idea. Any help is greatly … -
Django Rest API ManyToMany on exsiting Database not working
I have a database with one table for recipes without the ingredients and one table with the ingredients each with a recipe id to reference each other. Now I don't know how to refer to the recipe id column, because at the moment (I build a rest API) it returns no ingredients. My models.py class Ingredients(models.Model): ingredientid = models.AutoField(db_column='IngredientID', primary_key=True, blank=True) recipeid = models.ForeignKey('Recipe', models.DO_NOTHING, db_column='RecipeID', blank=True, null=True, related_name='+') amount = models.CharField(blank=True, null=True, max_length=100) unit = models.CharField(blank=True, null=True, max_length=100) unit2 = models.CharField(blank=True, null=True, max_length=100) ingredient = models.CharField(db_column='Ingredient', blank=True, null=True, max_length=255) class Meta: managed = False db_table = 'Ingredients' class Recipe(models.Model): recipeid = models.AutoField(db_column='RecipeID', primary_key=True, blank=True) # Field name made lowercase. title = models.CharField(db_column='Title', blank=True, null=True, max_length=255) # Field name made lowercase. preperation = models.TextField(db_column='Preperation', blank=True, null=True) # Field name made lowercase. images = models.CharField(db_column='Images', blank=True, null=True, max_length=255) # Field name made lowercase. ingredients = models.ManyToManyField(Ingredients) class Meta: managed = True db_table = 'Recipes' If there is no issue it has to be somewhere on the api part: Serializer: class FullRecipeSerializer(serializers.ModelSerializer): ingredients = serializers.PrimaryKeyRelatedField(queryset=Ingredients.objects.all()) class Meta: model = Recipe fields = ['title','ingredients'] ViewSet: class FullRecipesView(generics.ListCreateAPIView): serializer_class = FullRecipeSerializer permission_classes = [ permissions.AllowAny ] queryset = Recipe.objects.all() I hope you understand my … -
How to setup a socket server on django?
how can i use django to create a socket server that could be able to call procedures on a python client from the server ? it has to be launched on init, so when i just add a server like this one : https://pypi.org/project/aiohttp-json-rpc/ in the __init__.py it starts the RPC server, and block django, not allowing the HTTP server to start -
Block title renders but Block content does not, on the same page
The {% block title %} is being rendered, so Test is displayed on the page, and changes when I change whatever is in there. However, no matter what I do with {% block content %}, the content does not display on the page. I would have assumed that either both of them, or none of them would display. Why would only one block type display and not the other? <!-- templates/registration/password_reset_complete.html --> {% extends 'base.html' %} {% block title %} Test {% endblock %} {% block content %} <div id="content" class="colM"> <p>We've emailed a new password to the e-mail address you submitted. You should be receiving it shortly.</p> <p> You can log in now on the <a href="{% url 'login' %}">log in page</a>.</p> <h1>Password reset sent</h1> <br class="clear"> </div> {% endblock %} -
Error 'int' object has no attribute 'get'
This one is really confusing me. I am reading a excel file into my python script. When I run the script with about 5 rows it runs perfectly. When I run it with 10 rows it gives me this error. I looked the error up and it seems the solution is to use HttpResponse. I am already using the HttpResponse. io = BytesIO() writer = ExcelWriter(io) data.to_excel(writer, 'Results', index=False) data2.to_excel(writer, 'Suggestions', index=False) writer.save() rFile = io.getvalue() response = HttpResponse(rFile ,content_type='application/ms-excel') response['Content-Disposition'] = f'attachment; filename={FilePath}.xlsx' return response return render(request, 'home.html') Here is the error Environment: Request Method: POST Request URL: http://127.0.0.1:8000/page_objects/ Django Version: 3.1.2 Python Version: 3.8.3 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "C:\Users\e0185446\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\e0185446\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\deprecation.py", line 116, in __call__ response = self.process_response(request, response) File "C:\Users\e0185446\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\middleware\clickjacking.py", line 26, in process_response if response.get('X-Frame-Options') is not None: Exception Type: AttributeError at /page_objects/ Exception Value: 'int' object has no attribute 'get' If you think any other part of my code would be useful to see let me know and I will edit it in. -
Django: grid of 5 by 5 elements on desktop on 2/3 of the width screen
I need to make a grid of images of 5 by 5 (total 25) in desktop mode, but only occupaying 2/3 of the width of the screen (this is why I first create a col-md-8) on top of evertything. However, my grid is showing 3 images in the first row, 2 images in the second row, and 3 in the last element. I thought it was because of the size of the images, but made them smaller and the layout is still the same. So I think problem is in my code: DB only has 8 elements at the moment but grid will show 25 (5 by 5) images. Code: <div class="row"> <div class="col-md-8"> <div class="row"> {% for product in products %} <div class="col-sm-4"> <img src="https://picsum.photos/100/110" style="margin-right: 5%; margin-top: 5%;"> </div> {% if forloop.counter|divisibleby:5 %} </div> <div class="row"> {% endif %} {% endfor %} </div> </div> <div class="col-md-4"></div> </div> -
Celery task can not call Channels consumer via channel_layer.send
I've been setting up a websocket for a fairly simple application. I wrote a JsonWebsocketConsumer as well as some celery tasks in order to perform some longer-running tasks (db accesses). Everything is working without error but my consumers are never getting called. Any ideas? consumers.py class NetworkCompConsumer(JsonWebsocketConsumer): def connect(self): self.accept() def disconnect(self, close_code): pass def receive_json(self, content): include = content['include'] # exclude = content['exclude'] # Reduce Dimensions of Inputs to 2, Just in Case User uploads 3D # Geojson wkb_w = WKBWriter() wkb_w.outdim = 2 include = GEOSGeometry(json.dumps(include)) include = GEOSGeometry(wkb_w.write_hex(include)) # if exclude is not None: # exclude = GEOSGeometry(json.dumps(exclude)) # exclude = GEOSGeometry(wkb_w.write_hex(include)) print("firing tasks") genPolySize.delay(include.json, None, self.channel_name) genBuildingCount.delay(include.json, None, self.channel_name) self.send_json({ "hello world": "Hi!!!" }) def polygon_area(self, event): print("poly area consumer called!!") self.send_json( {"area": event['value']} ) def building_count(self, event): print("building count consumer called!!") self.send_json( {"buildingCount": event['value']} ) tasks.py def sync_send(channelName, consumer, value): channel_layer = get_channel_layer() print(channel_layer) async_to_sync(channel_layer.send)( channelName, { "type": consumer, "value": value, } ) @shared_task def genBuildingCount(include, exclude, channelName): query_skeleton = building_count_skeleton query_skeleton = getQueryTemplate(query_skeleton, exclude is not None, False) with connections['gis_data'].cursor() as cursor: cursor.execute( query_skeleton, [include, exclude] if exclude is not None else [include]) results = cursor.fetchone() buildingCount = results[0] sync_send(channelName, "building.count", buildingCount) print("successfully completed … -
Django admin field. get value in relation field
Models.py class Student(models.Model): first_name = models.CharField(max_length=255) class Room(models.Model): room_name = models.CharField(max_length=20) student = models.OneToOneField(Student, on_delete=models.CASCADE) Admin.py class RoomAdmin(admin.ModelAdmin): model = Room fields = ('room_name', 'student__first_name',) I need to appear field "first_name" on add room admin page. So i set admin follow source code, I recived errors. ERRORS: <class 'building.admin.RoomAdmin'>: (admin.E108) The value of 'fields[1]' refers to 'student__first_name', which is not a callable, an attribute of 'RoomAdmin', or an attribute or method on 'building.Room'. Please guide or suggess for this thank you :) -
Django set ModelForm ModelChoiceField initial value in UpdateView class
There are many related questions I checked on so before posting my own, but I still can't figure this out. Using Django 2.2.x. I want the owner field of my html form to initially display only 1 username and this username has to be the current event instance owner. Being a ModelChoiceField, the field on the html form is rendered as a dropdown. This dropdown for the time being contains all the app users, since the ModelChoiceField has queryset=User.objects.all() I tried to override the get_initial() method of my UpdateView but, afaict, this has no effect on the ModelChoiceField. I'm able to set all forms.CharField() initial values though. I tried also to override the __init__ method of my class EventForm(forms.ModelForm) without luck. forms.py class EventForm(forms.ModelForm): class Meta: model = Event fields = ["customer", "owner", ...] # the helper block comes from crispy_forms extension. # It rules the form layout, allowing to specify css classes, fields order # and even adding custom buttons helper = FormHelper() helper.layout = Layout( Field('customer'), Field('owner'), ... Submit('submit', 'Update') ) customer = forms.CharField(disabled=True) owner = forms.ModelChoiceField(queryset=User.objects.all()) ... views.py class EventUpdateView(LoginRequiredMixin, UpdateView): """ this view renders the update form that allows service desk operators to update event status, …