Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
in django admin, way of creating instances for related model when adding an object.
I have below models: product, category, margin, cost, pricing class Product(models.Model): category = models.ForeignKey(Category, ...) class Category(models.Model): formula = models.CharField(...) #formula is goint to be something like "(cost1+fixedmargin1)*percentmargin+cost2 class Margin(models.Model): category = models.ForeignKey(Category..) margin = models.DecimalField(...) class Cost(models.Model): product = models.ForeignKey(Product...) cost_name = models.CharField(...) cost_value = models.DecimalField(...) class Pricing(models.Model): product = models.OneToOneField(Product...) price = models.DecimalField(...) def calculate(self): #collect all margins, costs and calculate the pricing formula from Category and save self.price = calculated price and In my admin, class CostInline(admin.StackedInline): class MarginInline(admin.StackedInline): class ProductAdmin(admin.ModelAdmin): inlines = (CostInline, ) class CategoryAdmin(admin.ModelAdmin): inlines = (MarginInline, ) problem occurs when I try to add a product with costs, those cost is not saved and price calculating method gets no cost but only formulas and margins(they are both pre set in Category) is there anyway when im adding a product in admin with lots of inlines and i can add and fix those related field without having to first add/save product? -
Django ManyToMany related manager with no objects returns True
Django 1.9, Python 3.6, postgres DB There exists SomeModel and SomeOtherModel, where the many-to-many relationship is defined in SomeModel. class SomeModel(models.Model): ... some_other_models = models.ManyToManyField( 'some_app.ModelB', blank=True, related_name='some_models', ) ... def some_method(self): return not self.some_other_models.some_other_method() class SomeOtherModel(models.Model): ... def some_other_method(self): ... # returns a bool, depends on condition When I am calling SomeModel.some_method() for SomeModel that has SomeOtherModel associated with it, the logic in SomeOtherModel.some_other_method() works as intended. Why is it that when I am calling SomeModel.some_method() when no SomeOtherModel are associated with SomeModel it never calls SomeOtherModel.some_other_method() and always returns True. I can check if SomeModel.some_other_models.count() is zero and return False, but I want to see if there is any better way of doing that. -
File encoding on Django deployed server
I've deployed my Django application recently to pre-set hosting server (Red Hat) and after short usage came to a UnicodeEncode Error after uploaded images, which are containing Cyrillic symbols (russian, to be specific), but saving CharFields data in russian works just fine. However, the identical code works without a flaw on my persoal computers (tested both on Ubuntu and Windows). After file encoding inspection on server it turned out, that default system encoding on hosting is ASCII At this point I've contacted tech support and they claimed that it may be Django fault, because they use UTF-8 encoding on their servers (How then sys.getfilesystemencoding() showcases, that inherited from OS encoding is ASCII?) My another suspicion were messed locales And it turned out to be true. Anyway, is there any way that it's a Django's fault and it can be fixed with Python/Django hacks, or is it completely server's fault? -
How does Django execute the SQL statement and return to queryset?
sql: "select * from user_fresher where name in (select name from user_fresher group by name having count(name)>1) and status_id=0 ORDER BY name;" I want to execute this statement in Django and return a queryset object , because I need to use it as a filter in admin Page. Executing SQL statements directly doesn't seem to get the results I want, and I've checked the official documentation and I haven't found a good solution. Can you help me solve this problem? Or can I use ORM to achieve the purpose of this SQL statement?(I want to find out a duplicate value in a field.) -
loop through json response object with python
I'm trying to loop through a json response object that contains data. I would like to loop thought the json object and extract the for keys "event-id": "market-id": "event-participant-name": the json response is as below [ { "TIMESTAMP": "2018-09-05 22:59:44.398534", "id": 900652866170042, "name": "C Suarez Navarro vs M Keys", "sport-id": 9, "start": "2018-09-05T23:10:00.000Z", "in-running-flag": false, "allow-live-betting": true, "category-id": [ 9, 399952692940010, 410468520880009, 573630974180009, 613128376040013, 643136938410012, 894084819950041 ], "status": "open", "volume": 83821.22796, "event-participants": [ { "id": 900652866280041, "event-id": 900652866170042, "participant-name": "C Suarez Navarro", "number": 1 }, { "id": 900652866290042, "event-id": 900652866170042, "participant-name": "M Keys", "number": 2 } ], "markets": [ { "live": false, "event-id": 900652866170042, "id": 900652866490041, "name": "Moneyline", "runners": [ { "withdrawn": false, "prices": [ { "available-amount": 1390.32516, "currency": "EUR", "odds-type": "DECIMAL", "odds": 3.44, "decimal-odds": 3.44, "side": "back", "exchange-type": "back-lay" }, { "available-amount": 12.22, "currency": "EUR", "odds-type": "DECIMAL", "odds": 3.36, "decimal-odds": 3.36, "side": "back", "exchange-type": "back-lay" }, { "available-amount": 38.84366, "currency": "EUR", "odds-type": "DECIMAL", "odds": 3.34, "decimal-odds": 3.34, "side": "back", "exchange-type": "back-lay" }, { "available-amount": 1843.65097, "currency": "EUR", "odds-type": "DECIMAL", "odds": 3.48, "decimal-odds": 3.48, "side": "lay", "exchange-type": "back-lay" }, { "available-amount": 27.82505, "currency": "EUR", "odds-type": "DECIMAL", "odds": 3.5, "decimal-odds": 3.5, "side": "lay", "exchange-type": "back-lay" }, { "available-amount": 11.20312, "currency": "EUR", … -
Call external API and send data back to connect to Django through forms/templates
I am trying to use Django forms to load a template. I am able able to make an external API call and get some data back. Now, I need to use some of this external data (not form inputs) and make a Model filter within Django. Is there a way to pass data from Javascript into Django forms? -
Best-case scenario for saving static files in Django project
I have a question about good practice for saving images in Django project. Let's say we have two apps inside Django project appOne and appTwo. Should I save my images for every app to the same root folder or every app should have a separate folder for images? And is there a benefit if we create a folder for images for every model inside an app (if that model saves images). I know that there's not one correct answer but there is always most useful case scenario in the long run. p.s. I came from asp.net world and I fall in love with Django and Python 💙 -
Django objects.get_or_create(): passing arguments from dictionary or list
I currently have a django management command to import CSV files, which is based on this answer. The main business is done by the following line in a loop: created = Customer.objects.get_or_create(account_no = int(row[0]), name = row[1]) However, because I have a number of different models to run this on, I wish to put the above code inside a function, and pass the attributes and row keys in from a dictionary; so I'd defnine something like: csv_columns = { 0: 'account_no', 1: 'name' } However I don't know how to run the get_or_create function based on this. I'm sure this should be simple. -
Django: ModelManager
I created a model manager that should delete the entry. I always receive the error delete() takes 1 positional argument but 2 were given. Can anyone explain to me why I get this message? view.py ReservedItem.objects.delete(order_reference) models.py class ReservedItemManager(models.Manager): def delete(order_reference): super().get_queryset().filter(order_reference=order_reference).delete() -
django: Make query with django orm
I have two models, Author and Book. I need to get all authors who have not books with Django ORM? How can I get it? class Author(models.Model): name = models.CharField(max_length=30) age = models.IntegerField() class Book(models.Model): name = models.CharField(max_length=500) author = models.ForeignKey(Author, related_name='books') I make it with 'for loop': for person in Author.objects.all(): if person.books.count() == 0: "something code" But it need to make update for objects. I try like this: Author.objects.select_related('books').values('id').annotate(books_count=Count('id')).filter(books_count=0) but nothing get, QuerySet is empty. -
graphene django with redis does not work?
I have a resolver and I gave it a key to save into django-redis, I can see the key and value inside redis but somehow the loading time is still the same. If I am doing a regular rest it will work fine but somehow graphql doesn't seem to be working properly? def resolve_search(self, info, **kwargs): redis_key = 'graphl_search' if cache.keys(redis_key): # check if key exists, if do render the value print('using redis') # this will run the second time since key exists for 3600 seconds return cache.get(redis_key) # set redis print('set redis') # this will run the first time since they key does not exist yet my_model = Model.objects.filter(slug=kwargs.get('slug')).first() cache.set(redis_key, my_model, timeout=3600) return my_model works properly and doesn't go into the rest of the block if key exists, but when I checked the time it would be the same. 1st time (5xx ms) 2nd time (5xx ms) Am I doing something wrong or that is now how to should use redis with graphql? Thanks in advance for any help or suggestions -
Django Nested Query with Aggregate.Sum()
QUESTION I have an application that will make on-line reservations for a series of weekly events. I would like to display the list of upcoming events in an html template with the number of remaining seats available in a single html page. I was able to create views to display the list of upcoming events and another view to display the number of remaining seats available but I am unable to figure out how to nest the two into a single view. Example below... HTML OUTPUT Event Title Week 1 - x amount of seats remaining for this event Event Title Week 2 - x amount of seats remainign for this event Event Title Week 3 - x amount of seats remaining for this event and so on .... MODELS class Events(models.Model): event_date = models.DateField(auto_now_add=False) event_time = models.TimeField(auto_now_add=False) event_type = models.CharField(max_length=20, choices=EVENT_TYPE) seating = models.IntegerField(default=0) title = models.CharField(max_length=200) description = models.TextField() menu = models.TextField() price = models.DecimalField(max_digits=6, decimal_places=2) publish = models.CharField(max_length=1, choices=PUBLISH_CHOICE) def __int__(self): return self.title class Reservations(models.Model): user_id = models.IntegerField(default=0) event_id = models.IntegerField(default=0) reservations = models.IntegerField(default=0) def __int__(self): return self.event VIEWS def events_view(request): events=Events.objects.filter(publish='Y').filter(event_date__gte=datetime.now()).order_by('event_date') reservation_count = Reservations.objects.aggregate(Sum('reservations')) return render(request, 'restaurant/events.html',{"events":events, "reservation_count":reservation_count, }) def make_reservation_view(request, pk): event = Events.objects.get(id=pk) seating_available … -
Managing image size in django-markdownx
Is there a way to apply CSS on the images I upload with django-markdownx? Or basically any way to dynamically adjust the size of the images posted inline with text in Django-base blog website? I've tried all the regular ways: <p style="max-width: 100%">{{ post.formatted_markdown|safe }}</p> or: <div class="card" style="max-width: 100%"> <h2><a href="">{{ post.title }}</a></h2> <h5>published: {{ post.published_date }}, by: {{ post.author }}</h5> <div><img src="{{ post.main_image.url }}"></div> <p>{{ post.formatted_markdown|safe }}</p> </div> or: <p class="markdown">{{ post.formatted_markdown|safe }}</p> with CSS related .markdown { max-width: 100% } None of these kept the image within the limits, if the raw size is wider than the screen it just goes beyond. Is it just not possible to control the size of images added via django-markdownx? Is there another solution to easily manage a blog based on Django with posts with images inline with text? -
How to architect a Group in Django Channels so that the 24 hour group_expiry time does not harm my communication?
In my infrastructure, I have a fleet of RPi devices that connect in to our webserver over a websocket. The websocket connection ideally remains open permanently and acts as the conduit where the server can push information down to the RPi device, and the RPi can send information back to the server. When the RPi device connects in to Channels, it joins a specific group based on the configuration in the connection payload. The server doesn't need to know what devices are connected because it uses the same heuristic to algorithmically determine the group name to send out information to appropriate devices, if they'd exist. The place I'm getting destroyed is the group_expiry time in channels is set to 24 hours. Additionally, the websocket timeout is also set to 24 hours. I can deal with the websocket timeout because the JavaScript code will automatically attempt a reconnection as necessary. However, when the group expires after 24 hours, my devices stop receiving the communication over the group. The net effect is that every 24 hours, I have to bounce Daphne in order to have all of the groups reset and recreated. Exactly 24 hours later, Channels purges the groups and everything … -
how to use djnago-taggit similar_objects() with Class-based views
I want to display 4 related item on my template which have the same tags as the current item. I'm using the greate package django-taggit and I have read django-taggit doc and they didn't explain how to use "similar_objects() " to make related item with Class-based views my views.py : class GameDetail(DetailView): model = Game template_name = 'core/game_detail.html' context_object_name = 'game_detail' my models.py : class Game(models.Model): name = models.CharField(max_length=140) developer = models.CharField(max_length=140) game_trailer = models.CharField(max_length=300, default="No Trailer") game_story = models.TextField(default='No Story') tags = TaggableManager() my template "game_detail.html" is very log to post it here if you just can explain how to use django-taggit in my view and how to display the related item on template I'll be grateful -
Wagtail: Intermittent CSRF Verification Error
When saving a draft, I have been getting a "CSRF verification failed. Request aborted." error. It happens only intermittently, trying a couple of times to save the draft usually works. I am running Wagtail 2.2.2 and Django 2.0.3, and I have 'django.middleware.csrf.CsrfViewMiddleware' in my settings.py file. Here is the error message: Forbidden (403) CSRF verification failed. Request aborted. Reason given for failure: CSRF token missing or incorrect. -
How to refresh a div periodically using ajax by passing id to html
I want to refresh a div using ajax, i search solution and found some but none of them pass any data in url, since i am new to ajax i could not solve it. Also the chat page belong to sender user, i assume that i can not use request.user.id in refresh function should i place it in the chat.html so i can determine id from query. Here are the codes : function refresh() { $.ajax({ url: '{% url chat user.id %}', success: function(data) {$('#refresh-chat').html(data);} setTimeout(refresh, 10000); });} $(function(){ refresh(); }); urls.py: url(r'^chat/(?P<username>\w+)/$', views.chat, name='chat') chat.html: <div id="refresh-chat"> {% for msg in messages %} <div><p>{{msg.content}}</p></div> {% endfor %} </div> error: NoReverseMatch at /chat/username/ Reverse for '' not found. '' is not a valid view function or pattern name. -
adding a key value pair to dict
In the following code I get an error at 'row[header]': for field in Document._meta.get_fields(): headers.append(field.name) docs = Document.objects.order_by('id') for doc in docs: row = {} for header in headers: if hasattr(doc, header): row[header] = getattr(doc, header) files.append(row) Python says: TypeError: list indices must be integers or slices, not str What goes wrong? Python traceback: Traceback (most recent call last): File "/home/niels/PycharmProjects/sitesv/env/lib/python3.5/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/niels/PycharmProjects/sitesv/env/lib/python3.5/site-packages/django/core/handlers/base.py", line 126, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/niels/PycharmProjects/sitesv/env/lib/python3.5/site-packages/django/core/handlers/base.py", line 124, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/niels/PycharmProjects/sitesv/files/views.py", line 87, in get_file_list row[header] = getattr(doc, header) TypeError: list indices must be integers or slices, not str -
How to generate absolute urls in Django 2 templates
I have an html template, which is used to render an email, in that template, I want to attach verification links. I am using the following code to generate the link {% url 'verify_email' token=token email=email %} but this one generates following URL instead of absolute URL. I read this SO thread How can I get the full/absolute URL (with domain) in Django? and some initial google results but all of them seems old and not working for me. TLDR: How do I generate absolute URLs in Django2 template files -
how to update selected value of the dropdown list to the database
I got values of dropdown list which is expense.id and expense_type. In database I look for expense object which has id==expense.id sent by ajax in order to update its type (expense_type). So I need to send both expense.id and expense.type to sever using ajax. I dont know how to perform in jQuery as well as html. Below is my code I got error which is "Not Found: /polls/17/project_detail/ajax/update_form/" <form action="/ajax/update_form/" method="POST" id="selection-form"> {% csrf_token %} <select id="select_dropdown"> {% for expense in expenses %} {% if project.id and expense.city %} <option value="{{expense.id}}" selected="selected">{{expense.expense_type}}</option> {% else %} <option value="{{expense.id}}">{{expense.expense_type}}</option> {% endif %} {% endfor %} </select> <td><input type="submit" value="Save"></td> </form> =====js==== $('#selection-form').on('submit', function(event) { event.preventDefault(); console.log("form_submitted"); create_post(); }); function create_post(){ console.log("update fucntion is working!"); var value = $("#select_dropdown").find(":selected").val(); var text = $("#select_dropdown option:selected").text(); $.ajax({ //url: "{% url 'update_form' %}", url: "ajax/update_form/", method: "POST", data: { "value": value, "text": text, //"pro_expense": pro_expense, //"id": valueSelected, csrfmiddlewaretoken: '{{ csrf_token }}', }, //dataType: "json", success: function(data){ console.log(data); }, error: function(error_data){ console.log("error") console.log(error_data) } }); return false; }; ====views.py===== @csrf_exempt def update_form(request): if request.method == "POST" and request.is_ajax(): value = request.POST.get('value') text = request.POST.get('text') expense = Expense.objects.get(pk = value) expense.expense_type = text expense.save() return HttpResponse({"result": "success"}, content_type="application/json") … -
Django CreateForm - redirect to itself on success
I have a page that contains a blog post, with a comment form above the list of comments, to allow users to add a comment. The blog post has the following url (where blog_id is a url parameter): /blog/<blog_id> The view function: class BlogPostView(CreateView): template_name = 'blog_post.html' form_class = BlogCommentCreationForm success_url = ??? def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) context['blog_post'] = CompanyBlogPost.objects.get(id=self.kwargs['blog_id']) return context def form_valid(self, form): form.instance.author = self.request.user form.instance.publish_datetime = dt.now() form.instance.blogpost = CompanyBlogPost.objects.get(id=self.kwargs['blog_id']) return super().form_valid(form) Firstly, is this a reasonable way of implementing this? Secondly, everything here works, aside from the success_url. The submission of the form should create the comment, and redirect to the same page. How should I define success_url? I would like to use: success_url = reverse_lazy(BlogPostView, kwargs={'blog_id': self.kwargs['blog_id']}) However, this fails, as BlogPostView is used within its own definition. -
Trying to send html email template using django 2
this is my html template:- email.html <html> <head> <style> .colored { color: blue; } #body { font-size: 14px; } </style> </head> <body> <div id='body'> <p>Hi Pierce,</p> <p class='colored'>This text is blue.</p> <p>Jerry</p> </div> </body> </html> if sending to https://temp-mail.org/en/ it renders fine all the styles and tags works properly but when send to gmail it renders the html code. on temp-mail on gmail rendering like this -
How to make web app like Viberr in Node JS
Here is the Viberr app made by Bucky Roberts. Some time ago I have watched Django tutorials from "thenewboston" channel in YouTube. There we made the Viberr app. I am concerned about whether I can make the same thing using Node JS(express and mongodb - for database). If yes can you give an instance of what kind of folders and files does that project have to contain. Hope I my question is clear. -
Error 403 on my css files from my admin panel with django 2.0
i have the following problem, my admin panel don't load CSS files and you can see like this image on the console display this messages error and have this "user:group" on my files static files and finally here my settings.py and nginx config content Settings.py """ Django settings for oasiSystem project. Generated by 'django-admin startproject' using Django 2.0.2. For more information on this file, see https://docs.djangoproject.com/en/2.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.0/ref/settings/ """ import os from datetime import datetime # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.abspath(__file__)) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '!7p2^8bz736on1%%gcm)5^s21drrqz+$-=cj35*_ie((hvyl1-' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['159.89.150.67'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'reset_migrations', 'apps.captura', 'apps.cliente', 'apps.cliente', 'apps.cotizacion', 'apps.empleado', 'apps.reportes', 'apps.sucursal', 'apps.estado', 'apps.pais', 'apps.utils', 'apps.usuario', 'apps.kernel', 'apps.sendMail', ] 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', ] ROOT_URLCONF = 'oasiSystem.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', # 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'DIRS': [os.path.join(BASE_DIR, 'templates'), os.path.join(BASE_DIR, 'templates/registration')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': … -
Missing argument "self" Pythong, web3.py
So I have am connecting to a contract, and that seems to work fine, I am trying to use this class: web3.personal.Personal from https://web3py.readthedocs.io/en/stable/web3.personal.html and I dont seem to understand what i am dong wrong... when i print(web3.personal.Personal) gives me back a class object but I cant seem to use any functions associated with this class, says I am missing "self" argument contract_abi = my_abi w3 = Web3(HTTPProvider(myurl)) myContract = w3.eth.contract(address ,abi) ref = web3.personal.Personal print(ref.newAccount(password='the-passphrase')) TypeError: newAccount() missing 1 required positional argument: 'self