Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
telebot register_next_step_handler_by_chat_id not works in celery shared task
I have a small tg bot django project and the bot needs to send a message to users that have been inactive for over an hour and then wait for input from the user using tg_nick_or_phone_input_handler and write it to TelegramBotClientModel instance, sending more messages to chat def tg_nick_or_phone_input_handler(message): chat_id = message.chat.id bot_client = TelegramBotClientModel.objects.get(chat_id=chat_id) bot_client.phone_or_nickname = message.text bot_client.request_sent = True bot_client.save() bot.send_message( chat_id=chat_id, text='REQUEST SENT' ) bot.send_message( chat_id=chat_id, text='some message' ) import django.utils.timezone as tz from celery import shared_task from tg_funnel_bot.bot import bot from .views import tg_nick_or_phone_input_handler from .models import TelegramBotClientModel, BotMessagesSettingsModel # celery task where should register next step handler @shared_task(name='send_message_for_interrupted_dialog_after_one_hour') def send_message_for_interrupted_dialog_after_one_hour(): bot_messages_settings = BotMessagesSettingsModel.objects.all().first() inactive_for_hour_clients = TelegramBotClientModel.objects.filter( updated_at__lte=tz.now() - tz.timedelta(minutes=5), request_sent=False, message_for_one_hour_inactive_sent=False ) for inactive_client in inactive_for_hour_clients: chat_id = inactive_client.chat_id bot.send_message( chat_id=chat_id, text=bot_messages_settings.user_inactive_for_hour_message_text_first_part ) bot.send_message( chat_id=chat_id, text=bot_messages_settings.user_inactive_for_hour_message_text_second_part, reply_markup=bot_messages_settings.get_inactive_message_second_part_markup() ) bot.register_next_step_handler_by_chat_id( chat_id=chat_id, callback=tg_nick_or_phone_input_handler ) inactive_client = TelegramBotClientModel.objects.get(pk=inactive_client.pk) inactive_client.message_for_one_hour_inactive_sent = True inactive_client.save() return tz.now() bot.register_next_step_handler_by_chat_id not register handler and follow input in bot chat not processing. Maybe i cannot use bot instance in another processes, but i can send messages, so strange. Give me a hand please -
Django autogenerated models and relationships doesn't show up in model meta
I have the below code to create a Vote model for any given other model that I want to attach this relation to. from functools import lru_cache from django.contrib.auth import get_user_model from django.db import models from django.utils.translation import gettext_lazy as _ from apps.common.models.base import BaseModel from apps.common.utils import camel_to_snake @lru_cache(maxsize=None) def create_vote_class(klass): class Vote(BaseModel): class VoteType(models.IntegerChoices): UPVOTE = 1, _("Upvote") DOWNVOTE = -1, _("Downvote") user = models.ForeignKey( get_user_model(), on_delete=models.CASCADE, related_name=f"{camel_to_snake(klass.__name__)}_votes", verbose_name=_("User"), help_text=_("The voter."), ) post = models.ForeignKey( klass, on_delete=models.CASCADE, related_name=f"{camel_to_snake(klass.__name__)}_votes", verbose_name=_("Post"), help_text=_("The post this vote is for."), ) body = models.IntegerField( choices=VoteType.choices, verbose_name=_("Body"), help_text=_("The actual vote. -1 or +1"), ) def type(self): return self.get_body_display() class Meta: abstract = True app_label = klass._meta.app_label # NOQA klass_name = f"{klass.__name__}Vote" bases = (Vote,) class Meta: app_label = klass._meta.app_label # NOQA verbose_name = _(klass_name) verbose_name_plural = _(f"{klass_name}s") klass_dict = {"__module__": klass.__module__, "Meta": Meta} vote_class = (type(klass_name, bases, klass_dict) # NOQA return vote_class class VoteMaker: is_relation = True many_to_many = True def __init__(self, **kwargs): self.related_name = kwargs.get("related_name") self.vote_class_attribute_name = kwargs.get("vote_class_attribute_name") def contribute_to_class(self, cls, name): setattr(cls, self.vote_class_attribute_name, create_vote_class(cls)) setattr(cls, name, self.get_votes_field(cls)) def get_votes_field(self, cls): field = models.ManyToManyField( get_user_model(), through=create_vote_class(cls), related_name=self.related_name or f"voted_{camel_to_snake(cls.__name__)}s", verbose_name=_("Votes"), help_text=_("Votes for this post."), ) return field def votes(related_name=None, vote_class_attribute_name="vote_class"): vote_maker = VoteMaker( … -
Connecting my MySQL database ran with docker-compose to Django
I can't figure out how to get it connected. When I run the command - python manage.py check --database default I get the error below. **ERROR: django.db.utils.OperationalError: (1049, "Unknown database 'bears-local-db'") ** When I log into mysql with the CL I don't see the database when I run show databases; DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'bears-local-db', 'USER': 'user', 'PASSWORD': 'pass', 'HOST': '127.0.0.1', 'PORT': '3306' } } services: local-db: image: mysql:8.0 container_name: local-db ports: - 3308:3306 # - ${MYSQL_OUTER_PORT}:${MYSQL_INNER_PORT} network_mode: host environment: MYSQL_ROOT_PASSWORD: 'password' MYSQL_USER: 'user1' MYSQL_DATABASE: bears-local-db volumes: - ./mysql:/var/lib/mysql It took me 5 errors to get to this point so I haven't tried a whole lot but messing with the django settings. -
Django Fetch API JSON Parse Unexpected Character
I'm trying to update an upvote downvote counter with fetch api on my Django App about poop. I'm new to fetch and using this project to learn about it. It is returning the JsonResponse, but it kicks out an Error which I'm not sure how to troubleshoot. I've Followed the Basic Structure of the Fetch Tutorials, but I'm getting this strange error. I don't see what's wrong with my syntax, please help! .html this is the div counter I'm trying to replace <div class="voteCount{{poopfact.id}}">{{ poopfact.total_votes }}</div> .script here's my basic javascript, kicking out the error fetch(url, { headers:{ method: 'POST', 'Accept': 'application/json', 'X-Requested-With': 'XMLHttpRequest', 'poopfact_id':poopfact_id } }) .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.log('error')) .views this is what I'm returning, it seems successful def vote(request, poopfact_id): ... data = { "total_votes": total_votes, "value":poopfact_id } return JsonResponse(data, safe=False) console.log error I'm not sure how to troubleshoot it. Can anybody point me in the right direction? -
Django Cellery stuck as Pending
I am attempting to use celery within my django app to speed up processing time of a function and I can't get it to work correctly. I am using RabbitMQ. my tasks.py from celery import Celery from celery import shared_task,current_task from myapp.celery import app @app.task def add(x,y): for i in range(25000000): a = x+y return x+y my python code def test_multi_func(): x = 5 y = 10 i = 15 print(f"start = {time.perf_counter()}") while i > 0: g = add.delay(x,y) result = add.AsyncResult(g) i -= 1 print(result.backend) print(result.status) print(f"end = {time.perf_counter()}") print(f"g = {g.get()}") print(f"x = {x} ; y = {y}") my settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_select2', 'chartjs', 'django_material_icons', 'material', 'django_celery_results', 'celery_progress', 'django_apscheduler' ] BROKER_URL = 'django://' result_backend = 'django-db' CELERY_RESULT_BACKEND = 'django-db' result_persistent = True task_result_expires = None send_events = True CELERY_ACCEPT_CONTENT = ['json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_BROKER_URL = 'amqp://localhost' CELERY_CACHE_BACKEND = 'django-cache' CELERY_IGNORE_RESULT = False my celery.py import os from celery import Celery # Set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myapp.settings') app = Celery('myapp', backend='amqp://guest@localhost:15672/', broker='amqp://guest@localhost:15672/', include=['myapp.tasks']) app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print(f'Request: {self.request!r}') What am I doing wrong? I am have a … -
<link rel="stylesheet" type="text/css" href="{% static 'css/admin.css' %}"> Not working
When I make the website outside of Django it works perfectly fine. However, when I integrate everything in and put the CSS file in static files, it fails to load. The JavaScript file in the same folder loads perfectly fine. The files being used are: base.html, adminDash.html, admin.js, main.css, and admin.css. The admin.css file is the one specific to adminDash.html and is the one failing to load. Attached are images of all files, what the site should look like, and what it currently looks like. admin.js main.css admin.css adminDash.html base.html what it looks like outside django what it looks like inside django I have tried running it outside of the django project, changing the file location, got some friends to have a go at it, and got chatGPT to try rewriting it it. -
Django - ModelForm Change with ChoiceField
I have a ModelForm and i want to hide some fields and add help text according to values getting from the choiceField ex: if value_getting_from_the_choiceField == '1' hide_some fields in ModelForm elif value_getting_from_the_choiceField == '2' add help text to some fields -
Django Rest Framework web service - `Unsupported Media Type: /api/function_name`
I'm working on building a React (Next.js) application that will communicate with a DRF web service. The application will not be interacting with a database very much but instead sending in data to crunch with the DRF app which will return derived values for display in the React app. On a form submission, I have the following function run on the React side: (values) => { fetch(http://localhost:8000/api/testing_post/", { mode: 'no-cors', method: "POST", headers: {'Content-Type': 'application/json'}, body: JSON.stringify(values, null, 2) }).then(res => { console.log("Request complete! response:", res); }); } This posts the form data to the following view function in the DRF app: @api_view(["POST"]) @parser_classes([JSONParser]) def testing_post(request): print(dir(request)) print(request.data) return Response(status=status.HTTP_200_OK) When I run without print(request.data), everything works as expected. However, when I include this line, I get a 415 error Unsupported Media Type: /api/testing_post/ I'm confused as to why I'm receiving this message - I'm clearly setting the content type in the request; and, on the server side, am using a JSON parser. Does anyone know where the issue is stemming from? Thanks in advance! -
How to add data from an API to Django's database when i click on a button
My question is going to be split into two halves for a better understanding. First half: I'm trying to add a bunch of data that I rendered on a page from an API endpoint, to my database when I click "Add to my records", as can be seen in the image below, keeping in my mind that there are a lot more cards such as for other countries and I'm only trying to store "Date and Country" into the database: enter image description here and the second half, is after adding to the database I want to render them on another page, and if the database is empty aka the user hasn't added any data to the database yet, i want the page to show "now data to display" but if the user did, i want to render what's in the database. enter image description here Here's what I've tried so far: models.py from django.db import models class CountryData(models.Model): country = models.CharField(max_length=100) date = models.DateTimeField() def __str__(self): return self.country views.py def all_countries(request): first_response = requests.get('https://api.covid19api.com/summary').json() results = len(first_response['Countries']) my_new_list = [] for i in range(0, results): my_new_list.append(first_response['Countries'][i]) # print(my_new_list) if request.method == "POST": if request.POST.get('country') and request.POST.get('date'): added_record = CountryData() … -
How to stick the second upload file button on the same place?
I have two upload buttons. But the second upload button jumps down after submit. So I have this html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Create a Profile</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="{% static 'main/css/custom-style.css' %}" /> <link rel="stylesheet" type="text/css" href="{% static 'main/css/bootstrap.css' %}" /> </head> <body> <div class="container center"> <span class="form-inline" role="form"> <div class="inline-div"> <form class="form-inline" action="controlepunt140" method="POST" enctype="multipart/form-data"> <div class="d-grid gap-3"> <div class="form-group"> {% csrf_token %} {{ pdf_form.as_p }} </div> <div class="form-outline"> <div class="form-group"> <div class="wishlist"> <table class="paddingBetweenRows"> <tr> <th>fruit aantal </th> <th>&nbsp;&nbsp;&nbsp;fruit naam</th> <th>fruit kosten</th> <th>fruit totaal soort</th> <th>fruit totaal kosten</th> </tr> {% for value0, value1, value2, value3, value4 in content %} <tr> <td>{{ value0 }}</td> <td>{{ value1 }}</td> <td>{{ value2 }}</td> <td>{{ value3 }}</td> <td> <span {% if value4 in diff_set %} style="color: red;" {% endif %}> {{value4}}</span> </td> </span> </tr> {% endfor %} </table> </div> </div> </div> </div> </div> </span> <span class="form-inline" role="form"> <div class="inline-div"> <form class="form-inline" action="controlepunt140" method="POST" enctype="multipart/form-data"> <div class="d-grid gap-3"> <div class="form-group"> {% csrf_token %} {{ excel_form.as_p }} </div> <div class="form-outline"> <div class="form-group"> <div class="wishlist"> <table class="paddingBetweenRows"> <tr> <th>fruit kosten totaal </th> </tr> {% for value0 in content_excel %} <tr> <td> <span {% if … -
How do I customize the input format accepted by Django auth's PasswordResetView?
I'm using Django 3.1 witih Python 3.9. I'm using Django's django.contrib.auth application to manage my users. I would like to setup a reset password for my users, using Django's "PasswordResetView", but am unsure how to customize it to suit submitting a JSON request. I have created this in my urls.py file path('reset_password/', views.ResetPasswordView.as_view(), name='password_reset'), path('password-reset-confirm/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(template_name='users/password_reset_confirm.html'), name='password_reset_confirm'), path('password-reset-complete/', auth_views.PasswordResetCompleteView.as_view(template_name='users/password_reset_complete.html'), name='password_reset_complete'), Defined this in my views.py file class ResetPasswordView(SuccessMessageMixin, PasswordResetView): template_name = 'users/password_reset.html' email_template_name = 'users/password_reset_email.html' subject_template_name = 'users/password_reset_subject' success_message = "We've emailed you instructions for setting your password, " \ "if an account exists with the email you entered. You should receive them shortly." \ " If you don't receive an email, " \ "please make sure you've entered the address you registered with, and check your spam folder." success_url = reverse_lazy('users-home') and defined these in my settings.py file EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtppro.zohopro.com' EMAIL_USE_TLS = True EMAIL_PORT = 587 EMAIL_HOST_USER = str(os.getenv('EMAIL_USER')) EMAIL_HOST_PASSWORD = str(os.getenv('EMAIL_PASSWORD')) However, when I submit a POST request to my endpoint with the data {"username": "myuser@example.com"} in which "myemail@example.com" is a registered user, I get back curl: (52) Empty reply from server The specific curl request looks like the below, for what it's worth … -
Django multiple SMTP accounts
Here are the Django simple SMTP backend settings for just 1 email account EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = "mail.mysmtpserver.somewhere" EMAIL_PORT = 587 EMAIL_HOST_USER = "my@login" EMAIL_HOST_PASSWORD = "mypassword" EMAIL_USE_TLS = True How is it possible to use 2 or more email accounts on the same server instead of one? EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = "mail.mysmtpserver.somewhere" EMAIL_PORT =587 EMAIL_HOST_USER = "my@login2" EMAIL_HOST_PASSWORD = "mypassword2" EMAIL_USE_TLS = True I just need to send different emails based on the subject by different email account. I checked the Django documentation but there was nothing -
Returning celery task id to view
In my celery task, I want to calculate median of an array. My view: import myapp.tasks as tasks def my_view(request): data_arr = [[1,2], [3,4]] response = { 'median': tasks.median.delay(data_arr).id } return HttpResponse(json.dumps(response)) Here's the task file: from celery import shared_task import numpy @shared_task def median(arr): return numpy.mean(arr) When I call the view, I can get the following output: {"median": "88edea52-c60a-42a8-ad8d-799a4c7117a6"} The problem is celery outputs following error: File "/Users/tolgafiratoglu/Desktop/projects/python/nadir/process/tasks.py", line 7, in median return numpy.mean(arr).id AttributeError: 'numpy.float64' object has no attribute 'id' I understand the error, but I can't figure out how to proceed. -
put a word with white space as a variable in a sql query using .format()
I would like to know how to put a word with white space as a variable in a sql query (I use postgresql) data = "something with white space" choice = "DESC" limit = 10 def rDB(sql_request): with connection.cursor() as cursor: cursor.execute(sql_request) row = cursor.fetchall() return row queryWithFormat(data, choice, limit): return(''' SELECT col1, SUM(col2) as nb FROM Table WHERE col1 = {d} ORDER BY nb {c} LIMIT {l} '''.format(d=data, c=choice, l=limit) rDB(queryWithFormat(data, choice, limit)) django.db.utils.ProgrammingError: ERROR: syntax error on or near 'with' LINE 8: WHERE col1 = something with white ... -------------------------------^ -
how to get multiple input values in django loop (template) using javascript?
I am trying to get the value of some input field in my django template, the form is in a loop e.g {% for p in prediction %} {% endfor %}. I have this simple line to grab the id from the input field let odds = document.getElementById("odds").value Based on the fact that i have all these function in a django loop, am i not supposed to get all the odds when i console.log(odds) {% for p in prediction.prediction_data.all %} <form action="#" method="POST"> <input type="text" value="{{ p.odds }}" id="odds"> <input type="number" value="" name="amount" id="amount" onkeyup="CalculateNewBalance()"> <script> function CalculateNewBalance(){ let odds = document.getElementById("odds").value let stake_amount_input = document.getElementById("amount") console.log(odds); </script> </form> {% endfor %} [![enter image description here][1]][1] -
How to use both static files and media together
Is it possible to use both static files and media in a project? because all tutorials use only one of them. MEDIA_URL= 'media/' MEDIA_ROOT = BASE_DIR / 'media' STATIC_URL = 'static/' STATIC_ROOT = BASE_DIR / 'static/' STATICFILES_DIRS = BASE_DIR / 'static/ I wrote this to setting. How am supposed to modify urls.py? urlpatterns = [ path('admin/', admin.site.urls), path('',include('pages.urls')), path('users/',include('users.urls')), path('users/',include('django.contrib.auth.urls')), ] + static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) I wrote it this way but how should I add static urls? -
Twitter OAuth 2.0 Refresh Token Error - (invalid_request) Value passed for the token was invalid
I was running into this error while using Tweepy with OAuth 2.0 User Auth with PKCE when I tried to refresh the token via the User Handler. It was being returned when trying to call the non-production Tweepy refresh function on an expired token. -
Django channels + HTMX -> notification messages framework
I'd like to implement a notification framework for Django that uses channels/websockets and HTMX. But I don't get how to do that. Some things work, some are extremely complicated n my mind at least. Here's the code: from asgiref.sync import async_to_sync from channels.generic.websocket import WebsocketConsumer from channels.layers import get_channel_layer from django.contrib import messages from django.template.loader import get_template from medux.common.models import User class NotificationConsumer(WebsocketConsumer): def connect(self): self.user = self.scope["user"] if not self.user.is_authenticated: self.close() return # create a group "user-<username>" async_to_sync(self.channel_layer.group_add)( f"user-{self.user.username}", self.channel_name, ) self.accept() def disconnect(self, close_code): async_to_sync(self.channel_layer.group_discard)( f"user-{self.user.username}", self.channel_name, ) def notify(self, event: dict): html = get_template("common/toast.html").render( context={"message": event["message"]} ) self.send(text_data=html) <div hx-ext="ws" ws-connect="/ws/messages"> <div id="toasts" class="toast-container position-fixed bottom-0 end-0 p-3 pb-5"> {% for message in messages %} <div id="toasts" hx-swap-oob="beforeend"> <div data-toast-template class="toast align-items-center border-0 show" role="alert" aria-live="assertive" aria-atomic="true"> {# header here #} <div data-toast-body class="toast-body">{{ message }}</div> <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast" aria-label="Close"></button> </div> </div> {% endfor %} </div> </div> The client connects to the consumer, and if I write a small `self.send(text_data="foo") AFAIK, I have to send an "high level" event to the consumer with the type "notify", so the notify() method is called. So this would be a code called anywhere in a view … -
Django 403 error for static files on shared hosting using passenger_wsgi
I'm trying to get my Django app running on a shared hosting site using passenger_wsgi (following the instruction of the hosting provider). Since the app is for the main domain I installed it using this folder layout: public_html django static css js images SMC_website templates In settings.py I have: STATIC_URL = 'static/' STATICFILES_DIRS = [ '/home/xxxxxx/public_html/django/static/', '/home/xxxxxx/public_html/django/static/css', '/home/xxxxxx/public_html/django/static/js', '/home/xxxxxx/public_html/django/static/images', ] In urls.py I have: urlpatterns = [ path('admin/', admin.site.urls), re_path(r"^$", views.index, name="Home Page"), ] urlpatterns += static(settings.STATIC_URL, document_root=os.path.join(settings.BASE_DIR, 'static')) When I try out the "static(settings.STATIC_URL,document_root=os.path.join(settings.BASE_DIR, 'static'))" in the django manage.py shell I get a an empty list ([]). Not sure why, or if this is the cause of my problem. The app runs, pulls data from the database, but generates a 403 error for any content accessed from the static folders (css, js, or images). I have these folder permisisons: drwxr-x--- 2 xxxxxx xxxxxx 4096 Dec 17 18:30 css drwxr-x--- 8 xxxxxx xxxxxx 4096 Dec 17 18:30 images drwxr-x--- 3 xxxxxx xxxxxx 4096 Dec 17 18:30 js drwxr-xr-x 5 xxxxxx xxxxxx 4096 Dec 11 14:24 SMC_website drwxr-xr-x 3 xxxxxx xxxxxx 4096 Dec 11 14:24 logs -rw-r--r-- 1 xxxxxx xxxxxx 689 Dec 11 14:24 manage.py -rw-r--r-- 1 xxxxxx xxxxxx 1442 Dec … -
Django admin: reverse select foreign keys
I want to add pre-existing foreignkey items from the parent's admin. I have a "Bundle" model to hold "Product" items; many-to-one/foreignkey: models.py class Bundle(models.Model): title = models.CharField(max_length=300) class Product(models.Model): title = models.CharField(max_length=300) bundle = models.ForeignKey( 'Bundle', on_delete=models.CASCADE, null=True, blank=True, ) Below, I used StackedInline but this is for creating new products with a form: admin.py class ProductInline(admin.StackedInline): model = Product @admin.register(Bundle) class BundleAdmin(admin.ModelAdmin): inlines = [ ProductInline, ] Instead, I want to repeatedly add existing products from a dropdown/search in the Bundle section of admin. So, I make a Bundle and then add a series of Products from a dropdown / with a search. Thanks in advance. -
How to make query for some fields of the models?
I am makine business directory and i stucked in city and districts pages of business directory. I made a simple business directory. All i want three queries; Forexample category name: Manufacturing First: I want one page like this: abc.com/directory/category/slug:slug(this slug means category name)/ ( I did, i have no problem with this page. Second: City url like this abc.com/directory/category/slug:slug/(city name with slug style)/. forexample abc.com/category/manufacturing/london/ Third: District url like this abc.com/directory/category/slug:slug/(city name with slug style)/. forexample abc.com/category/manufacturing/london/southwark(district names) I only did first one and second and third made me crazy... I tried lots of things but failed... Here are my codes: models.py from django.db import models from django.urls import reverse from tinymce import models as tinymce_models # Create your models here. class City(models.Model): city = models.CharField(max_length=50) slug = models.SlugField() def __str__(self): return str(self.city) class District(models.Model): district = models.CharField(max_length=50) slug = models.SlugField() city = models.ForeignKey(City, on_delete=models.CASCADE) def __str__(self): return str(self.district) class FirmaCategory(models.Model): title = models.CharField(max_length=255) slug = models.SlugField() class Meta: verbose_name_plural = 'Firma Kategorileri' def __str__(self): return str(self.title) class Firma(models.Model): category = models.ForeignKey(FirmaCategory, related_name="Firma", on_delete=models.CASCADE) title = models.CharField(max_length=255) slug = models.SlugField() adres = tinymce_models.HTMLField() tel = tinymce_models.HTMLField() website = tinymce_models.HTMLField() email = tinymce_models.HTMLField() intro = tinymce_models.HTMLField() body = tinymce_models.HTMLField() city = … -
Rendering data from a dictionary inside json after saving data into JSONField in Django
I am working on a django project whereby I am using JSONField to save data into the database of the model. Everything works fine but I am having issues when trying to render the data into the html template. The data saved into the database is as shown below. {'degree': ['BSc','MSc'], 'designition': [ 'content writer', 'data scientist', 'systems administrator', ], 'email': 'maunarokguy@gmail.com', 'name': 'Brian Njoroge', 'phone': '+918511593595', 'skills': [ 'Python', ' C++', 'Power BI', 'Tensorflow', 'Keras', 'Pytorch', 'Scikit-Learn', 'Pandas', 'NLTK', 'OpenCv', 'Numpy', 'Matplotlib', 'Seaborn', 'Django', 'Linux', 'Docker'], 'total_exp': 3, 'university': ['gujarat university', 'wuhan university', 'egerton university']} I am looking for a way to render them such that in the html, I will have something that displays the dictionary data inside skills and university as a list. Here is the template for loop {% for skill in user.profile.json_data %} {{skill}} {% endfor %} And here is the models class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) avatar = models.ImageField(default='default.jpg', upload_to='profile_images') bio = models.TextField() resume = models.FileField('Upload Resumes', upload_to='resumes/', null=True, blank=True,default='resume.docx') json_data = models.JSONField(null=True, blank=True) Here is the views @login_required def myprofile(request, user_id): profile = Profile.objects.get(id=user_id) context = {'profile':profile} return render(request, 'user/profile.html', context) -
can not createsuperuser becuase one column (foreignkey) can not be null in django
I have started a django project with extending User model from AbstractUser to my CustomUser model which have foreign key relation with other model. When I try to create superuser with manage.py it does not create a superuser. It shows an error --> django.db.utils.IntegrityError: (1048, "Column 'cid_id' cannot be null"). Any help will be appreciated blog/models.py from django.db import models from django.utils import timezone from django.contrib.auth import get_user_model from ckeditor.fields import RichTextField # Create your models here. class Category(models.Model): cid = models.AutoField(primary_key=True) category_name = models.CharField(max_length=100) def __str__(self): return self.category_name class Post(models.Model): aid = models.AutoField(primary_key=True) image = models.ImageField(default='blog-default.png', upload_to='images/') title = models.CharField(max_length=200) # content = models.TextField() content = RichTextField() created = models.DateTimeField(default=timezone.now) author = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) cid = models.ForeignKey(Category, on_delete=models.CASCADE, verbose_name='specialization') approved = models.BooleanField('Approved', default=False) like = models.ManyToManyField(get_user_model(), related_name='likes') def __str__(self): return self.title users/model.py from django.db import models from blog.models import Category from django.contrib.auth.models import AbstractUser # Create your models here. class CustomUser(AbstractUser): cid = models.ForeignKey(Category, on_delete=models.CASCADE) profile_pic = models.ImageField(default='default_person.jpg', upload_to='profile_pics') cid in the Category model is the foreign key in the Post and CustomUser model. But when I try to createsuperuser it shows the error I mentioned above. cid can not be null for the user because when a user … -
Are there other cases which "select_for_update()" doesn't work in Django?
When using select_for_update() with update() as shown below: # "store/views.py" from django.db import transaction from .models import Person from django.http import HttpResponse @transaction.atomic def test(request): # Here # Here print(Person.objects.select_for_update().all().update(name="Tom")) # Here # Here print(Person.objects.select_for_update().filter(id=1).update(name="Tom")) return HttpResponse("Test") Only UPDATE query is run without SELECT FOR UPDATE query as shown below. *I use PostgreSQL and these logs below are the queries of PostgreSQL and you can check On PostgreSQL, how to log queries with transaction queries such as "BEGIN" and "COMMIT": While when using select_for_update() with save() as shown below: # "store/views.py" from django.db import transaction from .models import Person from django.http import HttpResponse @transaction.atomic def test(request): # Here person1 = Person.objects.select_for_update().all().first() person1.name = "Tom" person1.save() # Here # Here person2 = Person.objects.select_for_update().filter(id=1).first() person2.name = "Tom" person2.save() # Here # Here person3 = Person.objects.select_for_update().get(id=1) person3.name = "Tom" person3.save() # Here return HttpResponse("Test") SELECT FOR UPDATE query and UPDATE query are run as shown below: And, when using select_for_update() with count() as shown below: # "store/views.py" from django.db import transaction from .models import Person from django.http import HttpResponse @transaction.atomic def test(request): # Here # Here print(Person.objects.select_for_update().all().count()) # Here # Here print(Person.objects.select_for_update().filter(id=1).count()) return HttpResponse("Test") SELECT query is run instead of SELECT FOR UPDATE … -
Problem when download Python package and then install from .whl files
I want to download Python package pipy.org and move them to another machine and finally install that packages with downloaded .whl files in that machine This is requirements.txt file: amqp==5.1.1 anytree==2.8.0 asgiref==3.5.2 async-timeout==4.0.2 attrs==22.1.0 autobahn==22.7.1 Automat==22.10.0 beautifulsoup4==4.11.1 billiard==3.6.4.0 celery==5.2.7 certifi==2022.9.24 cffi==1.15.1 channels==4.0.0 channels-redis==4.0.0 charset-normalizer==2.1.1 click==8.1.3 click-didyoumean==0.3.0 click-plugins==1.1.1 click-repl==0.2.0 constantly==15.1.0 coreapi==2.3.3 coreschema==0.0.4 cryptography==38.0.3 daphne==4.0.0 Deprecated==1.2.13 Django==4.0.8 django-celery-beat==2.3.0 django-celery-results==2.4.0 django-filter==22.1 django-jalali==6.0.0 django-timezone-field==5.0 djangorestframework==3.14.0 djangorestframework-simplejwt==5.2.2 drf-yasg==1.21.4 et-xmlfile==1.1.0 gunicorn==20.1.0 h2==4.1.0 hpack==4.0.0 hyperframe==6.0.1 hyperlink==21.0.0 idna==3.4 incremental==22.10.0 inflection==0.5.1 itypes==1.2.0 jdatetime==4.1.0 Jinja2==3.1.2 kombu==5.2.4 lxml==4.9.1 MarkupSafe==2.1.1 msgpack==1.0.4 multitasking==0.0.11 numpy==1.23.3 openpyxl==3.0.10 packaging==21.3 pandas==1.5.0 pandas-datareader==0.10.0 Pillow==9.2.0 priority==1.3.0 prompt-toolkit==3.0.31 psutil==5.9.2 psycopg2==2.9.4 pyasn1==0.4.8 pyasn1-modules==0.2.8 pycparser==2.21 PyJWT==2.6.0 pyOpenSSL==22.1.0 pyparsing==3.0.9 python-crontab==2.6.0 python-dateutil==2.8.2 python-dotenv==0.21.0 pytz==2022.4 redis==4.3.4 requests==2.28.1 ruamel.yaml==0.17.21 ruamel.yaml.clib==0.2.7 service-identity==21.1.0 simplejson==3.17.6 six==1.16.0 soupsieve==2.3.2.post1 sqlparse==0.4.3 Twisted==22.10.0 txaio==22.2.1 typing_extensions==4.4.0 tzdata==2022.5 Unidecode==1.3.6 uritemplate==4.1.1 urllib3==1.26.12 vine==5.0.0 wcwidth==0.2.5 wrapt==1.14.1 yfinance==0.1.74 zope.interface==5.5.1 I did download packages with: pip download -r requirements.txt and after copy all `.whl files to traget computer, I did run this code: pip install --no-index --find-links ~/LocalPythonPackage -r requirements.txt But I got this error: ERROR: Could not find a version that satisfies the requirement MarkupSafe==2.1.1 (from versions: none) ERROR: No matching distribution found for MarkupSafe==2.1.1 I use python3.11 and Ubuntu 20.04.5 LTS in both computers. I think that, this problem is for dependencies or different in OS. Can …