Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
variable.object.get is this possible in django?
it would be better if I show this to you: @classmethod def validate_recommendation_id(cls, recommendation_id): try: Recommendation.objects.get(id=recommendation_id) except Recommendation.DoesNotExist as exception: raise ValidationError( {f"{recommendation_id}": "does not exist"} ) from exception return recommendation_i @classmethod def validate_profile_id(cls, profile_id): try: Profile.objects.get(id=profile_id) except Profile.DoesNotExist as exception: raise ValidationError({f"{profile_id}": "does not exist"}) from exception return profile_id What you see here happens in django_rest_framework serializers I was looking for implementing some sort of logic in these functions, since I do not want to keep repeating the same code over and over I could not find any information about this over net yet I wonder if there a possibility to have something like: def validate_recommendation_id(cls, value, model): try: model.objects.get(id=value) except model.DoesNotExist as exception: raise ValidationError( {f"{value}": "does not exist"} ) from exception return recommendation_i Thanks! -
How can I add a choice field in django models through a form?
I have a choices field which has a set of limited number of choices like: class Choices(models.Model): name = models.CharField(max_length=255) def __str__(self): return self.name This now is a foreign key to another model which has some data like: class Item(models.Model): name = models.Charfield(max_length = 255) choice = models.ForeignKey(Choices, on_delete=models.CASCADE) I want that if a choice does not exist, one may be able to add a new Choice item while submitting the form and add it to the database, then the newly created choice can be used again. Please help me accordingly. -
Creating a class structure for data in a catalogue python Django
I am currently developing a fruits catalogue using Django and was wondering how I would structure and implement a python class to structure the data for the items in my catalogue I was initially using the SQLite database but was told by my teacher not to. The structure would follow somthing similar to this but I am having trouble formulating it and just need an example of how this could work and be implemented into my server item1 = My_Item_Class(‘widget’, ‘something’, ‘data’) item2 = My_Item_Class(‘thingy’, ‘content’, ‘info’) my_catalogue_list = [item1, item2] -
How to change the output of the models.ForeignKey in Django?
How can I change the output of the models.ForeignKey field in my below custom field? Custom field: class BetterForeignKey(models.ForeignKey): def to_python(self, value): print('to_python', value) return { 'id': value.id, 'name_fa': value.name_fa, 'name_en': value.name_en, } def get_db_prep_value(self, value, connection, prepared=False): print('get_db_prep_value') return super().get_db_prep_value(value, connection, prepared) def get_prep_value(self, value): print('get_prep_value') return super().get_prep_value(value) And used in the below model: class A(models.Model): ... job_title = BetterForeignKey(JobTitle, on_delete=models.CASCADE) I want to change the output of the below print(a.job_title) statement: >>> a = A.objects.filter(job_title__isnull=False).last() get_db_prep_value get_prep_value >>> print(a.job_title) Developer -
Create template/model that use static-image when model is created and a real image-URL afterwards
I have a model class myModel(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete = models.CASCADE,null=True) start_price = models.FloatField(default=0) image_url = models.URLFild(max_length=512,default="{% static 'media/wait_logo.png' %}") #Issue which should link to an initial image (wait_logo.png) when created. In views.py I have def MyView(request): user = request.user instance = myModel(user=user) if request.method == "POST": form = my_form(request.POST,instance = instance) if form.is_valid(): form.save(commit=False) . . . form.instance.image_url="some_real_image_url.com" #Update URL to real image . . . return redirect("my_site") else: form = myForm() return render(request, "my_site/my_template.html",context=context) (I know it does not matter having an initial image in the view above since the user won't see the new request before it's overwritten, but the view is just for illustration purposes) The problem I (think) I'm facing is, in the template; if I want to refer to a static image I can use <a href="{% static 'media/wait_logo.png' %} but when refering to the form-field (when it's a correct URL) it'll be <a href="{{context.image_url}}">. Simply setting default="{% static 'media/wait_logo.png' %}" does not work. How do I write my href such that it can refer to the initial-image uppon creation but also being able to show a real image URL when that is provided? I'm thinking about just uploading the wait_logo.png to our … -
How to access datatable values from a django url in my Flutter datatable?
I have a project which shows the values of volts and current etc... The actual source of the data is a Django URL, and I want to read that values in my flutter data table. How to do it... Note: I am not familiar with Django. I know only flutter & dart. Here is my Django code ss. On the left side is the code & on the right side is the output of which accessed by a URL. and here is my data table code of Flutter ```rows: [ DataRow( cells: [ DataCell( Text( 'Red', style: TextStyle( color: Colors.red, fontWeight: FontWeight.bold), ), ), DataCell( Text('$c1R1'), ), DataCell( Text('$c2R1'), ), DataCell( Text('$c3R1'), ), ], ), DataRow( cells: [ DataCell( Text( 'Blue', style: TextStyle( color: Colors.blue, fontWeight: FontWeight.bold), ), ), DataCell( Text('$c1R2'), ), DataCell( Text('$c2R2'), ), DataCell( Text('$c3R2'), ), ], ), DataRow( cells: [ DataCell( Text( 'Yellow', style: TextStyle( color: Colors.yellow, fontWeight: FontWeight.bold), ), ), DataCell( Text('$c1R3'), ), DataCell( Text('$c2R3'), ), DataCell( Text('$c3R3'), ), ], ), ], ),``` Here is the output of the flutter code -
Bootstrap dropdown in each table row where the page refresh every five seconds not opening for a single record, but opens for multiple records Why?
I have a bootstrap dropdown, inside each table row cell. The page refresh in every five seconds. The dropdown will not open if single record appears but opens perfectly for multiple records. -
Django - Is it possible to access some content of one function from another function?
I have two functions in one of my Django-based projects, under the views.py file. Where the first function generates a view page and the second function is just returns some response based on jQuery request. Here's how they look like: First function that renders a show page: @login_required() def watchlist_details(request, iid): ... ... ... ... ... ... contracts = dict(enumerate(x.rstrip() for x in symbols)) automate = Automate() automate.init_symbol(contracts) automate.live_stream() ... ... ... ... ... ... return render(request, 'watchlist_show.html') Second function that will return some response on a jQuery call: def streaming_response(request): automate = Automate() # need to replace this with: automate = automate_of_first_function result = automate.get_stream_result() json_result = json.dumps(result) return json_result Here the problem is in the second function is, I reinitialize automate which does not have any content to generate a response. So, I need to access the method automate instance that is initialized in the watchlist_details function. As I follow function-based views in my Django apps rather than class-based views so there is no way to create a global/common variable. And I think Django does not allow the creation of more than one method in class-based views (and it is also a confusing concept for me). So my … -
'django-admin' is not recognized as an internal or external command, operable program or batch file
I have installed Django and my python path seems ok. whenever I try to create a new folder with the command line django-admin it is showing me up this message. I have tried reinstalling python but is not working. -
Django Celery - Some task messages are getting skipped
I've created a django-celery task. The task worker is hosted using supervisord. Normally whenever I call the method using celery's .delay() method a new task is received by the celery worker & immediately starts processing the same (as expected :D ) However, at frequent times this happens that we call the method using .delay() & receive no errors on main thread (where .delay was originally called). But as per the logs of the celery worker, the task never reaches it. Never seen such a behavior previously. Tried searching the docs as well as "SO" community, but can't get to why this is happening. The worker is up & free, redis-server is also up & running, after a few tries of adding new task, the worker receives the task again, without even restarting the worker. Thanks -
How would you make this interface in django? [closed]
I need to do something similar to this. What would be the best structure using classes and forms if I need to present them all together? At the time of creating a product I need: 1- add a model A. 2- Add one or more models B. 3- Add one or more models C. But I need each model to keep a key about the product. interface -
React rest-hooks authentication
I have to admit that I already asked this but it was answered correctly. But I can't still focus on how to authenticate against the backend. I have both sides: frontend (React) and backend (Django). I am reading the rest-hooks authentication documentation but I can't see how to use their resources the send the data and retrieve the token. Thanks to @LindaPaiste, "I" wrote this AuthResource.ts: import { Resource } from '@rest-hooks/rest'; import { API_URL } from '../utils/server'; export default class AuthResource extends Resource { static getFetchInit = (init: RequestInit): RequestInit => ({ ...init, credentials: 'same-origin' as const }); readonly email: string = ''; readonly password: string = ''; pk(parent?: any, key?: string | undefined): string | undefined { return; } static urlRoot = API_URL + 'auth-token/' } But, after reading the previous documentation I can't figure out which hook I should use. Is useFetcher(AuthResource.create(), { formData })? Just looking at it, you can tell is wrong..., but anyway...: import React, { useState } from 'react'; import { useFetcher } from 'rest-hooks'; import AuthResource from '../../../resources/AuthResource'; export default function LoginPage() { const create = useFetcher(AuthResource.create()); function submitForm(e: any) { e.preventDefault(); create({}, new FormData(e.target)); } return ( <div className="login-container"> <form className="login-form" … -
When I try to set the href attribute with Javascript, undesired text is added
I am developing on localhost: http://127.0.0.1:8000 When I do some search on the website, I want that if the query does not return results, the New entry button allows the creation of a new article from what has been searched in the search input. So if I search 'whatever' and there is no article called 'whatever', the button should redirect me to the creation page of the article 'whatever'. <script> $( document ).ready(function() { var newEntryUrl = window.location.hostname+":8000/wiki/_create/?slug="+"{{ search_query }}"; document.getElementById('newEntrybtn').setAttribute('href',newEntryUrl); }); </script> {% for article in articles %} {% block wiki_search_loop2 %} {% endblock %} {% empty%} There is no page created for '{{ search_query }}', would you like to create a page nowee? <a class="btn btn-success" id="newEntrybtn" role="button"><i class="fa fa-plus" aria-hidden="true"></i> New entry ({{ search_query }})</a> {% endfor %} To calculate the url to create the new article, I use this line: var newEntryUrl = window.location.hostname+":8000/wiki/_create/?slug="+"{{ search_query }}"; If I do an alert(newEntryUrl); it returns the desired result: 127.0.0.1:8000/wiki/_create/?slug=whatever However, if I click the newEntrybtn button, it redirects me to the following url: http://127.0.0.1:8000/wiki/_search/127.0.0.1:8000/wiki/_create/?slug=whatever Which is strange to me since at no time have I assigned the href attribute to the button, much less have I assigned it … -
How to Automatically Change English Typing from Korean Typing in Password Input in Django?
I'm working on Login Function using Django. I'd like to automatically change letters typed in Korean to English. For example, 가나다 -> rkskek How can I make it? I started yesterday, but still struggling with it.. Anyone could help me out!? FYI I've been trying Adding 'lang' attribute in password element -> Failed Using LoginView -> Failed -
Django iterate zip from same position in lists
first I zip all my lists just like books= zip(*bookName, *detail) the length of bookbName and detail is same, and I want to get the table like {% for bookName, detail, in books %} <tr> <td>{{bookName}}</td> <td>{{detail}}</td> </tr> {% endfor %} As I can not confirm the length of bookName and detail, I got the error message like "Need 3 values to unpack in for loop; got 5. " I tried {% for record in books %} <tr> {% for item in record %} <td>{{ item }}</td> {% endfor %} </tr> {% endfor %} but the result is get detail after all the bookname show. How can I get the table when I got first bookname then I can get the first book's detail? -
how to integrate video call and chat functionality in Django project?
i don't know whether i am violating the Stack Overflow guidelines but can anyone tell me who to integrate Video calling and Chatting functionality in a Django project. I don't want to create anything from scratch so how to use additional packages to accomplish this task? -
Django: what does new group, create mean?
I am trying to create different groups to be given different permission: new_group, created = Group.objects.get_or_create(name ='new_group') Came across this code and I just want to clarify what it means. This is my guess: I am creating a new group and that will be the name of that variable. But what does the ', created' mean? Then for the groups basically you just want to get a group and if there isnt a group you will create it. Thanks. -
django, admin jet- Problems with the same privileges of admin and staff
I designated admin menu through django-jet. settings.py JET_SIDE_MENU_ITEMS = [ { "label": _("board"), "app_label": "board", "items": [ {"name": "notice"}, {"name": "event"}, ], }, { "label": _("user"), "app_label": "users", "items": [ {"name": "user"}, {"name": "devices"}, {"name": "pushnotifications"}, {"name": "pushnotificationlogs"}, ], },] And then, I classified the member type as "manager" and called it [is_staff = true] I gave the manager access to the board app only. board_groups.py GROUPS_PERMISSIONS = { "Manager": { models.Notice: ["add", "change", "delete", "view"],} However, like the account in [super_admin], the account with the privileges of [is_staff] can see all models("label": _("board") &"label": _("user")) Is it because of the menus I prepared in the settings.py? -
How can i access to my application using IP I'm really tired
I'm working on a small project using Vue.js / Django Rest Framework I created my application, now I just want to visit my work, but I don't know which IP address I have to use in the browser to see my work, I tried everything this is my vue.config.js const BundleTracker = require("webpack-bundle-tracker"); module.exports = { publicPath: "http://0.0.0.0:8080/", outputDir: './dist/', chainWebpack: config => { config .plugin('BundleTracker') .use(BundleTracker, [{filename: './webpack-stats.json'}]) config.output .filename('bundle.js') config.optimization .splitChunks(false) config.resolve.alias .set('__STATIC__', 'static') config.devServer // the first 3 lines of the following code have been added to the configuration .public('http://127.0.0.1:8080') .host('127.0.0.1') .port(8080) .hotOnly(true) .watchOptions({poll: 1000}) .https(false) .disableHostCheck(true) .headers({"Access-Control-Allow-Origin": ["\*"]}) }, // uncomment before executing 'npm run build' // css: { // extract: { // filename: 'bundle.css', // chunkFilename: 'bundle.css', // }, // } }; I do npm run serve also I do python manage.py runserver / but when i access to the browser nothing is work -
Django app with gunicorn and container stack not running when deployed to heroku
I built a Django 3.1.0 app on my dev server (local windows machine) with postgreSQL, and I can run it perfectly well from inside a Docker container. When I deploy to heroku, I get no error, but when I click Open App (or run command heroku open -a myapp) it opens a browser window with a message as follows: Heroku | Welcome to your new app! Refer to the documentation if you need help deploying. I've tried several things, including running heroku ps which says 'no dynos on myapp'. Also tried running heroku ps:scale web=1 but to no effect. I have a Profile at the appropriate folder level, and it does not have a .txt or any other suffix. Also, it contains the following line: web: gunicorn config.wsgi --log-file - The stack is set to container on heroku. Another app deployed successfully but without using container. Another thing: when I run heroku run python manage.py migrate, or heroku run python manage.py createsuperuser, the commands seem to run forever and I have kill with CTRL-C. Not sure what's going on. Any help would be greatly appreciated. I've looked at a dozens similar threads here but my problem remains unresolved. Not sure … -
Django admin add view with custom actions (buttons)
I want to add in the admin, the possibility to approve or reject the registration of certain users. For that I want to add in the listing of these users a custom action that redirets to another view. In this other view I want to be able (as the admin) to check the info of the user and then either Approve or Reject the registration with two buttons. Having differentt logic for each choice. I've managed to the add the action in the listing, but can't seem to see the view. It automatically goes to the second step of approving. register.html {% extends "admin/base_site.html" %} {% block content %} <div id="content-main"> <form action="" method="POST"> {% csrf_token %} <fieldset class="module aligned"> {% for field in form %} <div class="form-row"> {{ field }} </div> {% endfor %} </fieldset> <div class="submit-row"> <input type="submit" class="default" value="Aprobar"> <input type="submit" class="default" value="Rechazar"> </div> </form> </div> {% endblock %} form.py class RegisterForm(forms.Form): def approve(self, student): pass def reject(self, student): pass def save(self, student): try: student.registered = True student.save() except Exception as e: error_message = str(e) self.add_error(None, error_message) raise return student admin.py @admin.register(PreRegisteredStudent) class StudentPreRegistered(StudentCommonAdmin): def check_button(self, obj): return format_html( '<a class="button" href="{}">Check</a>', reverse('check', args=[obj.pk]), ) actions = … -
Django restframework and markdownx
I want to know how to use preview of markdownx in restframework serializer. Example: I can show the preview by rendering the HTML with followings: {{form}} {{form.media}} However, Idk how to do it with {% render_form serializer %} Should i manually make a preview div in HTML and manually achieve it through ajax? -
Django Pagination Issues - Beginner
I'm making a project with Django and learning about pagination for the first time. I've read a lot of documentation so far but still can't get it to work. I don't know what I'm doing wrong. Any insight is helpful. From my understanding, this should make only 3 posts appear on the page. Instead, all of the posts appear. I want to make it so only 3 posts appear on the page at once. I don't get any errors with this. I just see all the posts on the page. views.py from .models import User, Post from django.core.paginator import Paginator def index(request): list_of_posts = Post.objects.all().order_by('id').reverse() paginator = Paginator(list_of_posts, 3) page_number = request.GET.get('page', 1) page_obj = paginator.get_page(page_number) return render(request, "network/index.html", { "list_of_posts": list_of_posts, "page_obj": page_obj }) Portion of the html for pagination: <div class="container"> <ul class="pagination justify-content-center"> {% if page_obj.has_previous %} <li class="page-item"><a href="?page=1" class="page-link">&laquo; First</a></li> <li class="page-item"><a href="?page={{ page_obj.previous_page_number }}" class="page-link">Previous</a></li> {% else %} <li class="page-item disabled"><a class="page-link">&laquo; First</a></li> <li class="page-item disabled"><a class="page-link">Previous</a></li> {% endif %} {% if page_obj.number %} <li class="page-item"><a class="page-link">{{ page_obj.number }}</a></li> {% else %} <li class="page-item"><a class="page-link">0</a></li> {% endif %} {% if page_obj.has_next %} <li class="page-item"><a href="?page={{ page_obj.next_page_number }}" class="page-link">Next</a></li> <li class="page-item"><a href="?page={{ page_obj.paginator.num_pages }}" class="page-link">Last … -
Performance difference of template logic vs. get_context_data
I am displaying a list of Bicycles. The Bicycle model has a function get_wheels that gets objects of type Wheel related to that model Bicycle instance. For each instance of Bicycle, I want to list all related Wheel objects in the template. Is it faster to call get_wheels in the get_context_data method, or is it faster to call get_wheels in the template? How I call it in the template: {% with wheels=p.get_wheels %} {% if files %} {% for w in wheels %} {{ w.store.label }} {% endfor %} {% endif %} {% endwith %} How I would call it in get_context_data: def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) bicycles = context['object_list'] for bicycle in bicycles: wheels = bicycle.get_wheels() if wheels: test.wheels = wheels return context Kind of related to Iterate over model instance field names and values in template Disclaimer: I am using Bicycles and Wheels as examples, this is not my actual use case. But I do have a model one one type that has a class function that gets the related models of type B. The question is about the speed of getting data in the template rather than in get_context_data -
pyexcel save to Django model
Having difficulties understanding the documentation for interaction between dest_initializer and dest_model? If I have a Django model like: class MyModel(Model) file = FileField() How can I write a file to an instance of this model? instance = MyModel() records = [OrderedDict([("Test Key", "Test Value")])] pyexcel.save_as( records=records, dest_model=MyModel, ...... ?????? How to write to instance.field? )